Reputation: 1497
I'm trying to encrypt string via sha256 in erlang, but I could not manage to get string back. crypto:hash(sha256, somestring) gives some binary, how can I get string?
Upvotes: 3
Views: 5180
Reputation:
The binary has to be decoded to an integer, and then printed in hexadecimal form:
1> io_lib:format("~64.16.0b", [binary:decode_unsigned(crypto:hash(sha256,
"somenewstring"))]).
"abf8a5e4f99c89cabb25b4bfde8a1db5478da09bcbf4f1d9cdf90b7b5321e43c"
binary:decode_unsigned/1
decodes the whole binary as one large big-endian unsigned integer. An alternative would be to pattern match the binary into an integer:
2> <<Integer:256>> = crypto:hash(sha256, "somenewstring").
<<171,248,165,228,249,156,137,202,187,37,180,191,222,138,
29,181,71,141,160,155,203,244,241,217,205,249,11,123,83,
...>>
3> Integer.
77784820141105809005227607825327585337759244421257967593474620236757179950140
4> io_lib:format("~64.16.0b", [Integer]).
"abf8a5e4f99c89cabb25b4bfde8a1db5478da09bcbf4f1d9cdf90b7b5321e43c"
(Note that <<Integer:256>>
is equivalent to <<Integer:256/big-unsigned-integer>>
since those are the default flags).
Upvotes: 11
Reputation: 26121
Alternative way how to get sha256
hashed string in Erlang:
[ element(C+1, {$0,$1,$2,$3,$4,$5,$6,$7,$8,$9,$A,$B,$C,$D,$E,$F}) || <<C:4>> <= crypto:hash(sha256,"somenewstring")]
Upvotes: 3