在 Java 中通过 SHA-256 的哈希字符串

2022-08-31 08:59:00

通过环顾这里以及整个互联网,我发现了充气城堡。我想使用Bouncy Castle(或其他一些免费提供的实用程序)在Java中生成字符串的SHA-256哈希。看着他们的文档,我似乎找不到任何我想做的事情的好例子。这里有人能帮我吗?


答案 1

若要对字符串进行哈希处理,请使用内置的 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);
  }
}

在上面的代码段中,包含哈希字符串,并包含左零填充的十六进制 ASCII 字符串。digesthex


答案 2

这已经在运行时库中实现。

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+环境中,还可以使用JAXB DataTypeConverter

import javax.xml.bind.DatatypeConverter;

String hash = DatatypeConverter.printHexBinary( 
           MessageDigest.getInstance("MD5").digest("SOMESTRING".getBytes("UTF-8")));

推荐