Package com.bastiaanjansen.otp
Class OTPGenerator
java.lang.Object
com.bastiaanjansen.otp.OTPGenerator
- Direct Known Subclasses:
HOTPGenerator,TOTPGenerator
Generates one-time passwords
- Author:
- Bastiaan Jansen
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionprotected static classAbstract OTP builder -
Field Summary
FieldsModifier and TypeFieldDescriptionprotected final HMACAlgorithmHashing algorithm used to generate code, defaults to SHA1protected final intNumber of digits for generated code in range 6...8, defaults to 6protected final byte[]Secret key used to generate the code, this should be a base32 string -
Constructor Summary
ConstructorsModifierConstructorDescriptionprotectedOTPGenerator(int passwordLength, HMACAlgorithm algorithm, byte[] secret) Constructs the generator with custom password length and hashing algorithm -
Method Summary
Modifier and TypeMethodDescriptionprotected StringgenerateCode(long counter) Generate a codeintbyte[]protected URIGenerate an OTPAuth URIbooleanChecks whether a code is valid for a specific counter with a delay window of 0booleanChecks whether a code is valid for a specific counter taking a delay window into account
-
Field Details
-
passwordLength
protected final int passwordLengthNumber of digits for generated code in range 6...8, defaults to 6 -
algorithm
Hashing algorithm used to generate code, defaults to SHA1 -
secret
protected final byte[] secretSecret key used to generate the code, this should be a base32 string
-
-
Constructor Details
-
OTPGenerator
Constructs the generator with custom password length and hashing algorithm- Parameters:
passwordLength- number of digits for generated code in range 6...8algorithm- HMAC hash algorithm used to hash datasecret- used to generate hash
-
-
Method Details
-
getPasswordLength
public int getPasswordLength() -
getAlgorithm
-
getSecret
public byte[] getSecret() -
verify
Checks whether a code is valid for a specific counter with a delay window of 0- Parameters:
code- an OTP codecounter- how many times time interval has passed since 1970- Returns:
- a boolean, true if code is valid, otherwise false
-
verify
Checks whether a code is valid for a specific counter taking a delay window into account- Parameters:
code- an OTP codeecounter- how many times time interval has passed since 1970delayWindow- window in which a code can still be deemed valid- Returns:
- a boolean, true if code is valid, otherwise false
-
generateCode
Generate a code- Parameters:
counter- how many times time interval has passed since 1970- Returns:
- generated OTP code
- Throws:
IllegalStateException- when hashing algorithm throws an error
-
getURI
Generate an OTPAuth URI- Parameters:
type- of OTPAuth URI: totp or hotppath- contains issuer and account namequery- items of URI- Returns:
- created OTPAuth URI
- Throws:
URISyntaxException- when URI cannot be created
-