Example usage for java.security AlgorithmParameters getParameterSpec

List of usage examples for java.security AlgorithmParameters getParameterSpec

Introduction

In this page you can find the example usage for java.security AlgorithmParameters getParameterSpec.

Prototype

public final <T extends AlgorithmParameterSpec> T getParameterSpec(Class<T> paramSpec)
        throws InvalidParameterSpecException 

Source Link

Document

Returns a (transparent) specification of this parameter object.

Usage

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

/**
 * this must be called after creating the initial Crypto object. It creates a salt of SALT_LEN bytes
 * and generates the salt bytes using secureRandom().  The encryption secret key is created
 * along with the initialization vectory. The member variable vEcipher is created to be used
 * by the class later on when either creating a CipherOutputStream, or encrypting a buffer
 * to be written to disk.//from  w  ww  .j  a  v a2s  .  co  m
 *
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws NoSuchPaddingException
 * @throws InvalidParameterSpecException
 * @throws IllegalBlockSizeException
 * @throws BadPaddingException
 * @throws UnsupportedEncodingException
 * @throws InvalidKeyException
 */
public void setupEncrypt() throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException,
        InvalidParameterSpecException, IllegalBlockSizeException, BadPaddingException,
        UnsupportedEncodingException, InvalidKeyException {
    SecretKeyFactory factory = null;
    SecretKey tmp = null;

    // crate secureRandom salt and store  as member var for later use
    vSalt = new byte[SALT_LEN];
    SecureRandom rnd = new SecureRandom();
    rnd.nextBytes(vSalt);
    Db("generated salt :" + Hex.encodeHexString(vSalt));

    factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");

    /* 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
     */
    KeySpec spec = new PBEKeySpec(vPassword.toCharArray(), vSalt, ITERATIONS, KEYLEN_BITS);
    tmp = factory.generateSecret(spec);
    SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");

    /* Create the Encryption cipher object and store as a member variable
     */
    vEcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    vEcipher.init(Cipher.ENCRYPT_MODE, secret);
    AlgorithmParameters params = vEcipher.getParameters();

    // get the initialization vectory and store as member var
    vInitVec = params.getParameterSpec(IvParameterSpec.class).getIV();

    Db("vInitVec is :" + Hex.encodeHexString(vInitVec));
}

From source file:ropes.Crypto.java

/**
* this must be called after creating the initial Crypto object. It creates a salt of SALT_LEN bytes
* and generates the salt bytes using secureRandom().  The encryption secret key is created 
* along with the initialization vectory. The member variable mEcipher is created to be used
* by the class later on when either creating a CipherOutputStream, or encrypting a buffer
* to be written to disk.//from  ww w  . ja va 2  s  .co  m
*  
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
* @throws NoSuchPaddingException
* @throws InvalidParameterSpecException
* @throws IllegalBlockSizeException
* @throws BadPaddingException
* @throws UnsupportedEncodingException
* @throws InvalidKeyException
*/
public void setupEncrypt() {
    try {
        SecretKeyFactory factory = null;
        SecretKey tmp = null;

        // crate secureRandom salt and store  as member var for later use
        mSalt = new byte[SALT_LEN];
        SecureRandom rnd = new SecureRandom();
        rnd.nextBytes(mSalt);
        Db("generated salt :" + Hex.encodeHexString(mSalt));

        factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");

        /* 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
        */
        KeySpec spec = new PBEKeySpec(mPassword.toCharArray(), mSalt, ITERATIONS, KEYLEN_BITS);
        tmp = factory.generateSecret(spec);
        SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");

        /* Create the Encryption cipher object and store as a member variable
        */
        mEcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        mEcipher.init(Cipher.ENCRYPT_MODE, secret);
        AlgorithmParameters params = mEcipher.getParameters();

        // get the initialization vectory and store as member var
        mInitVec = params.getParameterSpec(IvParameterSpec.class).getIV();

        Db("mInitVec is :" + Hex.encodeHexString(mInitVec));
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeySpecException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchPaddingException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeyException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidParameterSpecException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    }
}

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

/**
 * Method that encrypts data//from   w ww . j a  v  a 2 s  . c  o  m
 * @param data The data which should be encrypted
 * @return The encrypted bytes, null if encryption failed
 * 
 */
public byte[] encrypt(byte[] data) {
    //Inspired from http://stackoverflow.com/questions/992019/java-256-bit-aes-password-based-encryption

    Cipher cipher;
    try {
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

        // cipher.getParameters() seems to return null on Android 4.3 (Bug?)
        // Solution implemented from here: 
        // https://code.google.com/p/android/issues/detail?id=58191
        byte[] iv;
        if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
            iv = generateIv();
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(iv));
        } else {
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            AlgorithmParameters params = cipher.getParameters();
            iv = params.getParameterSpec(IvParameterSpec.class).getIV();
        }

        byte[] cipherText = cipher.doFinal(data);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        outputStream.write(iv);
        outputStream.write(cipherText);

        return outputStream.toByteArray();
    } catch (NoSuchAlgorithmException e) {
        Log.d(TAG, e.getMessage() + " ");
        e.printStackTrace();
        return null;
    } catch (NoSuchPaddingException e) {
        Log.d(TAG, e.getMessage() + " ");
        e.printStackTrace();
        return null;
    } catch (InvalidKeyException e) {
        Log.d(TAG, e.getMessage() + " ");
        e.printStackTrace();
        return null;
    } catch (InvalidParameterSpecException e) {
        Log.d(TAG, e.getMessage() + " ");
        e.printStackTrace();
        return null;
    } catch (IllegalBlockSizeException e) {
        Log.d(TAG, e.getMessage() + " ");
        e.printStackTrace();
        return null;
    } catch (BadPaddingException e) {
        Log.d(TAG, e.getMessage() + " ");
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        Log.d(TAG, e.getMessage() + " ");
        e.printStackTrace();
        return null;
    } catch (InvalidAlgorithmParameterException e) {
        Log.d(TAG, e.getMessage() + " ");
        e.printStackTrace();
        return null;
    }
}

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

/**
 * Creates a cipher for doing encryption.  The generated iv is placed in the value as a side effect.
 * //from  w ww  .jav  a2  s .  co m
 * @param secret the pre stretched secret key
 * @param value the value that the encrypted data will be stored in.
 * @return the cipher to use.
 * @throws EncryptionException
 */
Cipher createEncryptionCipher(SecretKey secret, E value) throws EncryptionException {
    if (Ciphers.AES_256_CBC.equals(value.getCipher())
            && KeyDerivations.PBKDF2.equals(value.getKeyDerivation())) {
        try {
            SecretKeySpec spec = new SecretKeySpec(secret.getEncoded(), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, spec);
            AlgorithmParameters params = cipher.getParameters();
            value.setIv(params.getParameterSpec(IvParameterSpec.class).getIV());
            return cipher;
        } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException
                | InvalidParameterSpecException e) {
            throw new EncryptionException("could not create encryption cypher", e);
        }
    } else {
        throw new EncryptionException(String.format("unsupported cipher %s and key derivation %s",
                value.getCipher(), value.getKeyDerivation()));
    }
}

From source file:org.jasig.cas.extension.clearpass.EncryptedMapDecorator.java

protected String encrypt(final String value, final String hashedKey) {
    if (value == null) {
        return null;
    }/*from w  w w  .  j  a  v a 2  s  . com*/

    try {
        final Cipher cipher = getCipherObject();
        cipher.init(Cipher.ENCRYPT_MODE, this.key);
        AlgorithmParameters params = cipher.getParameters();

        if (hashedKey != null) {
            algorithmParametersHashMap.put(hashedKey, params.getParameterSpec(IvParameterSpec.class));
        }

        byte[] valueByteArray = value.getBytes();
        byte[] encryptedByteArray = cipher.doFinal(valueByteArray);
        byte[] encrypted64ByteValue = new Base64().encode(encryptedByteArray);

        return new String(encrypted64ByteValue);

    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.sling.discovery.base.connectors.ping.TopologyRequestValidator.java

/**
 * Encrypt a payload with the numbed key/
 *
 * @param payload the payload./*from   w  w  w.ja  v a2s . c  om*/
 * @param keyNo the key number.
 * @return an encrypted version.
 * @throws IllegalBlockSizeException
 * @throws BadPaddingException
 * @throws UnsupportedEncodingException
 * @throws InvalidKeyException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchPaddingException
 * @throws InvalidKeySpecException
 * @throws InvalidParameterSpecException
 */
private List<String> encrypt(String payload) throws IllegalBlockSizeException, BadPaddingException,
        UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidKeySpecException, InvalidParameterSpecException {
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    byte[] salt = new byte[9];
    random.nextBytes(salt);
    cipher.init(Cipher.ENCRYPT_MODE, getCiperKey(salt));
    AlgorithmParameters params = cipher.getParameters();
    List<String> encrypted = new ArrayList<String>();
    encrypted.add(new String(Base64.encodeBase64(salt)));
    encrypted.add(new String(Base64.encodeBase64(params.getParameterSpec(IvParameterSpec.class).getIV())));
    encrypted.add(new String(Base64.encodeBase64(cipher.doFinal(payload.getBytes("UTF-8")))));
    return encrypted;
}