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.bcmcgroup.flare.client.ClientUtil.java

/**
 * Encrypt plain text using AES//from w  ww .j  av a 2s.  c o  m
 *
 * @param plainText the String text to be encrypted in AES
 * @return the encrypted text String
 *
 */
public static String encrypt(String plainText) {
    try {
        byte[] saltBytes = salt.getBytes("UTF-8");
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        PBEKeySpec spec = new PBEKeySpec(seeds, saltBytes, iterations, keySize);
        SecretKey secretKey = factory.generateSecret(spec);
        SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secret, new IvParameterSpec(ivBytes));
        byte[] encryptedTextBytes = cipher.doFinal(plainText.getBytes("UTF-8"));
        return new Base64().encodeAsString(encryptedTextBytes);
    } catch (NoSuchAlgorithmException e) {
        logger.error("NoSuchAlgorithmException when attempting to encrypt a string. ");
    } catch (InvalidKeySpecException e) {
        logger.error("InvalidKeySpecException when attempting to encrypt a string. ");
    } catch (NoSuchPaddingException e) {
        logger.error("NoSuchPaddingException when attempting to encrypt a string. ");
    } catch (IllegalBlockSizeException e) {
        logger.error("IllegalBlockSizeException when attempting to encrypt a string. ");
    } catch (BadPaddingException e) {
        logger.error("BadPaddingException when attempting to encrypt a string. ");
    } catch (UnsupportedEncodingException e) {
        logger.error("UnsupportedEncodingException when attempting to encrypt a string. ");
    } catch (InvalidKeyException e) {
        logger.error("InvalidKeyException when attempting to encrypt a string. ");
    } catch (InvalidAlgorithmParameterException e) {
        logger.error("InvalidAlgorithmParameterException when attempting to encrypt a string. ");
    }
    return null;
}

From source file:com.ethercamp.harmony.keystore.KeystoreFormat.java

private byte[] hash(String encryptedData, byte[] salt, int iterations) throws Exception {
    char[] chars = encryptedData.toCharArray();
    PBEKeySpec spec = new PBEKeySpec(chars, salt, iterations, 256);
    SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
    return skf.generateSecret(spec).getEncoded();
}

From source file:om.edu.squ.squportal.portlet.dps.security.CryptoAES.java

/**
* 
* method name  : generateKey//from w  w  w. j av a 2s.  c  o m
* @param salt
* @param passphrase
* @return
* CryptoAES
* return type  : SecretKey
* 
* purpose      :
*
* Date          :   Nov 15, 2017 7:30:08 PM
*/
private SecretKey generateKey(String salt, String passphrase) {
    SecretKey secretKey = null;
    try {
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec spec = new PBEKeySpec(passphrase.toCharArray(), hex(salt), iterationCount, keySize);
        SecretKey key = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
        secretKey = key;
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        logger.error(":: Crypto Error :: Error in key generation : {}", e.getMessage());
    }
    return secretKey;
}

From source file:com.filelocker.encryption.AES_Encryption.java

/**
 * If a file is being decrypted, we need to know the pasword, the salt and the initialization vector (iv).
 * We have the password from initializing the class. pass the iv and salt here which is
 * obtained when encrypting the file initially.
 *
 * @param inFile - The Encrypted File containing encrypted data , salt and InitVec
 * @throws NoSuchAlgorithmException//from   ww w .  j a va2 s .co  m
 * @throws InvalidKeySpecException
 * @throws NoSuchPaddingException
 * @throws InvalidKeyException
 * @throws InvalidAlgorithmParameterException
 * @throws DecoderException
 * @throws IOException
 */
public void setupDecrypt(File inFile)
        throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException, DecoderException, IOException {
    SecretKeyFactory factory = null;
    SecretKey tmp = null;
    SecretKey secret = null;

    byte[] vSalt = new byte[8];
    byte[] vInitVec = new byte[16];

    RandomAccessFile vFile = new RandomAccessFile(inFile, "rw");

    //The last 8 bits are salt so seek to length of file minus 9 bits
    vFile.seek(vFile.length() - 8);
    vFile.readFully(vSalt);

    //The last 8 bits are salt and 16 bits before last 8 are Initialization Vectory so 8+16=24
    //Thus to seek to length of file minus 24 bits
    vFile.seek(vFile.length() - 24);
    vFile.readFully(vInitVec);
    vFile.seek(0);

    File tmpFile = new File(inFile.getAbsolutePath() + ".tmpEncryption.file");

    RandomAccessFile vTmpFile = new RandomAccessFile(tmpFile, "rw");

    for (int i = 0; i < (vFile.length() - 24); ++i) {
        vTmpFile.write(vFile.readByte());
    }
    vFile.close();
    vTmpFile.close();

    inFile.delete();
    tmpFile.renameTo(inFile);

    Db("got salt " + Hex.encodeHexString(vSalt));

    Db("got initvector :" + Hex.encodeHexString(vInitVec));

    /* Derive the key, given password and salt. */
    // in order to do 256 bit crypto, you have to muck with the files for Java's "unlimted security"
    // The end user must also install them (not compiled in) so beware.
    // see here:
    // http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files.shtml
    // PBKDF2WithHmacSHA1,Constructs secret keys using the Password-Based Key Derivation Function function
    //found in PKCS #5 v2.0. (PKCS #5: Password-Based Cryptography Standard)

    factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    KeySpec spec = new PBEKeySpec(vPassword.toCharArray(), vSalt, ITERATIONS, KEYLEN_BITS);

    tmp = factory.generateSecret(spec);
    secret = new SecretKeySpec(tmp.getEncoded(), "AES");

    // Decrypt the message, given derived key and initialization vector.
    vDecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    vDecipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(vInitVec));
}

From source file:net.sourceforge.jencrypt.lib.CryptoWrapper.java

private byte[] getHashedPassword(CryptoWrapperBuilder builder)
        throws NoSuchAlgorithmException, InvalidKeySpecException {

    /* Apply PBKDF2 (Password-Based Key Derivation Function 2) with
     * HMAC-SHA-1 to the password (for further details, see RFC-2898).
     *//*ww  w . j  a  va 2 s.co  m*/
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    PBEKeySpec spec = new PBEKeySpec(builder.password.toCharArray(), salt, keyDerivationIterationCount,
            builder.keySize);
    SecretKey secret = factory.generateSecret(spec);
    return secret.getEncoded();
}

From source file:com.meltmedia.jackson.crypto.EncryptionService.java

/**
 * Performs PBKDF2WithHmacSHA1 key stretching on password and returns a key of the specified length.
 * /*  w  w w  . j av a2 s.c  o m*/
 * @param password the clear text password to base the key on.
 * @param salt the salt to add to the password
 * @param iterationCount the number of iterations used when stretching
 * @param keyLength the length of the resulting key in bits
 * @return the stretched key
 * @throws NoSuchAlgorithmException if PBKDF2WithHmacSHA1 is not available
 * @throws InvalidKeySpecException if the specification of the key is invalid.
 */
static SecretKey stretchKey(char[] password, byte[] salt, int iterationCount, int keyLength)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    KeySpec spec = new PBEKeySpec(password, salt, iterationCount, keyLength);
    return factory.generateSecret(spec);
}

From source file:org.apache.ofbiz.base.crypto.HashCrypt.java

public static boolean doComparePbkdf2(String crypted, String password) {
    try {//from www . j  a v  a2 s  .  co  m
        int typeEnd = crypted.indexOf("}");
        String hashType = crypted.substring(1, typeEnd);
        String[] parts = crypted.split("\\$");
        int iterations = Integer.parseInt(parts[0].substring(typeEnd + 1));
        byte[] salt = org.apache.ofbiz.base.util.Base64.base64Decode(parts[1]).getBytes();
        byte[] hash = Base64.decodeBase64(parts[2].getBytes());

        PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, iterations, hash.length * 8);
        switch (hashType.substring(hashType.indexOf("-") + 1)) {
        case "SHA256":
            hashType = "PBKDF2WithHmacSHA256";
            break;
        case "SHA384":
            hashType = "PBKDF2WithHmacSHA384";
            break;
        case "SHA512":
            hashType = "PBKDF2WithHmacSHA512";
            break;
        default:
            hashType = "PBKDF2WithHmacSHA1";
        }
        SecretKeyFactory skf = SecretKeyFactory.getInstance(hashType);
        byte[] testHash = skf.generateSecret(spec).getEncoded();
        int diff = hash.length ^ testHash.length;

        for (int i = 0; i < hash.length && i < testHash.length; i++) {
            diff |= hash[i] ^ testHash[i];
        }

        return diff == 0;
    } catch (NoSuchAlgorithmException e) {
        throw new GeneralRuntimeException("Error while computing SecretKeyFactory", e);
    } catch (InvalidKeySpecException e) {
        throw new GeneralRuntimeException("Error while creating SecretKey", e);
    }
}

From source file:ch.bfh.evoting.alljoyn.MessageEncrypter.java

/**
 * Key derivation method from the given password
 * @param password password to derive//from w ww.  j a va2 s  .co m
 */
private void derivateKey(char[] password) {
    //Inspired from http://stackoverflow.com/questions/992019/java-256-bit-aes-password-based-encryption
    SecretKeyFactory factory;
    try {
        factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");

        //1000 iteration should be enough since the attack has to be done online and
        //salt changes for each group
        KeySpec spec = new PBEKeySpec(password, this.salt, 1000, 256);
        SecretKey tmp = factory.generateSecret(spec);
        secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");
        this.isReady = true;
    } catch (NoSuchAlgorithmException e) {
        Log.d(TAG, e.getMessage() + " ");
        e.printStackTrace();
    } catch (InvalidKeySpecException e) {
        Log.d(TAG, e.getMessage() + " ");
        e.printStackTrace();
    }

}

From source file:org.apache.spark.network.crypto.AuthEngine.java

private SecretKeySpec generateKey(String kdf, int iterations, byte[] salt, int keyLength)
        throws GeneralSecurityException {

    SecretKeyFactory factory = SecretKeyFactory.getInstance(kdf);
    PBEKeySpec spec = new PBEKeySpec(secret, salt, iterations, keyLength);

    long start = System.nanoTime();
    SecretKey key = factory.generateSecret(spec);
    long end = System.nanoTime();

    LOG.debug("Generated key with {} iterations in {} us.", conf.keyFactoryIterations(), (end - start) / 1000);

    return new SecretKeySpec(key.getEncoded(), conf.keyAlgorithm());
}

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

/**
 * Provides two-way (reversible) encryption of a provided string. Can be used where reversibility
 * is required but encryption (obfuscation, technically) is required.
 *
 * @param value - The plain text data to encrypt
 * @param salt - The salt value to utilize for the request
 * @param secretInstance - The cryptographic instance to use for the SecretKeyFactory
 * @param iterations - The number of times to loop through the keyspec
 * @param keyBits - The size of the key, in bits
 * @param algorithm - The algorithm to encrypt the data with
 * @param cipherInstance - The cipher instance to utilize
 * @param encoding - The text encoding/*  w  ww . j a va  2 s.c o m*/
 * @return The encrypted string in a reversible format
 * @throws SecurityException {@link java.lang.SecurityException} if an exception occurs during processing
 */
public static final String decryptText(final String value, final String salt, final String secretInstance,
        final int iterations, final int keyBits, final String algorithm, final String cipherInstance,
        final String encoding) throws SecurityException {
    final String methodName = PasswordUtils.CNAME
            + "#encryptText(final String value, final String salt, final String secretInstance, final int iterations, final int keyBits, final String algorithm, final String cipherInstance, final String encoding) throws SecurityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", secretInstance);
        DEBUGGER.debug("Value: {}", iterations);
        DEBUGGER.debug("Value: {}", keyBits);
        DEBUGGER.debug("Value: {}", algorithm);
        DEBUGGER.debug("Value: {}", cipherInstance);
        DEBUGGER.debug("Value: {}", encoding);
    }

    String decPass = null;

    try {
        String decoded = new String(Base64.getDecoder().decode(value));
        String iv = decoded.split(":")[0];
        String property = decoded.split(":")[1];

        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(secretInstance);
        PBEKeySpec keySpec = new PBEKeySpec(salt.toCharArray(), salt.getBytes(), iterations, keyBits);
        SecretKey keyTmp = keyFactory.generateSecret(keySpec);
        SecretKeySpec sks = new SecretKeySpec(keyTmp.getEncoded(), algorithm);

        Cipher pbeCipher = Cipher.getInstance(cipherInstance);
        pbeCipher.init(Cipher.DECRYPT_MODE, sks, new IvParameterSpec(Base64.getDecoder().decode(iv)));
        decPass = new String(pbeCipher.doFinal(Base64.getDecoder().decode(property)), encoding);
    } catch (InvalidKeyException ikx) {
        throw new SecurityException(ikx.getMessage(), ikx);
    } catch (NoSuchAlgorithmException nsx) {
        throw new SecurityException(nsx.getMessage(), nsx);
    } catch (NoSuchPaddingException npx) {
        throw new SecurityException(npx.getMessage(), npx);
    } catch (IllegalBlockSizeException ibx) {
        throw new SecurityException(ibx.getMessage(), ibx);
    } catch (BadPaddingException bpx) {
        throw new SecurityException(bpx.getMessage(), bpx);
    } catch (UnsupportedEncodingException uex) {
        throw new SecurityException(uex.getMessage(), uex);
    } catch (InvalidAlgorithmParameterException iapx) {
        throw new SecurityException(iapx.getMessage(), iapx);
    } catch (InvalidKeySpecException iksx) {
        throw new SecurityException(iksx.getMessage(), iksx);
    }

    return decPass;
}