How to generate SHA256 hash of a string in Scala

1 Answer

0 votes
import java.security.MessageDigest
import java.math.BigInteger

object SHA256Hash {
    def generateSHA256(s: String): String = {
        val digest = MessageDigest.getInstance("SHA-256")
        val hashBytes = digest.digest(s.getBytes("UTF-8"))
        val hashString = new BigInteger(1, hashBytes).toString(16)
        
        String.format("%64s", hashString).replace(' ', '0')
    }

    def main(args: Array[String]): Unit = {
        val s = "Scala Programming"
        
        val hash = generateSHA256(s)
        
        println(s"SHA256 hash of '$s' is: $hash")
    }
}

   
   
/*
run:

SHA256 hash of 'Scala Programming' is: f566b0d353dae18861c0277a6e1a03a671eba4455fda11cf025d1753520044f9
 
*/

 



answered Feb 6, 2025 by avibootz

Related questions

...