Created
September 4, 2017 16:18
-
-
Save tuesd4y/e1584120484ac24be9f00f3968a4787d to your computer and use it in GitHub Desktop.
kotlin password hashing helper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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