Pages

Wednesday, January 24, 2018

Generating MD5, SHA-1, SHA-256, SHA-384, SHA-512 message digests

Just a note within sight. To generate hashes using any possible algorithms, I use digest method of a Java class:

public class MessageHash {

    static String DEFAULT_ALGORITHM = "SHA-1"; // MD5, SHA-1, SHA-256, SHA-384, SHA-512

    static String digest(String input, String algorithm) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance(algorithm);
        return HexConverter.bytesToHex(md.digest(input.getBytes()));
    }

    public static String digest(String input) {
        try {
            return digest(input, DEFAULT_ALGORITHM);
        } catch (NoSuchAlgorithmException ex) {
            throw new RuntimeException("This is impossible");
        }
    }
}

No comments:

Post a Comment