Calculate SHA-256 Hash Values

Is there any native way to calculate SHA-256 hash values? It seems that Groovy 2.5 natively supports this (Calculate MD5 And SHA Hash Values), however as far as I know Hubitat is on an earlier release.

I found this thread in which a staff member confirms that the org.codehaus.groovy.runtime.EncodingGroovyMethods library is available, but none of the methods work for me.

1 Like

I do it like this:

import java.security.MessageDigest
MessageDigest digest = MessageDigest.getInstance("SHA-256")
def sign = digest.digest(bytes)

Or
java.security.MessageDigest.getInstance("SHA-256").digest(bytes)

3 Likes

I was half way down the road of what you suggested when you replied.

Hashing is new to me, so learning as I'm going. I need to return a hex string, so I came up with the below. Perhaps this will help someone else.


import java.security.MessageDigest

private String sha256(String message) {

    // create MessageDigest object
    MessageDigest md = MessageDigest.getInstance("SHA-256")
    
    // pass data to hash
    md.update(message.getBytes())
    
    // compute message digest
    byte[] digest = md.digest()

    // convert byte array to hex string
    StringBuffer hexString = new StringBuffer()
    for (int i = 0;i<digest.length;i++) {
        hexString.append(Integer.toHexString(0xFF & digest[i]))
    }
    
    return hexString.toString();
    
}
3 Likes