Skip to content

Instantly share code, notes, and snippets.

@navicore
Last active September 15, 2022 13:58
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save navicore/6234040bbfce3aa58f866db314c07c15 to your computer and use it in GitHub Desktop.
Save navicore/6234040bbfce3aa58f866db314c07c15 to your computer and use it in GitHub Desktop.
sha256 single line function in scala

def sha256Hash(text: String) : String = java.security.MessageDigest.getInstance("SHA-256").digest(text.getBytes()).map(0xFF & ).map { "%02x".format() }.foldLeft(""){_ + _}

def sha256Hash(text: String) : String = String.format("%064x", new java.math.BigInteger(1, java.security.MessageDigest.getInstance("SHA-256").digest(text.getBytes("UTF-8"))))

verify via:

scala> sha256Hash("Rusty is a cowboy!")
res3: String = e0baa113fe0dd65bc88b4144c6b12c89f362a3617644315b48b36f668f7fa1d6
@bee-beep
Copy link

I get a different result from multiple on-line hash generators.

For example:
http://www.xorbin.com/tools/sha256-hash-calculator
Rusty is a cowboy!
e0baa113fe0dd65bc88b4144c6b12c89f362a3617644315b48b36f668f7fa1d6

@navicore
Copy link
Author

Thx @bee-beep! I think I got it now.

@dasbraja
Copy link

@navicore

here is output when I run it from scala.
e0baa113fe0dd65bc88b4144c6b12c89f362a3617644315b48b36f668f7fa1d6

@villordo
Copy link

👌🏼

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment