dev.turingcomplete.kotlinonetimepassword.RandomSecretGenerator.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of kotlin-onetimepassword Show documentation
Show all versions of kotlin-onetimepassword Show documentation
A Kotlin one-time password library to generate "Google Authenticator", "Time-based One-time Password" (TOTP) and "HMAC-based One-time Password" (HOTP) codes based on RFC 4226 and 6238.
The newest version!
package dev.turingcomplete.kotlinonetimepassword
import java.security.SecureRandom
/**
* Generator to create a secure random secret via [SecureRandom].
*/
class RandomSecretGenerator {
// -- Companion Object -------------------------------------------------------------------------------------------- //
// -- Properties -------------------------------------------------------------------------------------------------- //
private val secureRandom = SecureRandom()
// -- Initialization ---------------------------------------------------------------------------------------------- //
// -- Exposed Methods --------------------------------------------------------------------------------------------- //
/**
* Generates a secure random secret with the same length as a hash
* of the given HMAC algorithm (defined in [HmacAlgorithm.hashBytes]).
*
* @param hmacAlgorithm the HMAC algorithm from that the number of bytes is
* taken.
*/
fun createRandomSecret(hmacAlgorithm: HmacAlgorithm): ByteArray {
return createRandomSecret(hmacAlgorithm.hashBytes)
}
/**
* Generates a secure random secret with variable length.
*
* @param secretBytes the length (as number of bytes) of the generated secret.
*/
fun createRandomSecret(secretBytes: Int): ByteArray {
val randomSecret = ByteArray(secretBytes)
secureRandom.nextBytes(randomSecret)
return randomSecret
}
// -- Private Methods --------------------------------------------------------------------------------------------- //
// -- Inner Type -------------------------------------------------------------------------------------------------- //
}