Skip to content

Instantly share code, notes, and snippets.

@tuesd4y
Created September 4, 2017 16:18
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save tuesd4y/e1584120484ac24be9f00f3968a4787d to your computer and use it in GitHub Desktop.
Save tuesd4y/e1584120484ac24be9f00f3968a4787d to your computer and use it in GitHub Desktop.
kotlin password hashing helper
//probably this should be something like a JavaEE Singleton...
object PasswordUtils {
val random = SecureRandom()
fun generateSalt(): ByteArray {
val salt = ByteArray(16)
random.nextBytes(salt)
return salt
}
fun isExpectedPassword(password: String, salt: ByteArray, expectedHash: ByteArray): Boolean {
val pwdHash = hash(password, salt)
if (pwdHash.size != expectedHash.size) return false
return pwdHash.indices.all { pwdHash[it] == expectedHash[it] }
}
fun hash(password: String, salt: ByteArray): ByteArray {
val spec = PBEKeySpec(password.toCharArray(), salt, 1000, 256)
try {
val skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1")
return skf.generateSecret(spec).encoded
} catch (e: NoSuchAlgorithmException) {
throw AssertionError("Error while hashing a password: " + e.message, e)
} catch (e: InvalidKeySpecException) {
throw AssertionError("Error while hashing a password: " + e.message, e)
} finally {
spec.clearPassword()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment