Sha256 Hashes in Scala

Here’s the translation of the SHA256 Hashes example from Go to Scala, formatted in Markdown suitable for Hugo:

Our example demonstrates how to compute SHA256 hashes in Scala. 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.

import java.security.MessageDigest
import javax.xml.bind.DatatypeConverter

object SHA256Hashes {
  def main(args: Array[String]): Unit = {
    val s = "sha256 this string"

    // Here we start with a new hash.
    val md = MessageDigest.getInstance("SHA-256")

    // update expects bytes. If you have a string s,
    // use s.getBytes to coerce it to bytes.
    md.update(s.getBytes("UTF-8"))

    // This gets the finalized hash result as a byte array.
    val bs = md.digest()

    println(s)
    println(DatatypeConverter.printHexBinary(bs).toLowerCase)
  }
}

Scala, being a JVM language, uses Java’s cryptography libraries to compute hashes. The java.security.MessageDigest class provides the functionality to compute various hash functions, including SHA256.

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

$ scala SHA256Hashes.scala
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!