Search in sources :

Example 66 with IvParameterSpec

use of javax.crypto.spec.IvParameterSpec in project oxAuth by GluuFederation.

the class JweDecrypterImpl method decryptCipherText.

@Override
public String decryptCipherText(String encodedCipherText, byte[] contentMasterKey, byte[] initializationVector, byte[] authenticationTag, byte[] additionalAuthenticatedData) throws InvalidJweException {
    if (getBlockEncryptionAlgorithm() == null) {
        throw new InvalidJweException("The block encryption algorithm is null");
    }
    if (contentMasterKey == null) {
        throw new InvalidJweException("The content master key (CMK) is null");
    }
    if (initializationVector == null) {
        throw new InvalidJweException("The initialization vector is null");
    }
    if (authenticationTag == null) {
        throw new InvalidJweException("The authentication tag is null");
    }
    if (additionalAuthenticatedData == null) {
        throw new InvalidJweException("The additional authentication data is null");
    }
    try {
        if (getBlockEncryptionAlgorithm() == BlockEncryptionAlgorithm.A128GCM || getBlockEncryptionAlgorithm() == BlockEncryptionAlgorithm.A256GCM) {
            final int MAC_SIZE_BITS = 128;
            byte[] cipherText = Base64Util.base64urldecode(encodedCipherText);
            KeyParameter key = new KeyParameter(contentMasterKey);
            AEADParameters aeadParameters = new AEADParameters(key, MAC_SIZE_BITS, initializationVector, additionalAuthenticatedData);
            SecretKeySpec sks = new SecretKeySpec(contentMasterKey, "AES");
            BlockCipher blockCipher = new AESEngine();
            CipherParameters params = new KeyParameter(sks.getEncoded());
            blockCipher.init(false, params);
            GCMBlockCipher aGCMBlockCipher = new GCMBlockCipher(blockCipher);
            aGCMBlockCipher.init(false, aeadParameters);
            byte[] input = new byte[cipherText.length + authenticationTag.length];
            System.arraycopy(cipherText, 0, input, 0, cipherText.length);
            System.arraycopy(authenticationTag, 0, input, cipherText.length, authenticationTag.length);
            int len = aGCMBlockCipher.getOutputSize(input.length);
            byte[] out = new byte[len];
            int outOff = aGCMBlockCipher.processBytes(input, 0, input.length, out, 0);
            aGCMBlockCipher.doFinal(out, outOff);
            String plaintext = new String(out, Charset.forName(Util.UTF8_STRING_ENCODING));
            return plaintext;
        } else if (getBlockEncryptionAlgorithm() == BlockEncryptionAlgorithm.A128CBC_PLUS_HS256 || getBlockEncryptionAlgorithm() == BlockEncryptionAlgorithm.A256CBC_PLUS_HS512) {
            byte[] cipherText = Base64Util.base64urldecode(encodedCipherText);
            byte[] cek = KeyDerivationFunction.generateCek(contentMasterKey, getBlockEncryptionAlgorithm());
            Cipher cipher = Cipher.getInstance(getBlockEncryptionAlgorithm().getAlgorithm());
            IvParameterSpec ivParameter = new IvParameterSpec(initializationVector);
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(cek, "AES"), ivParameter);
            byte[] decodedPlainTextBytes = cipher.doFinal(cipherText);
            String decodedPlainText = new String(decodedPlainTextBytes, Charset.forName(Util.UTF8_STRING_ENCODING));
            // Integrity check
            String securedInputValue = new String(additionalAuthenticatedData, Charset.forName(Util.UTF8_STRING_ENCODING)) + "." + encodedCipherText;
            byte[] cik = KeyDerivationFunction.generateCik(contentMasterKey, getBlockEncryptionAlgorithm());
            SecretKey secretKey = new SecretKeySpec(cik, getBlockEncryptionAlgorithm().getIntegrityValueAlgorithm());
            Mac mac = Mac.getInstance(getBlockEncryptionAlgorithm().getIntegrityValueAlgorithm());
            mac.init(secretKey);
            byte[] integrityValue = mac.doFinal(securedInputValue.getBytes(Util.UTF8_STRING_ENCODING));
            if (!Arrays.equals(integrityValue, authenticationTag)) {
                throw new InvalidJweException("The authentication tag is not valid");
            }
            return decodedPlainText;
        } else {
            throw new InvalidJweException("The block encryption algorithm is not supported");
        }
    } catch (InvalidCipherTextException e) {
        throw new InvalidJweException(e);
    } catch (NoSuchPaddingException e) {
        throw new InvalidJweException(e);
    } catch (BadPaddingException e) {
        throw new InvalidJweException(e);
    } catch (InvalidAlgorithmParameterException e) {
        throw new InvalidJweException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new InvalidJweException(e);
    } catch (IllegalBlockSizeException e) {
        throw new InvalidJweException(e);
    } catch (UnsupportedEncodingException e) {
        throw new InvalidJweException(e);
    } catch (NoSuchProviderException e) {
        throw new InvalidJweException(e);
    } catch (InvalidKeyException e) {
        throw new InvalidJweException(e);
    } catch (InvalidParameterException e) {
        throw new InvalidJweException(e);
    }
}
Also used : InvalidCipherTextException(org.bouncycastle.crypto.InvalidCipherTextException) KeyParameter(org.bouncycastle.crypto.params.KeyParameter) InvalidParameterException(org.xdi.oxauth.model.exception.InvalidParameterException) SecretKeySpec(javax.crypto.spec.SecretKeySpec) InvalidJweException(org.xdi.oxauth.model.exception.InvalidJweException) AESEngine(org.bouncycastle.crypto.engines.AESEngine) BlockCipher(org.bouncycastle.crypto.BlockCipher) GCMBlockCipher(org.bouncycastle.crypto.modes.GCMBlockCipher) UnsupportedEncodingException(java.io.UnsupportedEncodingException) CipherParameters(org.bouncycastle.crypto.CipherParameters) AEADParameters(org.bouncycastle.crypto.params.AEADParameters) IvParameterSpec(javax.crypto.spec.IvParameterSpec) BlockCipher(org.bouncycastle.crypto.BlockCipher) GCMBlockCipher(org.bouncycastle.crypto.modes.GCMBlockCipher) GCMBlockCipher(org.bouncycastle.crypto.modes.GCMBlockCipher)

Example 67 with IvParameterSpec

use of javax.crypto.spec.IvParameterSpec in project lucene-solr by apache.

the class CryptoKeys method decodeAES.

public static String decodeAES(String base64CipherTxt, String pwd, final int keySizeBits) {
    final Charset ASCII = Charset.forName("ASCII");
    final int INDEX_KEY = 0;
    final int INDEX_IV = 1;
    final int ITERATIONS = 1;
    final int SALT_OFFSET = 8;
    final int SALT_SIZE = 8;
    final int CIPHERTEXT_OFFSET = SALT_OFFSET + SALT_SIZE;
    try {
        byte[] headerSaltAndCipherText = Base64.base64ToByteArray(base64CipherTxt);
        // --- extract salt & encrypted ---
        // header is "Salted__", ASCII encoded, if salt is being used (the default)
        byte[] salt = Arrays.copyOfRange(headerSaltAndCipherText, SALT_OFFSET, SALT_OFFSET + SALT_SIZE);
        byte[] encrypted = Arrays.copyOfRange(headerSaltAndCipherText, CIPHERTEXT_OFFSET, headerSaltAndCipherText.length);
        // --- specify cipher and digest for evpBytesTokey method ---
        Cipher aesCBC = Cipher.getInstance("AES/CBC/PKCS5Padding");
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        // --- create key and IV  ---
        // the IV is useless, OpenSSL might as well have use zero's
        final byte[][] keyAndIV = evpBytesTokey(keySizeBits / Byte.SIZE, aesCBC.getBlockSize(), md5, salt, pwd.getBytes(ASCII), ITERATIONS);
        SecretKeySpec key = new SecretKeySpec(keyAndIV[INDEX_KEY], "AES");
        IvParameterSpec iv = new IvParameterSpec(keyAndIV[INDEX_IV]);
        // --- initialize cipher instance and decrypt ---
        aesCBC.init(Cipher.DECRYPT_MODE, key, iv);
        byte[] decrypted = aesCBC.doFinal(encrypted);
        return new String(decrypted, ASCII);
    } catch (BadPaddingException e) {
        // AKA "something went wrong"
        throw new IllegalStateException("Bad password, algorithm, mode or padding;" + " no salt, wrong number of iterations or corrupted ciphertext.", e);
    } catch (IllegalBlockSizeException e) {
        throw new IllegalStateException("Bad algorithm, mode or corrupted (resized) ciphertext.", e);
    } catch (GeneralSecurityException e) {
        throw new IllegalStateException(e);
    }
}
Also used : GeneralSecurityException(java.security.GeneralSecurityException) Charset(java.nio.charset.Charset) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) BadPaddingException(javax.crypto.BadPaddingException) SecretKeySpec(javax.crypto.spec.SecretKeySpec) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) MessageDigest(java.security.MessageDigest)

Example 68 with IvParameterSpec

use of javax.crypto.spec.IvParameterSpec in project logging-log4j2 by apache.

the class ThrowableProxyTest method testLogStackTraceWithClassLoaderThatWithCauseSecurityException.

@Test
public void testLogStackTraceWithClassLoaderThatWithCauseSecurityException() throws Exception {
    final SecurityManager sm = System.getSecurityManager();
    try {
        System.setSecurityManager(new SecurityManager() {

            @Override
            public void checkPermission(Permission perm) {
                if (perm instanceof RuntimePermission) {
                    // deny access to the classloader to trigger the security exception
                    if ("getClassLoader".equals(perm.getName())) {
                        throw new SecurityException(perm.toString());
                    }
                }
            }
        });
        final String algorithm = "AES/CBC/PKCS5Padding";
        final Cipher ec = Cipher.getInstance(algorithm);
        // initialization vector
        final byte[] bytes = new byte[16];
        final SecureRandom secureRandom = new SecureRandom();
        secureRandom.nextBytes(bytes);
        final KeyGenerator generator = KeyGenerator.getInstance("AES");
        generator.init(128);
        final IvParameterSpec algorithmParameterSpec = new IvParameterSpec(bytes);
        ec.init(Cipher.ENCRYPT_MODE, generator.generateKey(), algorithmParameterSpec, secureRandom);
        final byte[] raw = new byte[0];
        final byte[] encrypted = ec.doFinal(raw);
        final Cipher dc = Cipher.getInstance(algorithm);
        dc.init(Cipher.DECRYPT_MODE, generator.generateKey(), algorithmParameterSpec, secureRandom);
        dc.doFinal(encrypted);
        fail("expected a javax.crypto.BadPaddingException");
    } catch (final BadPaddingException e) {
        new ThrowableProxy(e);
    } finally {
        // restore the existing security manager
        System.setSecurityManager(sm);
    }
}
Also used : SecureRandom(java.security.SecureRandom) BadPaddingException(javax.crypto.BadPaddingException) Permission(java.security.Permission) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) KeyGenerator(javax.crypto.KeyGenerator) Test(org.junit.Test)

Example 69 with IvParameterSpec

use of javax.crypto.spec.IvParameterSpec in project sling by apache.

the class TopologyRequestValidator method decrypt.

/**
     * Decrypt the body.
     *
     * @param jsonArray the encrypted payload
     * @return the decrypted payload.
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     * @throws UnsupportedEncodingException
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     * @throws InvalidKeySpecException
     * @throws InvalidAlgorithmParameterException
     * @throws JSONException
     */
private String decrypt(JsonArray jsonArray) throws IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeySpecException {
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, getCiperKey(Base64.decodeBase64(jsonArray.getString(0).getBytes("UTF-8"))), new IvParameterSpec(Base64.decodeBase64(jsonArray.getString(1).getBytes("UTF-8"))));
    return new String(cipher.doFinal(Base64.decodeBase64(jsonArray.getString(2).getBytes("UTF-8"))));
}
Also used : IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher)

Example 70 with IvParameterSpec

use of javax.crypto.spec.IvParameterSpec in project Conversations by siacs.

the class AbstractConnectionManager method createOutputStream.

private static OutputStream createOutputStream(DownloadableFile file, boolean gcm, boolean append) {
    FileOutputStream os;
    try {
        os = new FileOutputStream(file, append);
        if (file.getKey() == null) {
            return os;
        }
    } catch (FileNotFoundException e) {
        return null;
    }
    try {
        if (gcm) {
            AEADBlockCipher cipher = new GCMBlockCipher(new AESEngine());
            cipher.init(false, new AEADParameters(new KeyParameter(file.getKey()), 128, file.getIv()));
            return new org.bouncycastle.crypto.io.CipherOutputStream(os, cipher);
        } else {
            IvParameterSpec ips = new IvParameterSpec(file.getIv());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(file.getKey(), "AES"), ips);
            Log.d(Config.LOGTAG, "opening encrypted output stream");
            return new CipherOutputStream(os, cipher);
        }
    } catch (InvalidKeyException e) {
        return null;
    } catch (NoSuchAlgorithmException e) {
        return null;
    } catch (NoSuchPaddingException e) {
        return null;
    } catch (InvalidAlgorithmParameterException e) {
        return null;
    }
}
Also used : AESEngine(org.bouncycastle.crypto.engines.AESEngine) CipherOutputStream(javax.crypto.CipherOutputStream) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) KeyParameter(org.bouncycastle.crypto.params.KeyParameter) FileNotFoundException(java.io.FileNotFoundException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) AEADParameters(org.bouncycastle.crypto.params.AEADParameters) SecretKeySpec(javax.crypto.spec.SecretKeySpec) FileOutputStream(java.io.FileOutputStream) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) AEADBlockCipher(org.bouncycastle.crypto.modes.AEADBlockCipher) GCMBlockCipher(org.bouncycastle.crypto.modes.GCMBlockCipher) GCMBlockCipher(org.bouncycastle.crypto.modes.GCMBlockCipher) AEADBlockCipher(org.bouncycastle.crypto.modes.AEADBlockCipher)

Aggregations

IvParameterSpec (javax.crypto.spec.IvParameterSpec)229 Cipher (javax.crypto.Cipher)150 SecretKeySpec (javax.crypto.spec.SecretKeySpec)107 SecretKey (javax.crypto.SecretKey)49 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)46 InvalidKeyException (java.security.InvalidKeyException)43 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)42 AlgorithmParameterSpec (java.security.spec.AlgorithmParameterSpec)39 IllegalBlockSizeException (javax.crypto.IllegalBlockSizeException)30 BadPaddingException (javax.crypto.BadPaddingException)28 NoSuchPaddingException (javax.crypto.NoSuchPaddingException)25 Key (java.security.Key)21 KeyGenerator (javax.crypto.KeyGenerator)21 IOException (java.io.IOException)19 SecureRandom (java.security.SecureRandom)17 GeneralSecurityException (java.security.GeneralSecurityException)15 MyCipher (org.apache.harmony.crypto.tests.support.MyCipher)15 PBEParameterSpec (javax.crypto.spec.PBEParameterSpec)14 MessageDigest (java.security.MessageDigest)13 KeyParameter (org.bouncycastle.crypto.params.KeyParameter)13