2

I found when I use a algorithm to hash text in java, I have to transfer a const value like SHA-256 into the function like this:

public static String getHashText(String passwordToHash,String algorithm) {
        String generatedPassword = null;
        try {
            MessageDigest md = MessageDigest.getInstance(algorithm);
            byte[] bytes = md.digest(passwordToHash.getBytes(StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < bytes.length; i++) {
                sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
            }
            generatedPassword = sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return generatedPassword;
    }

we should pass the const algorithm name like this:

String hashedRefreshToken = MD5Utils.getHashText(request.getRefresh_token(),"SHA-256");

I was wonder is there a system Enum for the encrypt algorithm so that I could do it like this:

String hashedRefreshToken = MD5Utils.getHashText(request.getRefresh_token(),ENCRYPT.SHA-256);

this would be more readable code, I found a class MessageDigest but that named SHA256 not SHA-256. is there any system enum for it? why did not have enum? why we need to pass a const string into?

5
  • 1
    If it were possible for MessageDigest to take an enum value, it would show up in MessageDigest documentation. There is therefore no such thing. As for "why" - ask the implementors. But I'd guess it's because the class is extensible to any algorithm that someone wants to provide. Commented Mar 16, 2022 at 12:46
  • Whether ENCRYPT.SHA_256 is more 'readable' than "SHA-256" is a matter of opinion. I do not find it so. Commented Mar 16, 2022 at 12:51
  • 2
    Side note: instead of Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1) you can simply use String.format("%02x", bytes[i]). When using JDK 17, you could replace the entire loop with String generatedPassword = HexFormat.of().formatHex(bytes); Commented Mar 16, 2022 at 13:33
  • 1
    You can have multiple providers, which contribute hashing algorithms that are not supported or required by default. Using an enum would restrict this to only the defaults include (or required) by the Java specification. Commented Mar 16, 2022 at 13:45
  • 1
    And the string doesn't have to be constant. Currently-used digest algorithms are mostly simple, but signature algorithms are usually "{hash}withRSA", "{hash}withECDSA", "{hash}withECDSAinP1363" etc where hash} varies depending on the key and/or the data -- that would be hard with an enum. Ciphers and key derivations are similar though sometimes using parameters instead of or in addition to naming, MACs and key agreements less so. Commented Mar 16, 2022 at 16:24

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.