如何在Erlang中获得sha256散列字符串?

5anewei6  于 2022-12-08  发布在  Erlang
关注(0)|答案(2)|浏览(186)

我试图通过sha256在Erlang中加密字符串,但我无法设法得到字符串回来。crypto:hash(sha256,somestring)给出一些二进制,我如何才能得到字符串?

mspsb9vt

mspsb9vt1#

二进制必须解码为整数,然后以十六进制形式打印:

1> io_lib:format("~64.16.0b", [binary:decode_unsigned(crypto:hash(sha256,
 "somenewstring"))]).
"abf8a5e4f99c89cabb25b4bfde8a1db5478da09bcbf4f1d9cdf90b7b5321e43c"

binary:decode_unsigned/1将整个二进制编码为一个大的big-endian无符号整数。另一种方法是将二进制模式匹配为整数:

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 <<Integer:256>>等于<<Integer:256/big-unsigned-integer>>,因为它们是默认标志)。

o8x7eapl

o8x7eapl2#

如何在Erlang中获取 *sha256散列字符串 * 的替代方法:

[ 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")]

相关问题