在Java中通过SHA-256哈希字符串 [英] Hash String via SHA-256 in Java
问题描述
通过环顾四周以及互联网,我找到了 Bouncy Castle 。我想使用Bouncy Castle(或其他一些免费提供的实用程序)在Java中生成一个字符串的SHA-256哈希。看看他们的文档,我似乎找不到任何我想做的好例子。这里有人可以帮帮我吗?
By looking around here as well as the internet in general, I have found Bouncy Castle. I want to use Bouncy Castle (or some other freely available utility) to generate a SHA-256 Hash of a String in Java. Looking at their documentation I can't seem to find any good examples of what I want to do. Can anybody here help me out?
推荐答案
要散列字符串,请使用内置的 MessageDigest 类:
To hash a string, use the built-in MessageDigest class:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.nio.charset.StandardCharsets;
import java.math.BigInteger;
public class CryptoHash {
public static void main(String[] args) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
String text = "Text to hash, cryptographically.";
// Change this to UTF-16 if needed
md.update(text.getBytes(StandardCharsets.UTF_8));
byte[] digest = md.digest();
String hex = String.format("%064x", new BigInteger(1, digest));
System.out.println(hex);
}
}
在上面的代码段中,摘要
包含散列字符串, hex
包含一个带有左零填充的十六进制ASCII字符串。
In the snippet above, digest
contains the hashed string and hex
contains a hexadecimal ASCII string with left zero padding.
这篇关于在Java中通过SHA-256哈希字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!