0

I have some code that computes a hash of a byte array using Guava's Hashing class

private String getShaForFile(byte[] bytes) {
    return Hashing.sha256().hashBytes(bytes).toString();
}

However, a linting tool is complaining that this class is unstable, so I'd like to replace this implementation with one that uses the JDK classes (I'd rather not add a dependency like Bouncy Castle just for the sake of this one method).

Antonio Dragos
  • 1,106
  • 19
  • 31

1 Answers1

0

You can pass algorithm to MessageDigest.instance

 MessageDigest.getInstance(algorithm);

Code would be something around the lines as below:

MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] hash = md.digest(
  originalString.getBytes(StandardCharsets.UTF_8));
String sha256 = new String(Hex.encode(hash));

You can also use Apache common's API

String sha256hex = DigestUtils.sha256Hex(originalString);
Govinda Sakhare
  • 4,103
  • 5
  • 28
  • 62