如何使用sha256在Java中散列一些字符串?
问题描述:
如何使用sha256在Java中散列一些字符串?有没有人知道任何免费的图书馆?
How to hash some string with sha256 in Java ? Does anybody know any free library for this ?
答
SHA-256不是一个编码 - 它是一个单向哈希。
SHA-256 isn't an "encoding" - it's a one-way hash.
您将基本将字符串转换为字节(例如使用 text.getBytes(UTF-8)
)然后哈希字节。请注意,哈希的结果也将是任意的二进制数据,如果要在字符串中表示,则应使用base64或hex ... 不要尝试使用 String(byte [],String)
构造函数。
You'd basically convert the string into bytes (e.g. using text.getBytes("UTF-8")
) and then hash the bytes. Note that the result of the hash would also be arbitrary binary data, and if you want to represent that in a string, you should use base64 or hex... don't try to use the String(byte[], String)
constructor.
eg
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(text.getBytes(StandardCharsets.UTF_8));