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:cz.alej.michalik.totp.server.Users.java

/**
 * Vygenerovat kl? pro generovn TOTP hesla
 * /*from  ww  w  . j  av  a 2 s. co  m*/
 * @return base32 etzec
 */
public static String generateSecret() {
    // Chci kl? o velikosti 20 byt
    int maxBits = 20 * 8 - 1;
    SecureRandom rand = new SecureRandom();
    byte[] val = new BigInteger(maxBits, rand).toByteArray();
    return new Base32().encodeToString(val);
}

From source file:net.blogracy.controller.FileSharing.java

public static String hash(String text) {
    String result = null;/*from  w  ww. java 2s  . co  m*/
    try {
        MessageDigest digester = MessageDigest.getInstance("SHA-1");
        Base32 encoder = new Base32();
        byte[] digest = digester.digest(text.getBytes());
        result = encoder.encodeAsString(digest);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return result;
}

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

public static String encryptString(String password, String value) {
    String salt = KeyGenerators.string().generateKey();
    SecretKeySpec skeySpec = makeKeySpec(password, salt);
    byte[] iv = KeyGenerators.secureRandom(16).generateKey();
    String ivString = Hex.encodeHexString(iv);

    try {/*from w w  w .  ja v  a 2 s  .co  m*/
        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new GCMParameterSpec(128, iv));
        /*
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec,
        new IvParameterSpec(iv));
        */

        byte[] encrypted = cipher.doFinal(value.getBytes(Charset.forName("UTF-8")));
        String s = StringUtils.strip(new Base32().encodeAsString(encrypted), "=").toLowerCase();
        // Strip line breaks
        s = salt + ivString + s.replaceAll("(\\n|\\r)", "");
        return s;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:net.cortexx.otp.google.GoogleAuthenticator.java

/**
 * Creates a URI for a time-based one-time password consumable by the
 * <a href="http://code.google.com/p/google-authenticator/">Google Authenticator</a>.
 * /*from   w ww. ja va 2  s.co m*/
 * <p>
 * <b>Note:</b> This class requires the optional <a
 * href="http://commons.apache.org/proper/commons-codec/"><code>commons-codec</code></a>
 * dependency.
 * 
 * @param description
 *        the display name for the token inside the Authenticator
 * @param algorithm
 *        the algorithm to be used
 * @param digits
 *        the number of digits for this password
 * @param periodSeconds
 *        the length of the period for which one password value stays valid
 * @param secret
 *        the secret for the password
 * 
 * @return
 *         the <code>otpauth</code> URI corresponding to the given parameters
 * 
 * @see <a href="http://code.google.com/p/google-authenticator/wiki/KeyUriFormat">restrictions
 *      applying to the Google Authenticator</a>
 */
public static String createTimeBasedURI(final String description, final Algorithm algorithm, final int digits,
        final int periodSeconds, final byte... secret) {

    if (description == null || algorithm == null || secret == null) {
        throw new NullPointerException();
    }
    if (description.length() == 0) {
        throw new IllegalArgumentException("'description' must not be empty");
    }
    if (secret.length == 0) {
        throw new IllegalArgumentException("'secret' must contain at least one byte");
    }
    if (digits < 6 || digits > 8) {
        throw new IllegalArgumentException("'digits' must be in the range [6..8]");
    }
    if (periodSeconds <= 0) {
        throw new IllegalArgumentException("'periodSeconds' must be positive");
    }

    try {
        final StringBuilder uri = new StringBuilder().append("otpauth://totp/")
                .append(URLEncoder.encode(description, "UTF-8")).append("?secret=")
                .append(new Base32().encodeToString(secret));

        if (algorithm != Algorithm.SHA1) {
            uri.append("&algorithm=").append(algorithm);
        }
        if (digits != 6) {
            uri.append("&digits=").append(digits);
        }
        if (periodSeconds != 30) {
            uri.append("&period=").append(periodSeconds);
        }

        return uri.toString();
    } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException(e);
    }
}

From source file:at.asitplus.regkassen.core.base.util.CashBoxUtils.java

/**
 * BASE32 encoding helper (required for OCR representation)
 *
 * @param data binary representation of data to be encoded
 * @return BASE32 encoded representation of input data
 *///from w w  w  . j  a va  2s. c om
public static String base32Encode(byte[] data) {
    Base32 encoder = new Base32();
    return new String(encoder.encode(data)).replace("\r\n", "");
}

From source file:co.mitro.twofactor.TwoFactorTests.java

/** Enables two-factor auth for testIdentity, storing parameters in twoFactorData. */
@Before//from ww w  .j ava 2s  . c  o m
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();
}

From source file:at.asitplus.regkassen.core.base.util.CashBoxUtils.java

/**
 * BASE32 decoding helper (required for OCR representation)
 *
 * @param base32Data BASE32 encoded data
 * @return binary representation of decoded data
 *///from  ww  w.  j a  v a  2s  . c om
public static byte[] base32Decode(String base32Data) {
    Base32 decoder = new Base32();
    return decoder.decode(base32Data);
}

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

/**
 * Pid jeden panel se zznamem/*  w  ww.  ja v a 2 s  .co  m*/
 * 
 * @param raw_data
 *            Data z Properties
 * @param p
 *            Properties
 * @param index
 *            Index zznamu - pro vymazn
 */
public OtpPanel(String raw_data, final Properties p, final int index) {
    // Data jsou oddlena stednkem
    final String[] data = raw_data.split(";");

    // this.setBackground(App.COLOR);
    this.setLayout(new GridBagLayout());
    // Mkov rozloen prvk
    GridBagConstraints c = new GridBagConstraints();
    this.setMaximumSize(new Dimension(Integer.MAX_VALUE, 100));

    // Tla?tko pro zkoprovn hesla
    final JButton passPanel = new JButton("");
    passPanel.setFont(passPanel.getFont().deriveFont(App.FONT_SIZE));
    passPanel.setBackground(App.COLOR);
    // Zabere celou ku
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 100;
    this.add(passPanel, c);
    passPanel.setText(data[0]);

    // Tla?tko pro smazn
    JButton delete = new JButton("X");
    try {
        String path = "/material-design-icons/action/drawable-xhdpi/ic_delete_black_24dp.png";
        Image img = ImageIO.read(App.class.getResource(path));
        delete.setIcon(new ImageIcon(img));
        delete.setText("");
    } catch (Exception e) {
        System.out.println("Icon not found");
    }
    delete.setFont(delete.getFont().deriveFont(App.FONT_SIZE));
    delete.setBackground(App.COLOR);
    // Zabere kousek vpravo
    c.fill = GridBagConstraints.NONE;
    c.weightx = 0.5;
    c.anchor = GridBagConstraints.EAST;
    this.add(delete, c);

    // Akce pro vytvoen a zkoprovn hesla do schrnky
    passPanel.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("Generuji kod pro " + data[1]);
            System.out.println(new Base32().decode(data[1].getBytes()).length);
            clip.set(new TOTP(new Base32().decode(data[1].getBytes())).toString());
            System.out.printf("Kd pro %s je ve schrnce\n", data[0]);
            passPanel.setText("Zkoprovno");
            // Zobraz zprvu na 1 vteinu
            int time = 1000;
            // Animace zobrazen zprvy po zkoprovn
            final Timer t = new Timer(time, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    passPanel.setText(data[0]);
                }
            });
            t.start();
            t.setRepeats(false);
        }
    });

    // Akce pro smazn panelu a uloen zmn
    delete.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.printf("Odstrann %s s indexem %d\n", data[0], index);
            p.remove(String.valueOf(index));
            App.saveProperties();
            App.loadProperties();
        }
    });

}

From source file:com.sonicle.webtop.core.util.IdentifierUtils.java

/**
 * @deprecated use com.sonicle.commons.IdentifierUtils.getCRSFToken instead
 * @return/*  w w  w. j  av  a 2 s.  co  m*/
 */
@Deprecated
public static synchronized String getCRSFToken() {
    try {
        byte[] buffer = new byte[80 / 8];
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
        sr.nextBytes(buffer);
        byte[] secretKey = Arrays.copyOf(buffer, 80 / 8);
        byte[] encodedKey = new Base32().encode(secretKey);
        return new String(encodedKey).toLowerCase();
    } catch (NoSuchAlgorithmException ex) {
        return null;
    }
}

From source file:FileAccess.java

public JsonObject getProjectStructure(String projectId) {
    JsonObject projectStructure = new JsonObject();

    JsonArray rootFolder = new JsonArray();

    JsonArray rootFile = new JsonArray();

    List<String> rootDirectorys = vertx.fileSystem().readDirBlocking("project/" + projectId);

    System.out.println(new JsonArray(rootDirectorys).toString());

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    for (String directory : rootDirectorys) {
        System.out.println(directory + "directory");
        FileProps something = vertx.fileSystem().lpropsBlocking(directory);
        if (something.isDirectory()) {
            JsonObject directoryJSON = new JsonObject();
            String splitDirectory[] = directory.split("\\\\");
            directoryJSON.put("name", splitDirectory[splitDirectory.length - 1]);
            //                tinggal tambahkan encode menggunakan base 64 agar tidak terdeteksi titik.
            String id = splitDirectory[splitDirectory.length - 2];
            String tmpId = new Base32().encodeAsString(splitDirectory[splitDirectory.length - 1].getBytes())
                    .replace("=", "0");
            directoryJSON.put("id", tmpId);
            directoryJSON.put("create_date", dateFormat.format(new Date(something.creationTime())));
            directoryJSON.put("modify_date", dateFormat.format(new Date(something.lastModifiedTime())));
            rootFolder.add(directoryJSON);

            List<String> subDirectorysFiles = vertx.fileSystem().readDirBlocking(directory);
            JsonArray subFiles = new JsonArray();
            for (String subDirectoryFile : subDirectorysFiles) {
                JsonObject fileJSON = new JsonObject();
                String splitFile[] = subDirectoryFile.split("\\\\");
                fileJSON.put("name", splitFile[splitFile.length - 1]);
                fileJSON.put("id", new Base32().encodeAsString(
                        (splitFile[splitFile.length - 2] + "/" + splitFile[splitFile.length - 1]).getBytes())
                        .replace("=", "0"));
                fileJSON.put("create_date", dateFormat.format(new Date(something.creationTime())));
                fileJSON.put("modify_date", dateFormat.format(new Date(something.lastModifiedTime())));

                subFiles.add(fileJSON);//from   w  ww .  ja v a  2  s. co m
            }
            directoryJSON.put("files", subFiles);

        } else {
            JsonObject fileJSON = new JsonObject();
            String splitFile[] = directory.split("\\\\");
            fileJSON.put("name", splitFile[splitFile.length - 1]);
            fileJSON.put("id",
                    new Base32().encodeAsString(splitFile[splitFile.length - 1].getBytes()).replace("=", "0"));
            fileJSON.put("create_date", dateFormat.format(new Date(something.creationTime())));
            fileJSON.put("modify_date", dateFormat.format(new Date(something.lastModifiedTime())));
            rootFile.add(fileJSON);
        }
    }

    projectStructure.put("folders", rootFolder);
    projectStructure.put("files", rootFile);

    System.out.println(projectStructure.toString());
    return projectStructure;
}