Sha256 Hashes in Groovy
In Groovy, we can compute SHA256 hashes using the built-in java.security.MessageDigest class. SHA256 hashes are frequently used to compute short identities for binary or text blobs. For example, TLS/SSL certificates use SHA256 to compute a certificate’s signature. Here’s how to compute SHA256 hashes in Groovy:
import java.security.MessageDigest
String s = "sha256 this string"
// Create a MessageDigest instance for SHA-256
def digest = MessageDigest.getInstance("SHA-256")
// Update the digest with the byte representation of the string
digest.update(s.getBytes("UTF-8"))
// Get the hash's bytes
byte[] hashBytes = digest.digest()
// Convert the byte array to hexadecimal format
def hexString = hashBytes.encodeHex().toString()
println s
println hexStringRunning the program computes the hash and prints it in a human-readable hex format.
$ groovy sha256_hashes.groovy
sha256 this string
1af1dfa857bf1d8814fe1af8983c18080019922e557f15a8a0678ff2b9c8a95cYou can compute other hashes using a similar pattern to the one shown above. For example, to compute SHA512 hashes, you would use MessageDigest.getInstance("SHA-512").
Note that if you need cryptographically secure hashes, you should carefully research hash strength!
In this Groovy example:
We import the
java.security.MessageDigestclass, which provides the functionality for computing hashes.We create a
MessageDigestinstance for SHA-256 usingMessageDigest.getInstance("SHA-256").We update the digest with the byte representation of our string using
digest.update(s.getBytes("UTF-8")).We finalize the hash computation and get the result as a byte array using
digest.digest().We convert the byte array to a hexadecimal string for readable output.
This approach provides the same functionality as the original example, but uses Groovy’s syntax and the Java security libraries that Groovy can access.
Comments powered by Disqus