Example usage for javax.crypto Cipher getParameters

List of usage examples for javax.crypto Cipher getParameters

Introduction

In this page you can find the example usage for javax.crypto Cipher getParameters.

Prototype

public final AlgorithmParameters getParameters() 

Source Link

Document

Returns the parameters used with this cipher.

Usage

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

protected String encrypt(final String value, final String hashedKey) {
    if (value == null) {
        return null;
    }//w ww .ja  v  a 2 s  .c  o m

    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:com.meltmedia.jackson.crypto.EncryptionService.java

/**
 * Creates a cipher for doing encryption.  The generated iv is placed in the value as a side effect.
 * /* w w w  . jav a2  s  . c  o  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.apache.sling.discovery.base.connectors.ping.TopologyRequestValidator.java

/**
 * Encrypt a payload with the numbed key/
 *
 * @param payload the payload./*from   w  w  w .  j  a  va 2s. c  o m*/
 * @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;
}

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

/**
 * Method that encrypts data/*from   w w  w  . java2 s. com*/
 * @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:org.tolven.config.model.CredentialManager.java

private void writeDER(char[] password, PrivateKey privateKey, File file)
        throws IOException, GeneralSecurityException {
    byte[] bytes = null;
    if (password == null) {
        bytes = privateKey.getEncoded();
    } else {//from  w ww  . j  a  v a2  s . c  om
        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        PBEKeySpec passwordSpec = new PBEKeySpec(password);
        SecretKey secretKey = secretKeyFactory.generateSecret(passwordSpec);
        Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedPrivateKey = cipher.doFinal(privateKey.getEncoded());
        EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(cipher.getParameters(),
                encryptedPrivateKey);
        bytes = encryptedPrivateKeyInfo.getEncoded();
    }
    FileUtils.writeByteArrayToFile(file, bytes);
}

From source file:com.ccstats.crypto.AESWorker.java

/**
 * Through the power of the advanced encryption standard, a plaintext will be encrypted with a parameter-specified
 * password, an extra protective layer (salt), and a specified key length. Make sure to acquire the salt and ivBytes
 * as they are necessary for decrypting the encrypted result.
 *
 * Firstly, The password is obtained and instantly overridden with the hashed version of the password, allowing
 * for stronger security as the plaintext password will not be used. Second, an arbitrary salt is securely
 * generated. Finally, the encryption standard is carried out and the encrypted text is obtained.
 *
 * @param password the password as a char array.
 * @param text The plaintext bytes to be encrypted.
 *
 * @return The Encrypted text in hexadecimal format.
 *///from  w ww  .  j av  a 2 s  .c  om
public char[] encrypt(char[] password, byte[] text)
        throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException,
        InvalidParameterSpecException, BadPaddingException, IllegalBlockSizeException {

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    if (Cipher.getMaxAllowedKeyLength("AES") < this.keyLength) {
        this.keyLength = Cipher.getMaxAllowedKeyLength("AES");
        System.err.printf(
                "WARNING: YOUR MAXIMUM AES KEY LENGTH POLICY IS %d BITS. KEY LENGTH LIMITED TO %d BITS.\n",
                this.keyLength, this.keyLength);
    }

    // hash the password and acquire a securely and randomly generated salt
    password = hash(new String(password).getBytes(StandardCharsets.UTF_8));
    byte[] salt = new byte[20];
    new SecureRandom().nextBytes(salt);

    // acquire the key
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    PBEKeySpec spec = new PBEKeySpec(password, salt, 16384, this.keyLength);
    SecretKey key = factory.generateSecret(spec);
    SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES");

    // init the cipher and process the encryption
    cipher.init(Cipher.ENCRYPT_MODE, keySpec);
    AlgorithmParameters ap = cipher.getParameters();
    byte[] ivBytes = ap.getParameterSpec(IvParameterSpec.class).getIV();
    byte[] result = cipher.doFinal(text);

    return Hex.encodeHex(mergeByteArrays(ivBytes, result, salt));
}