问题
通过环顾这里以及一般的互联网,我找到了Bouncy Castle。我想使用Bouncy Castle(或其他一些免费提供的实用程序)在Java中生成一个字符串的SHA-256哈希。看看他们的文档,我似乎找不到任何我想做的好例子。这里有人可以帮帮我吗?
#1 热门回答(238 赞)
要散列字符串,请使用内置的MessageDigestclass:
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 );
}
}
在上面的代码片段中,digest
包含散列字符串,而hex
包含一个带有左零填充的十六进制ASCII字符串。
#2 热门回答(28 赞)
这已经在运行时库中实现。
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;
}
在JEE6环境中,也可以使用JAXBDataTypeConverter:
import javax.xml.bind.DatatypeConverter;
String hash = DatatypeConverter.printHexBinary(
MessageDigest.getInstance("MD5").digest("SOMESTRING".getBytes("UTF-8")));
#3 热门回答(15 赞)
你不一定需要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);
}
}
特别感谢来自这篇文章的user1452273:How to hash some string with sha256 in Java?
保持良好的工作 !