下面列出了 org.apache.commons.codec.binary.Base32 # decode ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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);
}
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;
}
/** 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();
}
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;
}
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;
}
/**
* 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");
}
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");
}
/**
* 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);
}
/**
* 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;
}
/**
* 根据密钥获取验证码
* 返回字符串是因为数值有可能以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");
}
/**
* 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;
}
/**
* 根据密钥获取验证码
* 返回字符串是因为数值有可能以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");
}
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");
}
@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);
}
}
/**
* 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);
}
/**
* 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);
}