Java 中通过 SHA-256 的哈希字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3103652/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hash String via SHA-256 in Java
提问by knpwrs
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?
通过环顾四周以及整个互联网,我找到了充气城堡。我想使用 Bouncy Castle(或其他一些免费提供的实用程序)在 Java 中生成字符串的 SHA-256 哈希。查看他们的文档,我似乎找不到任何关于我想做的事情的好例子。这里有人可以帮我吗?
采纳答案by Brendan Long
To hash a string, use the built-in MessageDigestclass:
要散列字符串,请使用内置的MessageDigest类:
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);
}
}
In the snippet above, digest
contains the hashed string and hex
contains a hexadecimal ASCII string with left zero padding.
在上面的代码片段中,digest
包含散列字符串并hex
包含一个带有左零填充的十六进制 ASCII 字符串。
回答by Nikolaus Gradwohl
When using hashcodes with any jce provider you first try to get an instance of the algorithm, then update it with the data you want to be hashed and when you are finished you call digest to get the hash value.
在任何 jce 提供程序中使用哈希码时,您首先尝试获取算法的一个实例,然后用要哈希的数据更新它,完成后调用摘要来获取哈希值。
MessageDigest sha = MessageDigest.getInstance("SHA-256");
sha.update(in.getBytes());
byte[] digest = sha.digest();
you can use the digest to get a base64 or hex encoded version according to your needs
您可以根据需要使用摘要获取 base64 或十六进制编码版本
回答by stacker
This is already implemented in the runtime libs.
这已经在运行时库中实现。
public static String calc(InputStream is) {
String output;
int read;
byte[] buffer = new byte[8192];
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
while ((read = is.read(buffer)) > 0) {
digest.update(buffer, 0, read);
}
byte[] hash = digest.digest();
BigInteger bigInt = new BigInteger(1, hash);
output = bigInt.toString(16);
while ( output.length() < 32 ) {
output = "0"+output;
}
}
catch (Exception e) {
e.printStackTrace(System.err);
return null;
}
return output;
}
In a JEE6+ environment one could also use JAXB DataTypeConverter:
在 JEE6+ 环境中,还可以使用 JAXB DataTypeConverter:
import javax.xml.bind.DatatypeConverter;
String hash = DatatypeConverter.printHexBinary(
MessageDigest.getInstance("MD5").digest("SOMESTRING".getBytes("UTF-8")));
回答by Kay
return new String(Hex.encode(digest));
回答by obe6
I suppose you are using a relatively old Java Version without SHA-256. So you must add the BouncyCastle Provider to the already provided 'Security Providers' in your java version.
我想您使用的是没有 SHA-256 的相对较旧的 Java 版本。因此,您必须将 BouncyCastle 提供程序添加到您的 Java 版本中已提供的“安全提供程序”中。
// NEEDED if you are using a Java version without SHA-256
Security.addProvider(new BouncyCastleProvider());
// then go as usual
MessageDigest md = MessageDigest.getInstance("SHA-256");
String text = "my string...";
md.update(text.getBytes("UTF-8")); // or UTF-16 if needed
byte[] digest = md.digest();
回答by Shrikant Karvade
This will work with "org.bouncycastle.util.encoders.Hex" following package
这将适用于“org.bouncycastle.util.encoders.Hex”以下包
return new String(Hex.encode(digest));
Its in bouncycastle jar.
它在充气城堡罐子里。
回答by Whiplash
You don't necessarily need the BouncyCastle library. The following code shows how to do so using the Integer.toHexString function
您不一定需要 BouncyCastle 库。以下代码显示如何使用 Integer.toHexString 函数执行此操作
public static String sha256(String base) {
try{
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(base.getBytes("UTF-8"));
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < hash.length; i++) {
String hex = Integer.toHexString(0xff & hash[i]);
if(hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
} catch(Exception ex){
throw new RuntimeException(ex);
}
}
Special thanks to user1452273 from this post: How to hash some string with sha256 in Java?
特别感谢这篇文章中的 user1452273:How to hash some string with sha256 in Java?
Keep up the good work !
保持良好的工作 !
回答by Mike Dever
Java 8: Base64 available:
Java 8:Base64 可用:
MessageDigest md = MessageDigest.getInstance( "SHA-512" );
md.update( inbytes );
byte[] aMessageDigest = md.digest();
String outEncoded = Base64.getEncoder().encodeToString( aMessageDigest );
return( outEncoded );
回答by M.S.T
Using Java 8
使用 Java 8
MessageDigest digest = null;
try {
digest = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
byte[] hash = digest.digest(text.getBytes(StandardCharsets.UTF_8));
String encoded = DatatypeConverter.printHexBinary(hash);
System.out.println(encoded.toLowerCase());