How to sha256 in Java consistently with Daml

Say I have a Java String s. How do I get the string the string matching sha256 s in Daml?

Daml generally treats all strings as UTF-8 which is likely what tripped you up as Java strings are UTF-16 by default. You can find the actual implementation in the repo.

Inlining and removing Scala’isms here, you end up with this:

  String sha256(String s) throws NoSuchAlgorithmException, UnsupportedEncodingException {
      final var digest = MessageDigest.getInstance("SHA-256");
      digest.update(s.getBytes("UTF-8"));
      return HexFormat.of().formatHex(digest.digest());
  }
1 Like