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 hexString

Running the program computes the hash and prints it in a human-readable hex format.

$ groovy sha256_hashes.groovy
sha256 this string
1af1dfa857bf1d8814fe1af8983c18080019922e557f15a8a0678ff2b9c8a95c

You 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:

  1. We import the java.security.MessageDigest class, which provides the functionality for computing hashes.

  2. We create a MessageDigest instance for SHA-256 using MessageDigest.getInstance("SHA-256").

  3. We update the digest with the byte representation of our string using digest.update(s.getBytes("UTF-8")).

  4. We finalize the hash computation and get the result as a byte array using digest.digest().

  5. 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