/** * Mereena Kurian */import java.nio.ByteBuffer;import java.security.InvalidKeyException;import java.security.Key;import java.security.NoSuchAlgorithmException;import javax.crypto.Mac;/** Generates OTP using Hmac Alogrithm but without any expiry */public class BaseGenerator { private final String algorithmUsed; private final int passwordLength; final Mac mac; private final int divisor; public static final int DEFAULT_PASSWORD_LENGTH = 4; //Algorithm used public static final String OTP_HMAC_ALGORITHM = “HmacSHA1”; public BaseGenerator() throws NoSuchAlgorithmException { this(DEFAULT_PASSWORD_LENGTH); } public BaseGenerator(final int passwordLength) throws NoSuchAlgorithmException { this(passwordLength, OTP_HMAC_ALGORITHM); } protected BaseGenerator(final int passwordLength, final String algorithm) throws NoSuchAlgorithmException { switch (passwordLength) { case 4: { this.divisor = 10_000; break; } case 6: { this.divisor = 1_000_000; break; } case 8: { this.divisor = 100_000_000; break; } default: { throw new IllegalArgumentException(“Password length must be between 4 and 8 digits.”); } } this.passwordLength = passwordLength; //initiating the algorithm mac = Mac.getInstance(algorithm); this.algorithmUsed = algorithm; } public int generateOneTimePassword(final Key key, final long counter) throws InvalidKeyException { mac.init(key); //generating actual OTP using HMAC final ByteBuffer buffer = ByteBuffer.allocate(8); buffer.putLong(0, counter); final byte hmac = mac.doFinal(buffer.array()); final int offset = hmachmac.length – 1 & 0x0f; for (int i = 0; i < 4; i++) { buffer.put(i, hmaci + offset); } final int otp = buffer.getInt(0) & 0x7fffffff; return otp % this.divisor; } public int getPasswordLength() { return this.passwordLength; } public String getAlgorithm() { return this.algorithmUsed; }}