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:eu.eubrazilcc.lvl.storage.security.shiro.CryptProvider.java

/**
 * Generates a short secret from {@link #FAST_BYTES_SIZE} random bytes and returns a Base32 representation of the string produced that can 
 * be used in URLs. The generated key will only contain the characters A-Z and 2-7.
 * @return A URL-safe representation of the computed key.
 * @see <a href="http://www.ietf.org/rfc/rfc4648.txt">RFC4648</a>
 *//*  w w  w  .  j a  va2s  .c o  m*/
public static String generateFastUrlSafeSecret() {
    return new Base32().encodeAsString(generateSalt(FAST_BYTES_SIZE));
}

From source file:co.cask.hydrator.plugin.DecoderTest.java

@Test
public void testBase32AsStringDecoder() throws Exception {
    String test = "This is a test for testing string base32 decoding";
    Transform<StructuredRecord, StructuredRecord> encoder = new Encoder(
            new Encoder.Config("a:STRING_BASE32", OUTPUT.toString()));
    encoder.initialize(null);/* w  w  w .  jav  a 2s  . c  o m*/

    MockEmitter<StructuredRecord> emitterEncoded = new MockEmitter<>();
    encoder.transform(StructuredRecord.builder(INPUT).set("a", test).set("b", "2").set("c", "3").set("d", "4")
            .set("e", "5").build(), emitterEncoded);

    Base32 base32 = new Base32();
    byte[] expected = base32.encode(test.getBytes("UTF-8"));
    byte[] actual = emitterEncoded.getEmitted().get(0).get("a");
    Assert.assertEquals(2, emitterEncoded.getEmitted().get(0).getSchema().getFields().size());
    Assert.assertArrayEquals(expected, actual);

    Transform<StructuredRecord, StructuredRecord> decoder = new Decoder(
            new Decoder.Config("a:STRING_BASE32", OUTPUTSTR.toString()));
    decoder.initialize(null);
    MockEmitter<StructuredRecord> emitterDecoded = new MockEmitter<>();
    decoder.transform(emitterEncoded.getEmitted().get(0), emitterDecoded);
    Assert.assertEquals(2, emitterDecoded.getEmitted().get(0).getSchema().getFields().size());
    Assert.assertEquals(test, emitterDecoded.getEmitted().get(0).get("a"));
}

From source file:com.chumbok.aauth.otp.TOTP.java

public static String getTOTPCode(String secretKey, long time) {
    Base32 base32 = new Base32();
    byte[] bytes = base32.decode(secretKey);
    String hexKey = Hex.encodeHexString(bytes);
    String hexTime = Long.toHexString(time);
    return TOTP.generateTOTP(hexKey, hexTime, "6");
}

From source file:cz.alej.michalik.totp.client.AddDialog.java

/**
 * Odele nov zznam/*from w  ww. j  ava2 s  .c  om*/
 * 
 * @param prop
 *            Properties
 * @param name
 *            Textov pole s jmnem
 * @param secret
 *            Textov pole s heslem
 * @param exitOnError
 *            Zave okno i pi chyb, pokud uivatel klikne na kek
 */
private void submit(final Properties prop, final JTextField name, final JTextField secret,
        boolean exitOnError) {
    System.out.printf("Jmno: %s | Heslo: %s\n", name.getText(), secret.getText());
    boolean error = false;
    sanitize(secret);
    if (name.getText().equals("") || secret.getText().equals("") || !verify(secret)) {
        System.out.println("Nepidno");
        error = true;
    } else {
        System.out.printf("Base32 heslo je: %s\n", new Base32().encodeToString(secret.getText().getBytes()));
        int id = prop.size();
        // Po odstrann me bt nkter index pesko?en
        while (prop.containsKey(String.valueOf(id))) {
            id++;
        }
        StringBuilder sb = new StringBuilder();
        // Zznam je ve tvaru "jmno;heslo"
        sb.append(name.getText());
        sb.append(";");
        sb.append(secret.getText());
        prop.setProperty(String.valueOf(id), sb.toString());
        App.saveProperties();
        App.loadProperties();
    }
    if (exitOnError || !error) {
        this.dispose();
    }
}

From source file:cz.alej.michalik.totp.client.AddDialog.java

/**
 * Ov zda je sdlen heslo platn/*from www  .jav  a 2s  .  co m*/
 * 
 * @param text
 * @return platnost
 */
private boolean verify(JTextField text) {
    System.out.println("Testuji retezec " + text.getText());
    // Pokud tda Base32 vrt kl? s nulovou dlkou, nen to platn kl?
    if (new Base32().decode(text.getText().getBytes()).length == 0) {
        System.out.println("Kl? nen platn");
        // Zvyraznim okraje
        text.setBorder(new EtchedBorder(new Color(255, 0, 0), new Color(250, 50, 50)));
        return false;
    }
    System.out.println("Kl? je platn");
    return true;
}

From source file:io.stallion.utils.GeneralUtils.java

/**
 * Turn the given long id into a random base32 string token. This can be used for generating unique, secret strings
 * for accessing data, such as a web page only viewable by a secret string. By using the long id, of the
 * underlying object we guarantee uniqueness, by adding on  random characters, we make the URL nigh
 * impossible to guess.//ww w . jav  a  2 s . c  o m
 *
 * @param id - a long id that will be convered to base32 and used as the first part of the string
 * @param length - the number of random base32 characters to add to the end of the string
 * @return
 */
public static String tokenForId(Long id, int length) {
    ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
    buffer.putLong(id);
    return StringUtils.stripStart(new Base32().encodeAsString(buffer.array()), "A").replace("=", "")
            .toLowerCase() + "8" + randomTokenBase32(length);
}

From source file:io.stallion.utils.GeneralUtils.java

/**
 * Psuedo-random string of the given length, in base32 characters
 * @param length//  w w w .j a v  a2 s .c o m
 * @return
 */
public static String randomTokenBase32(int length) {
    byte[] r = new byte[256]; //Means 2048 bit
    new Random().nextBytes(r);
    String s = new Base32().encodeAsString(r).substring(0, length).toLowerCase();
    return s;

}

From source file:co.cask.hydrator.transforms.CSVParser2.java

/**
 * Decodes the payload. /*from  w ww.  j a v  a 2 s .  co m*/
 *  
 * @param body
 * @return
 */
private byte[] decodePayLoad(String body) throws DecoderException {
    if (config.decoder.equalsIgnoreCase("base64")) {
        Base64 codec = new Base64();
        return codec.decode(body);
    } else if (config.decoder.equalsIgnoreCase("base32")) {
        Base32 codec = new Base32();
        return codec.decode(body);
    } else if (config.decoder.equalsIgnoreCase("hex")) {
        Hex codec = new Hex();
        return codec.decode(body.getBytes());
    }
    return new byte[0];
}

From source file:com.cws.esolutions.security.utils.PasswordUtils.java

/**
 * Base64 decodes a given string/*from   w w w.  j a  v  a 2s .c  o  m*/
 *
 * @param variance - The allowed differences in OTP values
 * @param algorithm - The algorithm to encrypt the data with
 * @param instance - The security instance to utilize
 * @param secret - The OTP secret
 * @param code - The OTP code
 * @return <code>true</code> if successful, <code>false</code> otherwise
 * @throws SecurityException {@link java.lang.SecurityException} if an exception occurs during processing
 */
public static final boolean validateOtpValue(final int variance, final String algorithm, final String instance,
        final String secret, final int code) throws SecurityException {
    final String methodName = PasswordUtils.CNAME
            + "#validateOtpValue(final int variance, final String algorithm, final String instance, final String secret, final int code) throws SecurityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", variance);
        DEBUGGER.debug("Value: {}", algorithm);
        DEBUGGER.debug("Value: {}", instance);
        DEBUGGER.debug("Value: {}", secret);
        DEBUGGER.debug("Value: {}", code);
    }

    long truncatedHash = 0;
    byte[] data = new byte[8];
    long timeIndex = System.currentTimeMillis() / 1000 / 30;

    final Base32 codec = new Base32();
    final byte[] decoded = codec.decode(secret);
    SecretKeySpec signKey = new SecretKeySpec(decoded, algorithm);

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

    try {
        for (int i = 8; i-- > 0; timeIndex >>>= 8) {
            data[i] = (byte) timeIndex;
        }

        Mac mac = Mac.getInstance(instance);
        mac.init(signKey);
        byte[] hash = mac.doFinal(data);
        int offset = hash[20 - 1] & 0xF;

        for (int i = 0; i < 4; i++) {
            truncatedHash <<= 8;
            truncatedHash |= (hash[offset + i] & 0xFF);
        }

        truncatedHash &= 0x7FFFFFFF;
        truncatedHash %= 1000000;

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

        return (truncatedHash == code);
    } catch (InvalidKeyException ikx) {
        throw new SecurityException(ikx.getMessage(), ikx);
    } catch (NoSuchAlgorithmException nsx) {
        throw new SecurityException(nsx.getMessage(), nsx);
    }
}

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

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

    sb.append(HTMLUtils.buildMenuNar(model, "Passwort-Abfrage", true, null, false));
    HTMLTable table = new HTMLTable();
    table.addTD("Neues Passwort", 1, HTMLTable.TABLE_HEADER);
    table.addNewRow();/*from   ww  w  .  jav  a2 s  .  c o m*/
    table.addTD("Zum Verschlsseln dieser Datei bitte ein Passwort eingeben.", 1, " align='center'");
    table.addNewRow();
    table.addTDSource(HTMLUtils.buildPasswordField("inapp_pass_one", "", 30, null), 1, " align='center'");
    HTMLUtils.setFocus("inapp_pass_one", model);
    table.addNewRow();
    table.addTD("Besttigung: ", 1, " align='center'");
    table.addNewRow();
    table.addTDSource(HTMLUtils.buildPasswordField("inapp_pass_two", "", 30, Condition.PASSWORD_CHECK_ENCRYPT),
            1, " align='center'");
    table.addNewRow();
    table.addTDSource(new Button("Verschlsseln", Condition.PASSWORD_CHECK_ENCRYPT).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));
        }
    }
    return;
}