Example usage for org.apache.commons.codec.binary Base32 Base32

List of usage examples for org.apache.commons.codec.binary Base32 Base32

Introduction

In this page you can find the example usage for org.apache.commons.codec.binary Base32 Base32.

Prototype

public Base32() 

Source Link

Usage

From source file:mfi.filejuggler.responsibles.BasicApplication.java

@Responsible(conditions = { Condition.PASSWORD_ASK_DECRYPT })
public void fjPasswortDecryptAbfrage(StringBuilder sb, Map<String, String> parameters, Model model)
        throws Exception {

    if (model.lookupConversation().getEditingFile().isBaseCrypted()) {
        Condition forward = Condition.valueOf(parameters.get(HTMLUtils.CONDITION));
        model.lookupConversation().setForwardCondition(forward);
    } else {/*  w  ww. j  a v a 2s.  c o m*/
        sb.append(HTMLUtils.buildMenuNar(model, "Passwort-Abfrage", true, null, false));
        HTMLTable table = new HTMLTable();
        table.addTD(model.lookupConversation().getEditingFile().dateiNameKlartext(), 1, HTMLTable.TABLE_HEADER);
        table.addNewRow();
        table.addTD("Diese Datei ist verschlsselt.", 1, " align='center'");
        table.addNewRow();
        table.addTD("Bitte Passwort eingeben, dann geht's weiter.", 1, " align='center'");
        table.addNewRow();
        table.addTDSource(
                HTMLUtils.buildPasswordField("inapp_pass_one", "", 30, Condition.PASSWORD_CHECK_DECRYPT), 1,
                " align='center'");
        HTMLUtils.setFocus("inapp_pass_one", model);
        table.addNewRow();
        table.addTDSource(new Button("Entschlsseln", Condition.PASSWORD_CHECK_DECRYPT).printForUseInTable(),
                1, " align='center'");
        table.addNewRow();
        sb.append(table.buildTable(model));

        // Parameter fuer naechsten Request retten
        // Ziel-Condition steht in parameters.get(HTMLUtils.CONDITION)
        Base32 base32 = new Base32();
        for (String key : parameters.keySet()) {
            if (StringUtils.isNotEmpty(key)) {
                String valueBase32 = base32.encodeAsString(parameters.get(key).getBytes());
                sb.append(HTMLUtils.buildHiddenField("pass_routing_" + key, valueBase32));
            }
        }
    }

}

From source file:com.sonicle.webtop.core.sdk.UserProfile.java

private String generateSecretKey() throws NoSuchAlgorithmException {
    byte[] buffer = new byte[80 / 8];
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
    sr.nextBytes(buffer);//  w w  w .j a  va  2 s .co m
    byte[] secretKey = Arrays.copyOf(buffer, 80 / 8);
    byte[] encodedKey = new Base32().encode(secretKey);
    return new String(encodedKey);
}

From source file:mfi.filejuggler.responsibles.BasicApplication.java

@Responsible(conditions = { Condition.PASSWORD_CHECK_DECRYPT, Condition.PASSWORD_CHECK_ENCRYPT })
public void fjPasswortPruefen(StringBuilder sb, Map<String, String> parameters, Model model) throws Exception {

    // Die via Hidden Fields durchgeschleiften Parameter uebernehmen, sofern nicht vorhanden
    Base32 base32 = new Base32();
    Object[] keys = parameters.keySet().toArray();
    for (Object key : keys) {
        String keyString = (String) key;
        if (StringUtils.startsWith(keyString, "pass_routing_")) {
            String keyOriginal = StringUtils.removeStart(keyString, "pass_routing_");
            // Alle nicht gesetzten Parameter setzen.
            // Damit wird vermieden, dass Sessionvariablen ueberschrieben werden
            // Ausnahme: Die Ziel-Condition (z.B. FILE_VIEW). Diese immer ueberschreiben, sonst geht bei >1 Versuchen der
            // Passwort-Eingabe die Ziel-Condition verloren und nach der Eingabe des korrektes Passworts wissen wir nicht mehr, wohin
            // wir zurueck springen muessen.
            if (!parameters.containsKey(keyOriginal) || StringUtils.equals(keyOriginal, HTMLUtils.CONDITION)) {
                String valueDecoded = new String(base32.decode(parameters.get(keyString)));
                parameters.put(keyOriginal, valueDecoded);
                // Xystem.out.println("durchschleifen rein:" + keyOriginal + " / " + valueDecoded);
            }// ww  w .  j a  v a 2 s  .c o m
            // String valueBase32 = new String(base32.decode(parameters.get(key).getBytes()));
            // sb.append(HTMLUtils.buildHiddenField("pass_routing_" + key, valueBase32));
        }
    }

    String pass1 = parameters.get("inapp_pass_one");
    String pass2 = parameters.get("inapp_pass_two");

    if (model.lookupConversation().getCondition().equals(Condition.PASSWORD_CHECK_ENCRYPT)) {
        // verschluesseln
        if (StringUtils.isNotEmpty(pass1) && StringUtils.equals(pass1, pass2)) {
            // Neues Passwort ist gueltig
            model.lookupConversation().getEditingFile().prospectivePassword(pass1);
        } else {
            model.lookupConversation().getMeldungen()
                    .add("Die Passwrter waren nicht gleich oder leer. Bitte nochmal eingeben.");
            // Zurueck zur Eingabe
            model.lookupConversation().setForwardCondition(Condition.PASSWORD_ASK_ENCRYPT);
            return;
        }
    } else {
        // entschluesseln
        if (model.lookupConversation().getEditingFile().pendingPassword(pass1)) {
            // eingegebenes Passwort ist richtig bzw kann die Datei entschluesseln
        } else {
            // Zurueck zur Eingabe
            model.lookupConversation().getMeldungen()
                    .add("Mit dem eingegebenen Passwort konnte die Datei nicht entschlsselt werden.");
            Security.addCounterToBlacklist(model.getUser());
            model.lookupConversation().setForwardCondition(Condition.PASSWORD_ASK_DECRYPT);
            return;
        }
    }
    // Wenn wir bis hier gekommen sind, ist/sind die Passwoerter richtig und es kann zur eigentlichen Ziel-Condition weitergeleitet
    // werden.
    Condition forward = Condition.valueOf(
            new String(base32.decode(parameters.get("pass_routing_" + HTMLUtils.CONDITION).getBytes())));
    model.lookupConversation().setForwardCondition(forward);
    return;
}

From source file:me.vertretungsplan.parser.WebUntisParser.java

private int authCodeInternal(long time) throws NoSuchAlgorithmException, InvalidKeyException {
    long t = time / 30000;
    byte[] key = new Base32().decode(sharedSecret.toUpperCase().getBytes());
    byte[] data = new byte[8];
    long value = t;
    int i = 8;/*from   w  w w.j  a v  a2 s . com*/
    while (true) {
        int i2 = i - 1;
        if (i <= 0) {
            break;
        }
        data[i2] = (byte) ((int) value);
        value >>>= 8;
        i = i2;
    }
    SecretKeySpec signKey = new SecretKeySpec(key, "HmacSHA1");
    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(signKey);
    byte[] hash = mac.doFinal(data);
    int offset = hash[19] & 15;
    long truncatedHash = 0;
    for (int i2 = 0; i2 < 4; i2 += 1) {
        truncatedHash = (truncatedHash << 8) | ((long) (hash[offset + i2] & 255));
    }
    return (int) ((truncatedHash & 2147483647L) % 1000000);
}

From source file:com.cws.esolutions.security.processors.impl.AccountChangeProcessorImpl.java

/**
 * @see com.cws.esolutions.security.processors.interfaces.IAccountChangeProcessor#enableOtpAuth(com.cws.esolutions.security.processors.dto.AccountChangeRequest)
 *//*from   w w  w .j ava  2 s .c om*/
public AccountChangeResponse enableOtpAuth(final AccountChangeRequest request) throws AccountChangeException {
    final String methodName = IAccountChangeProcessor.CNAME
            + "#enableOtpAuth(final AccountChangeRequest request) throws AccountChangeException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("AccountChangeRequest: {}", request);
    }

    AccountChangeResponse response = new AccountChangeResponse();

    final UserAccount requestor = request.getRequestor();
    final RequestHostInfo reqInfo = request.getHostInfo();
    final UserAccount userAccount = request.getUserAccount();
    final AuthenticationData reqSecurity = request.getUserSecurity();

    if (DEBUG) {
        DEBUGGER.debug("UserAccount: {}", userAccount);
        DEBUGGER.debug("RequestHostInfo: {}", reqInfo);
        DEBUGGER.debug("UserAccount: {}", userAccount);
    }

    if (!(StringUtils.equals(userAccount.getGuid(), requestor.getGuid()))) {
        // requesting user is not the same as the user being reset. authorize
        response.setRequestStatus(SecurityRequestStatus.UNAUTHORIZED);

        return response;
    }

    try {
        String userSalt = userSec.getUserSalt(userAccount.getGuid(), SaltType.LOGON.name());

        if (StringUtils.isNotEmpty(userSalt)) {
            // we aren't getting the data back here because we don't need it. if the request
            // fails we'll get an exception and not process further. this might not be the
            // best flow control, but it does exactly what we need where we need it.
            authenticator.performLogon(userAccount.getUsername(),
                    PasswordUtils.encryptText(reqSecurity.getPassword(), userSalt,
                            secBean.getConfigData().getSecurityConfig().getAuthAlgorithm(),
                            secBean.getConfigData().getSecurityConfig().getIterations(),
                            secBean.getConfigData().getSystemConfig().getEncoding()));

            String secret = new String(
                    new Base32().encode(RandomStringUtils.randomAlphanumeric(10).getBytes()));

            if (DEBUG) {
                DEBUGGER.debug("String: {}", secret);
            }

            String otpSalt = RandomStringUtils.randomAlphanumeric(secConfig.getSaltLength());

            if (StringUtils.isNotEmpty(otpSalt)) {
                boolean isSaltInserted = userSec.addOrUpdateSalt(userAccount.getGuid(), otpSalt,
                        SaltType.OTP.name());

                if (DEBUG) {
                    DEBUGGER.debug("isSaltInserted: {}", isSaltInserted);
                }

                if ((!isSaltInserted)) {
                    response.setRequestStatus(SecurityRequestStatus.FAILURE);

                    return response;
                }

                boolean isComplete = userManager.modifyOtpSecret(userAccount.getUsername(), true,
                        PasswordUtils.encryptText(secret, otpSalt,
                                secBean.getConfigData().getSecurityConfig().getSecretAlgorithm(),
                                secBean.getConfigData().getSecurityConfig().getIterations(),
                                secBean.getConfigData().getSecurityConfig().getKeyBits(),
                                secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(),
                                secBean.getConfigData().getSecurityConfig().getEncryptionInstance(),
                                secBean.getConfigData().getSystemConfig().getEncoding()));

                if (DEBUG) {
                    DEBUGGER.debug("isComplete: {}", isComplete);
                }

                if (!(isComplete)) {
                    response.setRequestStatus(SecurityRequestStatus.FAILURE);

                    return response;
                }

                String qrCodeData = String.format(IAccountChangeProcessor.KEY_URI_FORMAT,
                        userAccount.getUsername(), secret, request.getApplicationName(),
                        secConfig.getOtpAlgorithm());

                if (DEBUG) {
                    DEBUGGER.debug("qrCodeData: {}", qrCodeData);
                }

                ByteArrayOutputStream qrCode = QRCode.from(qrCodeData.trim()).to(ImageType.PNG).stream();

                if (DEBUG) {
                    DEBUGGER.debug("ByteArrayOutputStream: {}", qrCode);
                }

                response.setSecret(secret);
                response.setQrCode(qrCode);
                response.setRequestStatus(SecurityRequestStatus.SUCCESS);
            } else {
                response.setRequestStatus(SecurityRequestStatus.FAILURE);
            }
        } else {
            ERROR_RECORDER.error("Unable to obtain configured user salt. Cannot continue");

            response.setRequestStatus(SecurityRequestStatus.FAILURE);
        }
    } catch (SQLException sqx) {
        ERROR_RECORDER.error(sqx.getMessage(), sqx);

        throw new AccountChangeException(sqx.getMessage(), sqx);
    } catch (AuthenticatorException ax) {
        ERROR_RECORDER.error(ax.getMessage(), ax);

        throw new AccountChangeException(ax.getMessage(), ax);
    } catch (SecurityException sx) {
        ERROR_RECORDER.error(sx.getMessage(), sx);

        throw new SecurityException(sx.getMessage(), sx);
    } catch (UserManagementException umx) {
        ERROR_RECORDER.error(umx.getMessage(), umx);

        throw new SecurityException(umx.getMessage(), umx);
    } finally {
        // audit
        try {
            AuditEntry auditEntry = new AuditEntry();
            auditEntry.setHostInfo(reqInfo);
            auditEntry.setAuditType(AuditType.CHANGEKEYS);
            auditEntry.setUserAccount(userAccount);
            auditEntry.setAuthorized(Boolean.TRUE);
            auditEntry.setApplicationId(request.getApplicationId());
            auditEntry.setApplicationName(request.getApplicationName());

            if (DEBUG) {
                DEBUGGER.debug("AuditEntry: {}", auditEntry);
            }

            AuditRequest auditRequest = new AuditRequest();
            auditRequest.setAuditEntry(auditEntry);

            if (DEBUG) {
                DEBUGGER.debug("AuditRequest: {}", auditRequest);
            }

            auditor.auditRequest(auditRequest);
        } catch (AuditServiceException asx) {
            ERROR_RECORDER.error(asx.getMessage(), asx);
        }
    }

    return response;
}

From source file:net.spfbl.core.Core.java

public static boolean isValidOTP(String secret, int code) {
    if (secret == null) {
        return false;
    } else {/*w  ww.j a  v  a  2  s  .  co  m*/
        byte[] buffer = new Base32().decode(secret);
        long index = getTimeIndexOTP();
        if (code == getCodeOTP(buffer, index - 2)) {
            return true;
        } else if (code == getCodeOTP(buffer, index - 1)) {
            return true;
        } else if (code == getCodeOTP(buffer, index)) {
            return true;
        } else if (code == getCodeOTP(buffer, index + 1)) {
            return true;
        } else if (code == getCodeOTP(buffer, index + 2)) {
            return true;
        } else {
            return false;
        }
    }
}

From source file:net.spfbl.core.Core.java

public static String generateSecretOTP() {
    byte[] buffer = new byte[10];
    new SecureRandom().nextBytes(buffer);
    return new String(new Base32().encode(buffer));
}

From source file:net.webpasswordsafe.server.plugin.authentication.TwoStepTOTPAuthenticator.java

public static String generateKey() {
    byte[] buffer = new byte[10];
    new SecureRandom().nextBytes(buffer);
    Base32 codec = new Base32();
    return new String(codec.encode(buffer));
}

From source file:net.webpasswordsafe.server.plugin.authentication.TwoStepTOTPAuthenticator.java

private boolean verifyCode(String secret, int code, long t, int variance)
        throws NoSuchAlgorithmException, InvalidKeyException {
    Base32 codec = new Base32();
    byte[] decodedKey = codec.decode(secret);
    for (int i = -variance; i <= variance; i++) {
        int hash = calculateCode(decodedKey, t + i);
        if (hash == code)
            return true;
    }/* www . ja va2  s. c  o  m*/
    return false;
}

From source file:org.callimachusproject.xproc.DecodeTextStep.java

private String decodeText(XdmNode source_read) throws UnsupportedEncodingException, DecoderException {
    String text = extractText(source_read);
    if ("base64".equals(encoding)) {
        if (charset == null) {
            throw XProcException.stepError(10);
        }//from ww  w  .  j  a  v  a  2  s  .  c  om
        byte[] decoded = Base64.decodeBase64(text);
        return new String(decoded, charset);
    } else if ("base32".equals(encoding)) {
        if (charset == null) {
            throw XProcException.stepError(10);
        }
        byte[] decoded = new Base32().decode(text);
        return new String(decoded, charset);
    } else if ("hex".equals(encoding)) {
        if (charset == null) {
            throw XProcException.stepError(10);
        }
        byte[] decoded = Hex.decodeHex(text.toCharArray());
        return new String(decoded, charset);
    } else if ("binary".equals(encoding)) {
        if (charset == null) {
            throw XProcException.stepError(10);
        }
        byte[] decoded = BinaryCodec.fromAscii(text.toCharArray());
        return new String(decoded, charset);
    } else if ("quoted-printable".equals(encoding)) {
        if (charset == null) {
            throw XProcException.stepError(10);
        }
        return new QuotedPrintableCodec(charset).decode(text);
    } else if ("www-form-urlencoded".equals(encoding)) {
        if (charset == null) {
            throw XProcException.stepError(10);
        }
        return new URLCodec(charset).decode(text);
    } else if (encoding != null && encoding.length() != 0) {
        throw new XProcException(step.getNode(), "Unexpected encoding: " + encoding);
    } else {
        return text;
    }
}