Skip to content

Instantly share code, notes, and snippets.

@meiwin
Created December 3, 2012 08:18
Show Gist options
  • Save meiwin/4193601 to your computer and use it in GitHub Desktop.
Save meiwin/4193601 to your computer and use it in GitHub Desktop.
Secure Credentials
import java.io._
import java.security._
import org.apache.commons.codec.binary.Base64
object SecureCredentials {
def isValidPassword(password: String, hashedPassword: String, passKey: String) = {
try {
val theHashedPassword = hash(password, passKey)
(theHashedPassword == hashedPassword)
} catch {
case _ => false
}
}
def generatePassword(password: String) = {
val secureRandom = SecureRandom.getInstance("SHA1PRNG")
val b = Array.fill[Byte](8){0}
secureRandom.nextBytes(b)
val key = Base64.encodeBase64String(b)
val hashedPassword = hash(password, key)
(hashedPassword, key)
}
private def hash(value: String, key: String): String = {
val md = MessageDigest.getInstance("SHA-256")
md.reset()
md.update(Base64.decodeBase64(key))
Base64.encodeBase64String(md.digest(value.getBytes("UTF-8")))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment