How to sha256 in Java consistently with Daml
App Development2 posts169 views1 likesLast activity Nov 2023
BE
bernhardOP
Nov 2023Say I have a Java String s. How do I get the string the string matching sha256 s in Daml?
CO
cocreature
Nov 2023Daml 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());
}