Compute SHA-1 of byte array

后端 未结 7 788
青春惊慌失措
青春惊慌失措 2020-11-29 23:02

I\'m looking for a way of getting an SHA-1 checksum with a Java byte array as the message.

Should I use a third party tool or is there something built in to the JVM

7条回答
  •  不知归路
    2020-11-29 23:33

    What about:

    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    import java.util.Formatter;
    
    public static String SHAsum(byte[] convertme) throws NoSuchAlgorithmException{
        MessageDigest md = MessageDigest.getInstance("SHA-1"); 
        return byteArray2Hex(md.digest(convertme));
    }
    
    private static String byteArray2Hex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        return formatter.toString();
    }
    

提交回复
热议问题