Android OTP Generator

2:40 PM 0 Comments

OTP(One time password)

one-time password (OTP) is a password that is valid for only one login session or transaction.

Android OTP Generator is a project to create OATH software tokens for the Android platform. Turning a mobile phone into a One Time Password (OTP) generation device which can be used in the place of hardware tokens.

Here i created a simple demo project on time based OTP generation.

Code snippet for OTP generattion :

public String generateOtp() {

  byte[] counter = new byte[8];
  long movingFactor = mEventCount;

  for (int i = counter.length - 1; i >= 0; i--) {
   counter[i] = (byte) (movingFactor & 0xff);
   movingFactor >>= 8;
  }

  byte[] hash = hmacSha(stringToHex(seed), counter);
  int offset = hash[hash.length - 1] & 0xf;

  int otpBinary = ((hash[offset] & 0x7f) << 24)
    | ((hash[offset + 1] & 0xff) << 16)
    | ((hash[offset + 2] & 0xff) << 8) | (hash[offset + 3] & 0xff);

  int otp = otpBinary % DIGITS_POWER[otpLength];
  String result = Integer.toString(otp);

  while (result.length() < otpLength) {
   result = "0" + result;
  }

  return result;
 }

 public static byte[] stringToHex(String hexInputString) {

  byte[] bts = new byte[hexInputString.length() / 2];

  for (int i = 0; i < bts.length; i++) {
   bts[i] = (byte) Integer.parseInt(
     hexInputString.substring(2 * i, 2 * i + 2), 16);
  }

  return bts;
 }

 private byte[] hmacSha(byte[] seed, byte[] counter) {

  try {
   Mac hmacSha1;

   try {
    hmacSha1 = Mac.getInstance("HmacSHA1");
   } catch (NoSuchAlgorithmException ex) {
    hmacSha1 = Mac.getInstance("HMAC-SHA-1");
   }

   SecretKeySpec macKey = new SecretKeySpec(seed, "RAW");
   hmacSha1.init(macKey);

   return hmacSha1.doFinal(counter);

  } catch (GeneralSecurityException ex) {
   throw new UndeclaredThrowableException(ex);
  }
 }
Here i used HMAC-SHA1 algorithm for encryption.

0 comments: