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


当前回答

在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);

  }
}

其他回答

这是我使用Kotlin的方法:

private fun getHashFromEmailString(email : String) : String{
    val charset = Charsets.UTF_8
    val byteArray = email.toByteArray(charset)
    val digest = MessageDigest.getInstance("SHA-256")
    val hash = digest.digest(byteArray)

    return hash.fold("", { str, it -> str + "%02x".format(it)})
}
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:

Java 10及以上版本:

public static String sha256(String text) {
    try {
        var messageDigest = MessageDigest.getInstance("SHA-256");
        var hash = messageDigest.digest(text.getBytes(StandardCharsets.UTF_8));
        
        return String.format("%064x", new BigInteger(1, hash));
    }
    catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        return null;
    }
}

Java 8:

public static String sha256(String text) {
    try {
        MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
        byte[] hash = messageDigest.digest(text.getBytes(StandardCharsets.UTF_8));
        
        return String.format("%064x", new BigInteger(1, hash));
    }
    catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        return null;
    }
}

顺便说一下,您可以使用“%064X”表示大写结果。

例子:

System.out.println(sha256("hello world 1"));

063dbf1d36387944a5f0ace625b4d3ee36b2daefd8bdaee5ede723637efb1cf4

与Linux cmd的比较:

$ echo -n 'hello world 1' | sha256sum 063 dbf1d36387944a5f0ace625b4d3ee36b2daefd8bdaee5ede723637efb1cf4 -

我认为最简单的解决方案是使用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);
    }
}