Skip to content
This repository has been archived by the owner on Jun 17, 2024. It is now read-only.

Commit

Permalink
Merge 24cf5e2 into af3b288
Browse files Browse the repository at this point in the history
  • Loading branch information
ahjohannessen committed Mar 11, 2019
2 parents af3b288 + 24cf5e2 commit dfef508
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 4 deletions.
1 change: 0 additions & 1 deletion build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@ libraryDependencies ++= Seq(
"com.typesafe" % "config" % "1.3.3",
"io.spray" %% "spray-json" % "1.3.5",
"com.typesafe.akka" %% "akka-http-spray-json" % AkkaHttpVersion,
"org.apache.directory.studio" % "org.apache.commons.codec" % "1.8",
"joda-time" % "joda-time" % "2.10.1",
"org.joda" % "joda-convert" % "2.2.0",
"org.mockito" % "mockito-all" % "1.10.19" % Test,
Expand Down
18 changes: 15 additions & 3 deletions src/main/scala/eventstore/util/PasswordHashAlgorithm.scala
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package eventstore
package util

import java.nio.charset.StandardCharsets
import java.util.Base64

trait PasswordHashAlgorithm {
type Hash = String
type Salt = String
Expand All @@ -14,9 +17,18 @@ object PasswordHashAlgorithm {
def apply(): PasswordHashAlgorithm = Rfc2898

private object Rfc2898 extends PasswordHashAlgorithm {

private val encoder64 = Base64.getEncoder
private val decoder64 = Base64.getDecoder

private def encode64(value: Array[Byte]) =
new String(encoder64.encode(value), StandardCharsets.UTF_8)

private def decode64(value: String): Array[Byte] =
decoder64.decode(value.getBytes(StandardCharsets.UTF_8))

val random = java.security.SecureRandom.getInstance("SHA1PRNG")
val factory = javax.crypto.SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1")
val base64 = new org.apache.commons.codec.binary.Base64()

def hash(password: String): (Hash, Salt) = {
val salt = new Array[Byte](16)
Expand All @@ -25,7 +37,7 @@ object PasswordHashAlgorithm {
}
val spec = new javax.crypto.spec.PBEKeySpec(password.toCharArray, salt, 1000, 20 * 8)
val hash = factory.generateSecret(spec).getEncoded
base64.encodeToString(hash) -> base64.encodeToString(salt)
encode64(hash) -> encode64(salt)
}

def isValid(password: Password, hash: Hash, salt: Salt) = {
Expand All @@ -35,7 +47,7 @@ object PasswordHashAlgorithm {
val diff = hash.length ^ test.length
(hash zip test).foldLeft(diff) { case (d, (x, y)) => d | x ^ y } == 0
}
isValid(base64.decode(hash), base64.decode(salt))
isValid(decode64(hash), decode64(salt))
}
}
}

0 comments on commit dfef508

Please sign in to comment.