Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to base64 encode a SHA-1 hash in Scala and Play Framework?

I would like to base64 encode a generated SHA-1 hash in Scala using Play Framework.

This works for me in Scala:

val md = java.security.MessageDigest.getInstance("SHA-1");
println(new sun.misc.BASE64Encoder().encode(md.digest("Foo".getBytes)))

But in Play Framework I get an error using:

 type encode is not a member of object sun.misc.BASE64Encoder

when using:

val md = java.security.MessageDigest.getInstance("SHA-1")
val ha = new sun.misc.BASE64Encoder.encode(md.digest(params.get("Foo").getBytes))

How can I generate a SHA-1 hash and base64 encode it using Scala and Play Framework?

like image 509
Jonas Avatar asked Jun 13 '11 14:06

Jonas


2 Answers

You seem to have forgotten a pair of parenthesis:

val md = java.security.MessageDigest.getInstance("SHA-1")
val ha = new sun.misc.BASE64Encoder().encode(md.digest(params.get("Foo").getBytes))

That should work better.

like image 55
SirDarius Avatar answered Oct 05 '22 23:10

SirDarius


Faster and cleaner with Play api :

var signature = play.api.libs.Codecs.sha1(md.digest("Foo".getBytes))

Play 2.7 (possible also older versions)

var signature = play.api.libs.Codecs.sha1("Foo")
like image 20
Régis Avatar answered Oct 06 '22 00:10

Régis