School Papers

import default: { throw new IllegalArgumentException(“Password length must

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;    private final int divisor;    public static final int DEFAULT_PASSWORD_LENGTH = 4;    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;        Mac.getInstance(algorithm);        this.algorithmUsed = algorithm;    }    public int generateOneTimePassword(final Key key, final long counter) throws InvalidKeyException {        final Mac mac;        try {            mac = Mac.getInstance(this.algorithmUsed);            mac.init(key);        } catch (final NoSuchAlgorithmException e) {            throw new RuntimeException(e);        }        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;    }}

x

Hi!
I'm Rhonda!

Would you like to get a custom essay? How about receiving a customized one?

Check it out