List of usage examples for org.apache.commons.codec.binary Base32 Base32
public Base32()
From source file:org.mozilla.android.sync.Utils.java
public static byte[] decodeFriendlyBase32(String base32) { Base32 converter = new Base32(); return converter.decode(base32.replace('8', 'l').replace('9', '0').toUpperCase()); }
From source file:org.wso2.carbon.identity.application.authenticator.totp.TOTPTokenGenerator.java
/** * Generate TOTP token for a locally stored user. * * @param username Username of the user//from ww w.ja v a 2s .c o m * @param context Authentication context * @return TOTP token as a String * @throws TOTPException When could not find user realm for the given tenant domain, invalid * secret key, decrypting invalid key and could not find the configured hashing algorithm */ public static String generateTOTPTokenLocal(String username, AuthenticationContext context) throws TOTPException { long token = 0; String tenantAwareUsername = null; if (username != null) { try { String tenantDomain = MultitenantUtils.getTenantDomain(username); UserRealm userRealm = TOTPUtil.getUserRealm(username); tenantAwareUsername = MultitenantUtils.getTenantAwareUsername(username); if (userRealm != null) { Map<String, String> userClaimValues = userRealm.getUserStoreManager().getUserClaimValues( tenantAwareUsername, new String[] { TOTPAuthenticatorConstants.SECRET_KEY_CLAIM_URL }, null); String secretKey = TOTPUtil .decrypt(userClaimValues.get(TOTPAuthenticatorConstants.SECRET_KEY_CLAIM_URL)); String firstName = userRealm.getUserStoreManager().getUserClaimValue(tenantAwareUsername, TOTPAuthenticatorConstants.FIRST_NAME_CLAIM_URL, null); String email = userRealm.getUserStoreManager().getUserClaimValue(tenantAwareUsername, TOTPAuthenticatorConstants.EMAIL_CLAIM_URL, null); byte[] secretKeyByteArray; String encoding = TOTPUtil.getEncodingMethod(tenantDomain, context); if (TOTPAuthenticatorConstants.BASE32.equals(encoding)) { Base32 codec32 = new Base32(); secretKeyByteArray = codec32.decode(secretKey); } else { Base64 codec64 = new Base64(); secretKeyByteArray = codec64.decode(secretKey); } token = getCode(secretKeyByteArray, getTimeIndex(context)); sendNotification(tenantAwareUsername, firstName, Long.toString(token), email); if (log.isDebugEnabled()) { log.debug("Token is sent to via email to the user : " + tenantAwareUsername); } } else { throw new TOTPException("Cannot find the user realm for the given tenant domain : " + CarbonContext.getThreadLocalCarbonContext().getTenantDomain()); } } catch (UserStoreException e) { throw new TOTPException("TOTPTokenGenerator failed while trying to access userRealm of the user : " + tenantAwareUsername, e); } catch (NoSuchAlgorithmException e) { throw new TOTPException("TOTPTokenGenerator can't find the configured hashing algorithm", e); } catch (InvalidKeyException e) { throw new TOTPException("Secret key is not valid", e); } catch (CryptoException e) { throw new TOTPException("Error while decrypting the key", e); } catch (AuthenticationFailedException e) { throw new TOTPException("TOTPTokenVerifier cannot find the property value for encodingMethod"); } } return Long.toString(token); }
From source file:org.wso2.carbon.identity.application.authenticator.totp.util.TOTPAuthenticatorCredentials.java
/** * Decode the secret key./*from w ww . j a v a 2 s. co m*/ * * @param secret Secret key * @return Decoded secret key */ private byte[] decodeSecret(String secret) { // Decoding the secret key to get its raw byte representation. switch (config.getKeyRepresentation()) { case BASE32: Base32 codec32 = new Base32(); return codec32.decode(secret); case BASE64: Base64 codec64 = new Base64(); return codec64.decode(secret); default: throw new TOTPAuthenticatorException("Unknown key representation type."); } }
From source file:org.wso2.carbon.identity.application.authenticator.totp.util.TOTPAuthenticatorCredentials.java
/** * This method calculates the secret key given a random byte buffer. * * @param secretKey A random byte buffer * @return The secret key/*from w w w . ja va2s. c o m*/ */ private String calculateSecretKey(byte[] secretKey) { switch (config.getKeyRepresentation()) { case BASE32: return new Base32().encodeToString(secretKey); case BASE64: return new Base64().encodeToString(secretKey); default: throw new TOTPAuthenticatorException("Unknown key representation type."); } }
From source file:org.wso2.carbon.identity.application.authenticator.totp.util.TOTPAuthenticatorImpl.java
private byte[] decodeSecret(String secret) { // Decoding the secret key to get its raw byte representation. switch (config.getKeyRepresentation()) { case BASE32:/*from w ww .j a v a2 s . c o m*/ Base32 codec32 = new Base32(); return codec32.decode(secret); case BASE64: Base64 codec64 = new Base64(); return codec64.decode(secret); default: throw new IllegalArgumentException("Unknown key representation type."); } }
From source file:org.wso2.carbon.identity.application.authenticator.totp.util.TOTPAuthenticatorImpl.java
/** * This method calculates the secret key given a random byte buffer. * * @param secretKey a random byte buffer. * @return the secret key./*from ww w .jav a 2s .c o m*/ */ private String calculateSecretKey(byte[] secretKey) { switch (config.getKeyRepresentation()) { case BASE32: return new Base32().encodeToString(secretKey); case BASE64: return new Base64().encodeToString(secretKey); default: throw new IllegalArgumentException("Unknown key representation type."); } }
From source file:password.pwm.util.java.StringUtil.java
public static String base32Encode(final byte[] input) throws IOException { final Base32 base32 = new Base32(); return new String(base32.encode(input)); }
From source file:password.pwm.util.operations.OtpService.java
public boolean validateToken(final PwmSession pwmSession, final UserIdentity userIdentity, final OTPUserRecord otpUserRecord, final String userInput, final boolean allowRecoveryCodes) throws PwmOperationalException, PwmUnrecoverableException { boolean otpCorrect = false; try {//from www. java 2s . co m final Base32 base32 = new Base32(); final byte[] rawSecret = base32.decode(otpUserRecord.getSecret()); final Mac mac = Mac.getInstance("HMACSHA1"); mac.init(new SecretKeySpec(rawSecret, "")); final PasscodeGenerator generator = new PasscodeGenerator(mac, settings.getOtpTokenLength(), settings.getTotpIntervalSeconds()); switch (otpUserRecord.getType()) { case TOTP: otpCorrect = generator.verifyTimeoutCode(userInput, settings.getTotpPastIntervals(), settings.getTotpFutureIntervals()); break; //@todo HOTP implementation default: throw new UnsupportedOperationException("OTP type not supported: " + otpUserRecord.getType()); } } catch (Exception e) { LOGGER.error(pwmSession.getLabel(), "error checking otp secret: " + e.getMessage()); } if (!otpCorrect && allowRecoveryCodes && otpUserRecord.getRecoveryCodes() != null && otpUserRecord.getRecoveryInfo() != null) { final OTPUserRecord.RecoveryInfo recoveryInfo = otpUserRecord.getRecoveryInfo(); final String userHashedInput = doRecoveryHash(userInput, recoveryInfo); for (final OTPUserRecord.RecoveryCode code : otpUserRecord.getRecoveryCodes()) { if (code.getHashCode().equals(userInput) || code.getHashCode().equals(userHashedInput)) { if (code.isUsed()) { throw new PwmOperationalException(PwmError.ERROR_OTP_RECOVERY_USED, "recovery code has been previously used"); } code.setUsed(true); try { pwmApplication.getOtpService().writeOTPUserConfiguration(null, userIdentity, otpUserRecord); } catch (ChaiUnavailableException e) { throw new PwmUnrecoverableException( new ErrorInformation(PwmError.ERROR_WRITING_OTP_SECRET, e.getMessage())); } otpCorrect = true; } } } return otpCorrect; }
From source file:tor.HiddenService.java
public static byte[] getDescId(String onion, byte replica) { byte[] onionbin = new Base32().decode(onion.toUpperCase()); assert onionbin.length == 10; long curtime = System.currentTimeMillis() / 1000L; int oid = onionbin[0] & 0xff; long t = (curtime + (oid * 86400L / 256)) / 86400L; ByteBuffer buf = ByteBuffer.allocate(10); buf.putInt((int) t); buf.put(replica);/*from w w w . j a v a 2 s. co m*/ buf.flip(); MessageDigest md = TorCrypto.getSHA1(); md.update(buf); byte hashT[] = md.digest(); md = TorCrypto.getSHA1(); return md.digest(ArrayUtils.addAll(onionbin, hashT)); //md.digest(); }
From source file:tor.HiddenService.java
public static String fetchHSDescriptor(TorSocket sock, final String onion) throws IOException { // get list of ORs with resposibility for this HS OnionRouter ors[] = findResposibleDirectories(onion); // loop through responsible directories until successful for (int i = 0; i < ors.length; i++) { OnionRouter or = ors[i];/*from ww w . j av a 2 s . c o m*/ log.debug("Trying Directory Server: {}", or); // establish circuit to responsible director TorCircuit circ = sock.createCircuit(true); try { circ.create(); circ.extend(ors[0]); } catch (TorCircuitException e) { log.error("HS fetched failed due to circuit failure - moving to next directory"); continue; } final int replica = i < 3 ? 0 : 1; // asynchronous call TorStream st = circ.createDirStream(new TorStream.TorStreamListener() { @Override public void dataArrived(TorStream s) { } @Override public void connected(TorStream s) { try { s.sendHTTPGETRequest("/tor/rendezvous2/" + new Base32().encodeAsString(HiddenService.getDescId(onion, (byte) replica)), "dirreq"); } catch (IOException e) { e.printStackTrace(); } } @Override public void disconnected(TorStream s) { synchronized (onion) { onion.notify(); } } @Override public void failure(TorStream s) { synchronized (onion) { onion.notify(); } } }); // wait for notification from the above listener that data is here! (that remote side ended connection - data could be blank synchronized (onion) { try { onion.wait(1000); if (circ.state == TorCircuit.STATES.DESTROYED) { System.out.println("HS - Desc Fetch - Circuit Destroyed"); throw new TorCircuitException("circuit destroyed"); } } catch (InterruptedException e) { e.printStackTrace(); } } // get HTTP response and body String data = IOUtils.toString(st.getInputStream()); circ.destroy(); // HTTP success code if (data.length() < 1 || !data.split(" ")[1].equals("200")) { continue; } int dataIndex = data.indexOf("\r\n\r\n"); return data.substring(dataIndex); } log.warn("Not found hs descriptor!"); return null; }