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


当前回答

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;
}

其他回答

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

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

这是我用于哈希的:

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

public static String sha256(String s) {
    try {
        return DatatypeConverter.printHexBinary(MessageDigest.getInstance("SHA-256").digest(s.getBytes(StandardCharsets.UTF_8))).toLowerCase();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return null;
}

这个方法返回一个带零的左填充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 -

我通过DigestUtils跟踪Apache代码,sha256似乎默认返回java.security.MessageDigest进行计算。Apache没有实现独立的sha256解决方案。我正在寻找一个独立的实现来与java进行比较。安全库。仅供参考。