org.apache.commons.codec.binary.Base32 Java Examples

The following examples show how to use org.apache.commons.codec.binary.Base32. 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: Entry.java    From otp-authenticator with MIT License 6 votes vote down vote up
public Entry(String contents) throws Exception {
    contents = contents.replaceFirst("otpauth", "http");
    Uri uri = Uri.parse(contents);
    URL url = new URL(contents);

    if(!url.getProtocol().equals("http")){
        throw new Exception("Invalid Protocol");
    }

    if(!url.getHost().equals("totp")){
        throw new Exception();
    }

    String secret = uri.getQueryParameter("secret");
    String label = uri.getPath().substring(1);

    String issuer = uri.getQueryParameter("issuer");

    if(issuer != null){
        label = issuer +" - "+label;
    }

    this.label = label;
    this.secret = new Base32().decode(secret.toUpperCase());
}
 
Example #2
Source File: Entry.java    From andOTP with MIT License 6 votes vote down vote up
public JSONObject toJSON() throws JSONException {
    JSONObject jsonObj = new JSONObject();
    jsonObj.put(JSON_SECRET, new String(new Base32().encode(getSecret())));
    jsonObj.put(JSON_ISSUER, getIssuer());
    jsonObj.put(JSON_LABEL, getLabel());
    jsonObj.put(JSON_DIGITS, getDigits());
    jsonObj.put(JSON_TYPE, getType().toString());
    jsonObj.put(JSON_ALGORITHM, algorithm.toString());
    jsonObj.put(JSON_THUMBNAIL, getThumbnail().name());
    jsonObj.put(JSON_LAST_USED, getLastUsed());
    jsonObj.put(JSON_USED_FREQUENCY, getUsedFrequency() );

    if (type == OTPType.TOTP)
        jsonObj.put(JSON_PERIOD, getPeriod());
    else if (type == OTPType.HOTP)
        jsonObj.put(JSON_COUNTER, getCounter());

    JSONArray tagsArray = new JSONArray();
    for(String tag : tags){
        tagsArray.put(tag);
    }
    jsonObj.put(JSON_TAGS, tagsArray);

    return jsonObj;
}
 
Example #3
Source File: GoogleAuthCode.java    From zheshiyigeniubidexiangmu with MIT License 6 votes vote down vote up
/**
 * Generate a random secret key. This must be saved by the server and
 * associated with the users account to verify the code displayed by Google
 * Authenticator. The user must register this secret on their device.
 * 生成一个随机秘钥
 *
 * @return secret key
 */
public static String generateSecretKey() {
    SecureRandom sr = null;
    try {
        sr = SecureRandom.getInstance(RANDOM_NUMBER_ALGORITHM);
        sr.setSeed(Base64.decodeBase64(SEED));
        byte[] buffer = sr.generateSeed(SECRET_SIZE);
        Base32 codec = new Base32();
        byte[] bEncodedKey = codec.encode(buffer);
        String encodedKey = new String(bEncodedKey);
        return encodedKey;
    } catch (NoSuchAlgorithmException e) {
        // should never occur... configuration error
    }
    return null;
}
 
Example #4
Source File: GoogleAuthCode.java    From zheshiyigeniubidexiangmu with MIT License 6 votes vote down vote up
/**
 * Generate a random secret key. This must be saved by the server and
 * associated with the users account to verify the code displayed by Google
 * Authenticator. The user must register this secret on their device.
 * 生成一个随机秘钥
 *
 * @return secret key
 */
public static String generateSecretKey() {
    SecureRandom sr = null;
    try {
        sr = SecureRandom.getInstance(RANDOM_NUMBER_ALGORITHM);
        sr.setSeed(Base64.decodeBase64(SEED));
        byte[] buffer = sr.generateSeed(SECRET_SIZE);
        Base32 codec = new Base32();
        byte[] bEncodedKey = codec.encode(buffer);
        String encodedKey = new String(bEncodedKey);
        return encodedKey;
    } catch (NoSuchAlgorithmException e) {
        // should never occur... configuration error
    }
    return null;
}
 
Example #5
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 #6
Source File: CredentialDisplay.java    From passman-android with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        Vault v = (Vault) SingleTon.getTon().getExtra(SettingValues.ACTIVE_VAULT.toString());
        credential = v.findCredentialByGUID(getArguments().getString(CREDENTIAL));
    }

    handler = new Handler();
    otp_refresh = new Runnable() {
        @Override
        public void run() {
            int progress =  (int) (System.currentTimeMillis() / 1000) % 30 ;
            otp_progress.setProgress(progress*100);

            ObjectAnimator animation = ObjectAnimator.ofInt(otp_progress, "progress", (progress+1)*100);
            animation.setDuration(1000);
            animation.setInterpolator(new LinearInterpolator());
            animation.start();

            otp.setText(TOTPHelper.generate(new Base32().decode(credential.getOtp())));
            handler.postDelayed(this, 1000);
        }
    };
}
 
Example #7
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 #8
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 #9
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 #10
Source File: GoogleAuthenticatorDemo.java    From twofactorauth with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static String getRandomSecretKey() {
    SecureRandom random = new SecureRandom();
    byte[] bytes = new byte[20];
    random.nextBytes(bytes);
    Base32 base32 = new Base32();
    String secretKey = base32.encodeToString(bytes);
    // make the secret key more human-readable by lower-casing and
    // inserting spaces between each group of 4 characters
    return secretKey.toLowerCase().replaceAll("(.{4})(?=.{4})", "$1 ");
}
 
Example #11
Source File: GoogleAuthenticatorUtils.java    From google-authenticator-integration with MIT License 5 votes vote down vote up
/**
 * 创建一个密钥
 */
public static String createSecretKey() {
    SecureRandom random = new SecureRandom();
    byte[] bytes = new byte[20];
    random.nextBytes(bytes);
    return new Base32().encodeToString(bytes).toLowerCase();
}
 
Example #12
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 #13
Source File: Entry.java    From otp-authenticator with MIT License 5 votes vote down vote up
public JSONObject toJSON() throws JSONException {
    JSONObject jsonObj = new JSONObject();
    jsonObj.put(JSON_SECRET, new String(new Base32().encode(getSecret())));
    jsonObj.put(JSON_LABEL, getLabel());

    return jsonObj;
}
 
Example #14
Source File: ApplicationTest.java    From otp-authenticator with MIT License 5 votes vote down vote up
public void testEntry() throws JSONException {
    byte secret[] = "Das System ist sicher".getBytes();
    String label = "5 von 5 Sterne";

    String s = "{\"secret\":\""+ new String(new Base32().encode(secret)) +"\",\"label\":\"" + label + "\"}";

    Entry e = new Entry(new JSONObject(s));
    assertTrue(Arrays.equals(secret, e.getSecret()));
    assertEquals(label, e.getLabel());

    assertEquals(s, e.toJSON()+"");
}
 
Example #15
Source File: TwoFactorAuthUtilTest.java    From two-factor-auth with ISC License 5 votes vote down vote up
@Test
public void testBadBase32() {
	String[] strings =
			new String[] { "A", "AB", "ABC", "ABCD", "ABCDE", "ABCDEF", "ABCDEFG", "ABCDEFGH", "ABCDEFGHI" };
	Base32 base32 = new Base32();
	for (String str : strings) {
		byte[] decoded = TimeBasedOneTimePasswordUtil.decodeBase32(str);
		String encoded = base32.encodeAsString(decoded);
		byte[] result = TimeBasedOneTimePasswordUtil.decodeBase32(encoded);
		// System.out.println(str + " becomes " + encoded);
		assertArrayEquals(decoded, result);
	}
}
 
Example #16
Source File: TOTPUtils.java    From spring-backend-boilerplate with Apache License 2.0 5 votes vote down vote up
/**
 * @param base32Key       base32 encoded key
 * @param timeStepInMills
 * @return
 */
public static String getGeneratedValue(String base32Key, long timeStepInMills) {
	// time step
	String hexKey = new String(Hex.encode(new Base32().decode(base32Key)));
	return TOTP.generateTOTP(hexKey,
							 Long.toHexString(System.currentTimeMillis() / timeStepInMills),
							 "6",
							 "HmacSHA1");
}
 
Example #17
Source File: ApplicationTest.java    From andOTP with MIT License 5 votes vote down vote up
@Test
public void testEntry() throws Exception {
    byte secret[] = "Das System ist sicher".getBytes();
    String label = "5 von 5 Sterne";
    int period = 30;

    String s = "{\"secret\":\"" + new String(new Base32().encode(secret)) + "\"," +
                "\"issuer\":\"\"," +
                "\"label\":\"" + label + "\"," +
                "\"digits\":6," +
                "\"type\":\"TOTP\"," +
                "\"algorithm\":\"SHA1\"," +
                "\"thumbnail\":\"Default\"," +
                "\"last_used\":0," +
                "\"used_frequency\":0," +
                "\"period\":" + Integer.toString(period) + "," +
                "\"tags\":[\"test1\",\"test2\"]}";

    Entry e = new Entry(new JSONObject(s));
    assertTrue(Arrays.equals(secret, e.getSecret()));
    assertEquals(label, e.getLabel());

    String[] tags = new String[]{"test1", "test2"};
    assertEquals(tags.length, e.getTags().size());
    assertTrue(Arrays.equals(tags, e.getTags().toArray(new String[e.getTags().size()])));

    assertEquals(s, e.toJSON().toString());
}
 
Example #18
Source File: Entry.java    From andOTP with MIT License 5 votes vote down vote up
public static boolean validateSecret(String secret) {
    try {
        new Base32().decode(secret.toUpperCase());
    } catch (Exception e) {
        return false;
    }

    return true;
}
 
Example #19
Source File: GoogleAuthenticatorUtil.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
public static String generateSecretKey() {  
    SecureRandom sr = null;  
    try {  
        sr = SecureRandom.getInstance(RANDOM_NUMBER_ALGORITHM);  
        sr.setSeed(Base64.decodeBase64(SEED));  
        byte[] buffer = sr.generateSeed(SECRET_SIZE);   
        Base32 codec = new Base32();  
        byte[] bEncodedKey = codec.encode(buffer);  
        String encodedKey = new String(bEncodedKey);  
        return encodedKey;  
    }catch (NoSuchAlgorithmException e) {  
        // should never occur... configuration error  
    }  
    return null;  
}
 
Example #20
Source File: Entry.java    From andOTP with MIT License 5 votes vote down vote up
public Entry(OTPType type, String secret, int period, int digits, String issuer, String label, TokenCalculator.HashAlgorithm algorithm, List<String> tags) {
    this.type = type;
    this.secret = new Base32().decode(secret.toUpperCase());
    this.period = period;
    this.digits = digits;
    this.issuer = issuer;
    this.label = label;
    this.algorithm = algorithm;
    this.tags = tags;
    setThumbnailFromIssuer(issuer);
}
 
Example #21
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 #22
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 #23
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 #24
Source File: GoogleAuthenticatorUtil.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
public static String generateSecretKey() {  
    SecureRandom sr = null;  
    try {  
        sr = SecureRandom.getInstance(RANDOM_NUMBER_ALGORITHM);  
        sr.setSeed(Base64.decodeBase64(SEED));  
        byte[] buffer = sr.generateSeed(SECRET_SIZE);   
        Base32 codec = new Base32();  
        byte[] bEncodedKey = codec.encode(buffer);  
        String encodedKey = new String(bEncodedKey);  
        return encodedKey;  
    }catch (NoSuchAlgorithmException e) {  
        // should never occur... configuration error  
    }  
    return null;  
}
 
Example #25
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 #26
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 #27
Source File: TOTPAuthenticator.java    From personal_book_library_web_project with MIT License 5 votes vote down vote up
public boolean verifyCode(String secret, int code, int variance) throws InvalidKeyException, NoSuchAlgorithmException {
	
	long timeIndex = System.currentTimeMillis() / 1000 / 30;
	byte[] secretBytes = new Base32().decode(secret);
	for (int i = -variance; i <= variance; i++) {
		long calculatedCode = getCode(secretBytes, timeIndex + i);
		if (calculatedCode == code) {
			return true;
		}
	}
	return false;
}
 
Example #28
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 #29
Source File: DirectoryStoreFile.java    From tessera with Apache License 2.0 5 votes vote down vote up
@Override
public DataEntry nextEntry() {
    if (!fileListIterator.hasNext()) {
        return null;
    }

    final Path nextPath = fileListIterator.next();

    return new DataEntry(
        new Base32().decode(nextPath.toFile().getName()),
        fileDelegate.newInputStream(nextPath)
    );

}
 
Example #30
Source File: Entry.java    From andOTP with MIT License 5 votes vote down vote up
public Entry(OTPType type, String secret, long counter, int digits, String issuer, String label, TokenCalculator.HashAlgorithm algorithm, List<String> tags) {
    this.type = type;
    this.secret = new Base32().decode(secret.toUpperCase());
    this.counter = counter;
    this.digits = digits;
    this.issuer = issuer;
    this.label = label;
    this.algorithm = algorithm;
    this.tags = tags;
    setThumbnailFromIssuer(issuer);
}