I’m working on a spray framework REST based tech demo project, and I want to securely store passwords as salted hashes in a database. I took a look around at existing projects, and couldn’t find quite what I was looking for.
The public methods createHash() and validatePassword() are for the most part the same as the Java version. Some of the private methods are quite a bit different.
slowEquals
This is an interesting method in the Java implementation. It is designed to always take the same amount of time to determine equality regardless of the length of the arrays being compared. Additionally it uses the XOR operator ^ to produce consistent branching. I suspect using XOR in Java this way is somewhat controversial, regardless I used a similar approach in my Scala implementation.
The most significant change in the Scala port is making diff immutable. The same result is achieved by folding over a range, and using an accumulator seeded by the initial test of a.length ^ b.length.
I tested the code by using it in conjunction with the existing Java implementation. Verifying that passwords created by each side were interoperable with the other. I used ScalaCheck to randomly generate a set of passwords to test.
PasswordHashTest
12345678910111213141516171819202122232425
packagescalapasswordhashimportorg.scalacheck.Genimportorg.scalacheck.Gen._importorg.scalatest.FunSuiteimportorg.scalatest.prop.GeneratorDrivenPropertyChecksimportpasswordhash.{PasswordHash=>JPasswordHash}classPasswordHashTestextendsFunSuitewithGeneratorDrivenPropertyChecks{test("hash generated from Java should validate with Scala"){forAll(identifier){(password:String)=>valh1=JPasswordHash.createHash(password)assert(PasswordHash.validatePassword(password,h1))}}test("hash generated from Scala should validate with Java"){forAll(identifier){(password:String)=>valh1=PasswordHash.createHash(password)assert(JPasswordHash.validatePassword(password,h1))}}}