Skip to content

Instantly share code, notes, and snippets.

@kali
Created October 29, 2015 13:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kali/bb51e33d7899f71396f8 to your computer and use it in GitHub Desktop.
Save kali/bb51e33d7899f71396f8 to your computer and use it in GitHub Desktop.
case class PasswordHash(salt:Array[Byte], loops:Int, hash:Array[Byte], algorithm:String, keyLength:Int) {
def hashText(plainText:String):Array[Byte] = PasswordHash.hash(plainText, salt, loops, algorithm, keyLength)
def challenge(plainText:String):Boolean = java.util.Arrays.equals(hashText(plainText), hash)
}
object PasswordHash {
def hash(plainText:String):PasswordHash = {
val algo = "PBKDF2WithHmacSHA512"
val salt = new java.security.SecureRandom().generateSeed(512/8)
val loops = 10000
val length = 512
PasswordHash(salt, loops, hash(plainText, salt, loops, algo, length), algo, length)
}
def hash(plainText:String, salt:Array[Byte], loops:Int, algorithm:String, keyLength:Int):Array[Byte] = {
val crypt = javax.crypto.SecretKeyFactory.getInstance(algorithm)
val spec = new javax.crypto.spec.PBEKeySpec(plainText.toCharArray, salt, loops, keyLength)
val h = crypt.generateSecret(spec).getEncoded
spec.clearPassword
h
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment