Example usage for javax.crypto.spec PBEKeySpec PBEKeySpec

List of usage examples for javax.crypto.spec PBEKeySpec PBEKeySpec

Introduction

In this page you can find the example usage for javax.crypto.spec PBEKeySpec PBEKeySpec.

Prototype

public PBEKeySpec(char[] password, byte[] salt, int iterationCount, int keyLength) 

Source Link

Document

Constructor that takes a password, salt, iteration count, and to-be-derived key length for generating PBEKey of variable-key-size PBE ciphers.

Usage

From source file:com.board.games.handler.modx.MODXPokerLoginServiceImpl.java

public static void main(String[] a) {

    Verifier verifier = new Verifier();

    String dbHash = "iDxLTbkejeeaQqpPoZTqUCJfWo1ALcBf7gMlYwwMa+Y="; //"dlgQ65ruCfeVVxqHJ3Bf02j50P0Wvis7WOoTfHYV3Nk=";
    String password = "rememberme";
    String dbSalt = "008747a35b77a4c7e55ab7ea8aec3ee0";
    PasswordResponse response = new PasswordResponse();
    String salt = "008747a35b77a4c7e55ab7ea8aec3ee0";
    response.setAlgorithm(Algorithm.PBKDF2);
    response.setSalt(salt);//  w  w w  .j av a  2 s  .  c o m
    response.setAlgorithmDetails(new AlgorithmDetails());
    response.getAlgorithmDetails().setIterations(1000);
    response.getAlgorithmDetails().setHashFunction("SHA256");
    response.getAlgorithmDetails().setKeySize(263);
    PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), 1000,
            response.getAlgorithmDetails().getKeySize());
    try {
        SecretKeyFactory skf = PBKDF2Algorithms.getSecretKeyFactory(
                "PBKDF2WithHmac" + response.getAlgorithmDetails().getHashFunction().replace("-", ""));
        byte[] hash = skf.generateSecret(spec).getEncoded();

        String encodedHash = Base64.encodeBase64String(hash);
        response.setHash(encodedHash);

        System.out.println("hash " + response.getHash());
        if (verifier.verify(password, response)) {
            // Check it against database stored hash
            if (encodedHash.equals(dbHash)) {
                System.out.println("Authentication Successful");
            } else {
                System.out.println("Authentication failed");
            }

        } else {
            System.out.println("failed verification of hashing");
        }
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}

From source file:Main.java

/**
 *
 * @throws InvalidKeySpecException//  w  w w. ja  v a2 s .  co  m
 * @throws NoSuchAlgorithmException
 */
private static Key deriveKeyPbkdf2(byte[] salt, String password)
        throws InvalidKeySpecException, NoSuchAlgorithmException {

    KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, ITERATION_COUNT, KEY_LENGTH);
    SecretKeyFactory factory;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1And8bit");
    } else {
        factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    }

    byte[] keyBytes = factory.generateSecret(keySpec).getEncoded();

    return new SecretKeySpec(keyBytes, "AES");
}

From source file:Main.java

private static byte[] doPBKDF2(char[] password, byte[] salt, int iterations, int bits)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, bits);
    SecretKeyFactory skf = SecretKeyFactory.getInstance(PBKDF2_ALGORITHM);
    return skf.generateSecret(spec).getEncoded();
}

From source file:Main.java

public static String decryptData(String ciphertext, String password) throws Exception {
    int iterationCount = 100; //because polaroid
    int keyLength = 256;

    String[] fields = ciphertext.split("]");
    byte[] iv = Base64.decode(fields[0], 0);
    byte[] salt = Base64.decode(fields[1], 0);
    byte[] cipherBytes = Base64.decode(fields[2], 0);

    Log.d(TAG, "ciphertext: " + ciphertext + "\n" + "iv length is " + "\n" + iv.length);

    KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, iterationCount, keyLength);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
    SecretKey key = new SecretKeySpec(keyBytes, "AES");

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    IvParameterSpec ivParams = new IvParameterSpec(iv);
    cipher.init(Cipher.DECRYPT_MODE, key, ivParams);
    byte[] plaintext = cipher.doFinal(cipherBytes);
    String plainStr = new String(plaintext, "UTF-8");

    return plainStr;
}

From source file:Main.java

public static String encryptData(String password, String plaintextData) throws Exception {
    // Thank you Mr. Nelenkov
    String maybeThisHelps = "http://nelenkov.blogspot.com/2012/04/using-password-based-encryption-on.html";
    Log.v(TAG, maybeThisHelps);/*from w  w  w. j a  va  2  s  .c  o  m*/
    int iterationCount = 100; //because Polaroid
    int keyLength = 256;
    int saltLength = keyLength;

    SecureRandom random = new SecureRandom();
    byte[] salt = new byte[saltLength];
    random.nextBytes(salt);
    KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, iterationCount, keyLength);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
    SecretKey key = new SecretKeySpec(keyBytes, "AES");

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    byte[] iv = new byte[cipher.getBlockSize()];
    random.nextBytes(iv);

    IvParameterSpec ivParams = new IvParameterSpec(iv);
    cipher.init(Cipher.ENCRYPT_MODE, key, ivParams);
    byte[] ciphertext = cipher.doFinal(plaintextData.getBytes("UTF-8"));

    String ivToString = new String(Base64.encode(iv, 0));
    String saltToString = new String(Base64.encode(salt, 0));
    String ciphertextToString = new String(Base64.encode(ciphertext, 0));

    Log.d(TAG, ivToString + "]" + saltToString + "]" + ciphertextToString);
    return (ivToString + "]" + saltToString + "]" + ciphertextToString).replace("\n", "");
}

From source file:fi.ilmoeuro.membertrack.util.Crypto.java

public static String hash(String candidate, String salt) {
    try {/*from  w  ww  . j a v  a 2  s. c  o m*/
        SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec ks = new PBEKeySpec(candidate.toCharArray(), salt.getBytes(StandardCharsets.US_ASCII), 1024,
                128);
        SecretKey sk = skf.generateSecret(ks);
        Key k = new SecretKeySpec(sk.getEncoded(), "AES");
        return Hex.encodeHexString(k.getEncoded());
    } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
        throw new RuntimeException("Error while hashing", ex);
    }
}

From source file:com.ro.ssc.app.client.licensing.TrialKeyValidator.java

public static String decodeKey(String encodedEncrypted) {
    String decoded = "";
    try {//from   ww  w.j  a v a 2 s .  c  o m
        byte[] saltDecrypt = SALT_DECRYPT.getBytes(StandardCharsets.UTF_8);
        SecretKeyFactory factoryKeyDecrypt = SecretKeyFactory.getInstance(SECRET_KEY_FACTORY);
        SecretKey tmp2 = factoryKeyDecrypt.generateSecret(
                new PBEKeySpec(PASS_DECRYPT.toCharArray(), saltDecrypt, ITERATIONS_DECRYPT, KEY_LENGTH));
        SecretKeySpec decryptKey = new SecretKeySpec(tmp2.getEncoded(), ALGORITHM);
        Cipher aesCipherDecrypt = Cipher.getInstance(CIPHER);
        aesCipherDecrypt.init(Cipher.DECRYPT_MODE, decryptKey);
        byte[] e64bytes = StringUtils.getBytesUtf8(encodedEncrypted);
        byte[] eBytes = Base64.decodeBase64(e64bytes);
        byte[] cipherDecode = aesCipherDecrypt.doFinal(eBytes);
        decoded = StringUtils.newStringUtf8(cipherDecode);
    } catch (Exception e) {
        LOGGER.error("Error while decoding the trial key", e);
    }
    return decoded;
}

From source file:rs.htec.cms.cms_bulima.helper.Password.java

private static String hash(String password, byte[] salt) throws Exception {
    if (password == null || password.length() == 0) {
        throw new IllegalArgumentException("Password must have at least one character");
    }/*from   w w  w  .  j  a  v a2  s  .  c o  m*/
    SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    SecretKey key = f.generateSecret(new PBEKeySpec(password.toCharArray(), salt, iterations, desiredKeyLen));
    return Base64.encodeBase64String(key.getEncoded());
}

From source file:org.craftercms.commons.crypto.impl.PbkAesTextEncryptor.java

private static Key generateKey(String password, String salt) throws CryptoException {
    try {/*from   ww w .j av  a  2  s .co m*/
        KeySpec keySpec = new PBEKeySpec(password.toCharArray(), Base64.decodeBase64(salt), PBK_ITER, PBK_LEN);
        SecretKeyFactory factory = SecretKeyFactory.getInstance(PBK_ALGORITHM);

        return new SecretKeySpec(factory.generateSecret(keySpec).getEncoded(),
                CryptoUtils.AES_CIPHER_ALGORITHM);
    } catch (GeneralSecurityException e) {
        throw new CryptoException("Unable to generate PBK key", e);
    }
}

From source file:com.cisco.oss.foundation.directory.utils.ObfuscatUtil.java

/**
 * Encrypt the password in PBKDF2 algorithm.
 *
 * @param password/*from  w  w  w.j a v a 2  s  .c  o  m*/
 *         the password to obfuscate.
 * @param salt
 *         the randomly sequence of bits of the user.
 * @return
 *         the obfuscated password byte array.
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
public static byte[] pBKDF2ObfuscatePassword(String password, byte[] salt)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    String algorithm = "PBKDF2WithHmacSHA1";
    int derivedKeyLength = 160;
    int iterations = 20000;
    KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, iterations, derivedKeyLength);
    SecretKeyFactory f = SecretKeyFactory.getInstance(algorithm);

    return f.generateSecret(spec).getEncoded();
}