Java Code Examples for org.apache.commons.codec.binary.Base32#decode()

The following examples show how to use org.apache.commons.codec.binary.Base32#decode() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DefaultCodeGenerator.java    From java-totp with MIT License 6 votes vote down vote up
/**
 * Generate a HMAC-SHA1 hash of the counter number.
 */
private byte[] generateHash(String key, long counter) throws InvalidKeyException, NoSuchAlgorithmException {
    byte[] data = new byte[8];
    long value = counter;
    for (int i = 8; i-- > 0; value >>>= 8) {
        data[i] = (byte) value;
    }

    // Create a HMAC-SHA1 signing key from the shared key
    Base32 codec = new Base32();
    byte[] decodedKey = codec.decode(key);
    SecretKeySpec signKey = new SecretKeySpec(decodedKey, algorithm.getHmacAlgorithm());
    Mac mac = Mac.getInstance(algorithm.getHmacAlgorithm());
    mac.init(signKey);

    // Create a hash of the counter value
    return mac.doFinal(data);
}
 
Example 2
Source File: TwoFactorCodeChecker.java    From passopolis-server with GNU General Public License v3.0 6 votes vote down vote up
public static boolean checkCode(String secret, long code, long timeMsec) {
  Base32 codec = new Base32();
  byte[] decodedKey = codec.decode(secret);
  long t = (timeMsec / 1000L) / 30L;
  for (int i = -WINDOW_SIZE; i <= WINDOW_SIZE; ++i) {
    long hash;
    try {
      hash = computeHash(decodedKey, t + i);
    } catch (Exception e) {
      e.printStackTrace();
      throw new RuntimeException(e.getMessage());
    }
    if (hash == code) {
      return true;
    }
  }
  return false;
}
 
Example 3
Source File: TwoFactorTests.java    From passopolis-server with GNU General Public License v3.0 6 votes vote down vote up
/** Enables two-factor auth for testIdentity, storing parameters in twoFactorData. */
@Before
public void twoFactorTestSetup() throws Exception {
  twoFactorData = new TwoFactorTestData();

  // set secret in DB means two factor auth is enabled
  testIdentity.setTwoFactorSecret(twoFactorData.testSecret);

  // create testToken and sign it
  twoFactorData.testToken =
      GetMyPrivateKey.makeLoginTokenString(testIdentity, twoFactorData.redirectUrl, null);
  twoFactorData.testSignature = TwoFactorSigningService.signToken(twoFactorData.testToken);

  // create code as if the google authenticator had
  Base32 codec = new Base32();
  byte[] decodedKey = codec.decode(twoFactorData.testSecret);
  long t = (System.currentTimeMillis() / 1000L) / 30L;
  twoFactorData.validTimeCode = Integer.toString(TwoFactorCodeChecker.computeHash(decodedKey, t));
  twoFactorData.backupCode = "123456789";
  byte[] salt = CryptoForBackupCodes.randSaltGen();
  testIdentity.setBackup(0, CryptoForBackupCodes.digest(twoFactorData.backupCode, salt));

  manager.identityDao.update(testIdentity);
  manager.commitTransaction();
}
 
Example 4
Source File: GoogleAuthenticatorUtil.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
public boolean check_code(String secret, long code, long timeMsec) {  
    Base32 codec = new Base32();  
    byte[] decodedKey = codec.decode(secret);  
    // convert unix msec time into a 30 second "window"  
    // this is per the TOTP spec (see the RFC for details)  
    long t = (timeMsec / 1000L) / 30L;  
    // Window is used to check codes generated in the near past.  
    // You can use this value to tune how far you're willing to go.  
    for (int i = -window_size; i <= window_size; ++i) {  
        long hash;  
        try {  
            hash = verify_code(decodedKey, t + i);  
            System.out.println("hash="+hash);
            System.out.println("code="+code);
        }catch (Exception e) {  
            // Yes, this is bad form - but  
            // the exceptions thrown would be rare and a static configuration problem  
            e.printStackTrace();  
            throw new RuntimeException(e.getMessage());  
            //return false;  
        }  
        if (hash == code) {  
            return true;  
        }  
    }  
    // The validation code is invalid.  
    return false;  
}
 
Example 5
Source File: GoogleAuthenticatorUtil.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
public boolean check_code(String secret, long code, long timeMsec) {  
    Base32 codec = new Base32();  
    byte[] decodedKey = codec.decode(secret);  
    // convert unix msec time into a 30 second "window"  
    // this is per the TOTP spec (see the RFC for details)  
    long t = (timeMsec / 1000L) / 30L;  
    // Window is used to check codes generated in the near past.  
    // You can use this value to tune how far you're willing to go.  
    for (int i = -window_size; i <= window_size; ++i) {  
        long hash;  
        try {  
            hash = verify_code(decodedKey, t + i);  
            System.out.println("hash="+hash);
            System.out.println("code="+code);
        }catch (Exception e) {  
            // Yes, this is bad form - but  
            // the exceptions thrown would be rare and a static configuration problem  
            e.printStackTrace();  
            throw new RuntimeException(e.getMessage());  
            //return false;  
        }  
        if (hash == code) {  
            return true;  
        }  
    }  
    // The validation code is invalid.  
    return false;  
}
 
Example 6
Source File: CredentialData.java    From yubikit-android with Apache License 2.0 5 votes vote down vote up
/**
 * Makes sure that secret is Base32 encoded and decodes it
 *
 * @param secret string that contains Base32 encoded secret
 * @return decoded secret in byte array
 * @throws ParseUriException in case of not proper format
 */
private static byte[] decodeSecret(String secret) throws ParseUriException {
    if (secret == null) {
        throw new ParseUriException("secret must not be null");
    }
    secret = secret.toUpperCase();
    Base32 base32 = new Base32();
    if (base32.isInAlphabet(secret)) {
        return base32.decode(secret);
    }

    throw new ParseUriException("secret must be base32 encoded");
}
 
Example 7
Source File: TOTP.java    From mcg-helper with Apache License 2.0 5 votes vote down vote up
public static String getTOTPCode(String secretKey) {
    String normalizedBase32Key = secretKey.replace(" ", "").toUpperCase();
    Base32 base32 = new Base32();
    byte[] bytes = base32.decode(normalizedBase32Key);
    String hexKey = Hex.encodeHexString(bytes);
    long time = (System.currentTimeMillis() / 1000) / 30;
    String hexTime = Long.toHexString(time);
    return TOTP.generateTOTP(hexKey, hexTime, "6");

}
 
Example 8
Source File: Base32Encoder.java    From symbol-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Converts a string to a byte array.
 *
 * @param base32String The input Base32 string.
 * @return The output byte array.
 */
public static byte[] getBytes(final String base32String) {
    final Base32 codec = new Base32();
    final byte[] encodedBytes = StringEncoder.getBytes(base32String);
    if (!codec.isInAlphabet(encodedBytes, true)) {
        throw new IllegalArgumentException("malformed base32 string passed to getBytes");
    }
    return codec.decode(encodedBytes);
}
 
Example 9
Source File: GoogleAuthCode.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
/**
 * Check the code entered by the user to see if it is valid 验证code是否合法
 *
 * @param secret The users secret.
 * @param code   The code displayed on the users device
 * @param t      The time in msec (System.currentTimeMillis() for example)
 * @return
 */
public boolean check_code(String secret, long code, long timeMsec) {
    Base32 codec = new Base32();
    byte[] decodedKey = codec.decode(secret);
    // convert unix msec time into a 30 second "window"
    // this is per the TOTP spec (see the RFC for details)
    long t = (timeMsec / 1000L) / 30L;
    // Window is used to check codes generated in the near past.
    // You can use this value to tune how far you're willing to go.
    for (int i = -window_size; i <= window_size; ++i) {
        long hash;
        try {
            hash = verify_code(decodedKey, t + i);
        } catch (Exception e) {
            // Yes, this is bad form - but
            // the exceptions thrown would be rare and a static
            // configuration problem
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
            // return false;
        }
        if (hash == code) {
            return true;
        }
    }
    // The validation code is invalid.
    return false;
}
 
Example 10
Source File: GoogleAuthCode.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
/**
 * 根据密钥获取验证码
 * 返回字符串是因为数值有可能以0开头
 *
 * @param secretKey 密钥
 * @param time      第几个30秒 System.currentTimeMillis() / 1000 / 30
 */
public static String getTOTP(String secretKey, long time) {
    Base32 base32 = new Base32();
    byte[] bytes = base32.decode(secretKey.toUpperCase());
    String hexKey = Hex.encodeHexString(bytes);
    String hexTime = Long.toHexString(time);
    return TOTP.generateTOTP(hexKey, hexTime, "6");
}
 
Example 11
Source File: GoogleAuthCode.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
/**
 * Check the code entered by the user to see if it is valid 验证code是否合法
 *
 * @param secret The users secret.
 * @param code   The code displayed on the users device
 * @param t      The time in msec (System.currentTimeMillis() for example)
 * @return
 */
public boolean check_code(String secret, long code, long timeMsec) {
    Base32 codec = new Base32();
    byte[] decodedKey = codec.decode(secret);
    // convert unix msec time into a 30 second "window"
    // this is per the TOTP spec (see the RFC for details)
    long t = (timeMsec / 1000L) / 30L;
    // Window is used to check codes generated in the near past.
    // You can use this value to tune how far you're willing to go.
    for (int i = -window_size; i <= window_size; ++i) {
        long hash;
        try {
            hash = verify_code(decodedKey, t + i);
        } catch (Exception e) {
            // Yes, this is bad form - but
            // the exceptions thrown would be rare and a static
            // configuration problem
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
            // return false;
        }
        if (hash == code) {
            return true;
        }
    }
    // The validation code is invalid.
    return false;
}
 
Example 12
Source File: GoogleAuthCode.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
/**
 * 根据密钥获取验证码
 * 返回字符串是因为数值有可能以0开头
 *
 * @param secretKey 密钥
 * @param time      第几个30秒 System.currentTimeMillis() / 1000 / 30
 */
public static String getTOTP(String secretKey, long time) {
    Base32 base32 = new Base32();
    byte[] bytes = base32.decode(secretKey.toUpperCase());
    String hexKey = Hex.encodeHexString(bytes);
    String hexTime = Long.toHexString(time);
    return TOTP.generateTOTP(hexKey, hexTime, "6");
}
 
Example 13
Source File: GoogleAuthenticatorDemo.java    From twofactorauth with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static String getTOTPCode(String secretKey) {
    String normalizedBase32Key = secretKey.replace(" ", "").toUpperCase();
    Base32 base32 = new Base32();
    byte[] bytes = base32.decode(normalizedBase32Key);
    String hexKey = Hex.encodeHexString(bytes);
    long time = (System.currentTimeMillis() / 1000) / 30;
    String hexTime = Long.toHexString(time);
    return TOTP.generateTOTP(hexKey, hexTime, "6");
}
 
Example 14
Source File: TwoFactorAuthUtilTest.java    From two-factor-auth with ISC License 5 votes vote down vote up
@Test
public void testDecodeBase32() {
	Random random = new Random();
	random.nextBytes(new byte[100]);
	Base32 base32 = new Base32();
	for (int i = 0; i < 10000; i++) {
		byte[] bytes = new byte[random.nextInt(10) + 1];
		random.nextBytes(bytes);
		String encoded = base32.encodeAsString(bytes);
		byte[] expected = base32.decode(encoded);
		byte[] actual = TimeBasedOneTimePasswordUtil.decodeBase32(encoded);
		assertArrayEquals(expected, actual);
	}
}
 
Example 15
Source File: Base32Encoder.java    From nem.core with MIT License 5 votes vote down vote up
/**
 * Converts a string to a byte array.
 *
 * @param base32String The input Base32 string.
 * @return The output byte array.
 */
public static byte[] getBytes(final String base32String) {
	final Base32 codec = new Base32();
	final byte[] encodedBytes = StringEncoder.getBytes(base32String);
	if (!codec.isInAlphabet(encodedBytes, true)) {
		throw new IllegalArgumentException("malformed base32 string passed to getBytes");
	}

	return codec.decode(encodedBytes);
}
 
Example 16
Source File: CodecUtil.java    From common_gui_tools with Apache License 2.0 3 votes vote down vote up
/**
 * Decode Base32.
 *
 * @param string  String
 * @param charSet CharSet
 * @return <code>String</code> string
 * @throws UnsupportedEncodingException unsupported encoding exception
 */
public static String decodeBase32(String string, String charSet) throws UnsupportedEncodingException {
    if (string == null) {
        return null;
    }
    Base32 base32 = new Base32();
    return new String(base32.decode(string.getBytes(charSet)), charSet);
}