herd_rand.erl 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. -module(herd_rand).
  2. -export([init_crypto/0, str/1, uuid/0, md5hex/1, hex/0]).
  3. %%% module API
  4. %% sets random seed for current process
  5. -spec init_crypto() -> ok.
  6. init_crypto() ->
  7. <<A:32, B:32, C:32>> = crypto:strong_rand_bytes(12),
  8. rand:seed(exsplus, {A,B,C}),
  9. ok.
  10. %% generates random string which consists of 0-9A-Za-z chars
  11. -spec str(integer()) -> string().
  12. str(Length) ->
  13. lists:map(fun(Char) when Char > 83 -> Char + 13;
  14. (Char) when Char > 57 -> Char + 7;
  15. (Char) -> Char
  16. end,
  17. [47 + rand:uniform(109) || _ <- lists:seq(1, Length)]).
  18. %% generates UUIDs like "85b3a1cf-d003-4548-a16d-c7739c18f519"
  19. -spec uuid() -> string().
  20. uuid() ->
  21. <<R1:48, _:4, R2:12, _:2, R3:62>> = crypto:strong_rand_bytes(16),
  22. Rand =
  23. <<R1:48,
  24. 0:1, 1:1, 0:1, 0:1, % version
  25. R2:12,
  26. 1:1, 0:1, % RFC 4122
  27. R3:62>>,
  28. <<TL:32, TM:16, THV:16, CSR:8, CSL:8, N:48>> = Rand,
  29. lists:flatten(io_lib:format("~8.16.0b-~4.16.0b-~4.16.0b-~2.16.0b~2.16.0b-~12.16.0b",
  30. [TL, TM, THV, CSR, CSL, N])).
  31. %% gets md5 hash from string
  32. -spec(md5hex(string()) -> string()).
  33. md5hex(Str) ->
  34. <<Hash:128/integer>> = erlang:md5(Str),
  35. string:to_lower(integer_to_list(Hash, 16)).
  36. %% generates random md5 hash
  37. -spec hex() -> string().
  38. hex() -> md5hex(integer_to_list(erlang:phash2({os:system_time(micro_seconds), make_ref()}))).