我如何在Java中用SHA-256散列一些字符串?


当前回答

我认为最简单的解决方案是使用Apache Common Codec:

String sha256hex = org.apache.commons.codec.digest.DigestUtils.sha256Hex(stringText);   

其他回答

完整的例子哈希字符串作为另一个字符串。

public static String sha256(final String base) {
    try{
        final MessageDigest digest = MessageDigest.getInstance("SHA-256");
        final byte[] hash = digest.digest(base.getBytes("UTF-8"));
        final StringBuilder hexString = new StringBuilder();
        for (int i = 0; i < hash.length; i++) {
            final 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);
    }
}
String hashWith256(String textToHash) {
    MessageDigest digest = MessageDigest.getInstance("SHA-256");
    byte[] byteOfTextToHash = textToHash.getBytes(StandardCharsets.UTF_8);
    byte[] hashedByetArray = digest.digest(byteOfTextToHash);
    String encoded = Base64.getEncoder().encodeToString(hashedByetArray);
    return encoded;
}

这是我用于哈希的:

String pass = "password";

MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
byte hashBytes[] = messageDigest.digest(pass.getBytes(StandardCharsets.UTF_8));
BigInteger noHash = new BigInteger(1, hashBytes);
String hashStr = noHash.toString(16);

输出:5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8

在Java中,MessageDigest类用于计算加密哈希值。该类提供加密哈希函数(MD5, SHA-1和SHA-256)来查找文本的哈希值。

使用SHA-256算法的代码示例。

public void printHash(String str) throws NoSuchAlgorithmException {

MessageDigest md=MessageDigest.getInstance("SHA-256");

byte[] sha256=md.digest(str.getBytes(StandardCharsets.UTF_8));

   for(byte b : sha256){

      System.out.printf("%02x",b);

  }
}

另一个替代方案是Guava,它有一套易于使用的哈希实用程序。例如,使用SHA256作为十六进制字符串来哈希字符串,你可以简单地这样做:

final String hashed = Hashing.sha256()
        .hashString("your input", StandardCharsets.UTF_8)
        .toString();