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?
Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1)you can simply useString.format("%02x", bytes[i]). When using JDK 17, you could replace the entire loop withString generatedPassword = HexFormat.of().formatHex(bytes);