Search in sources :

Example 51 with AlgorithmParameterSpec

use of java.security.spec.AlgorithmParameterSpec in project robovm by robovm.

the class CipherTest method test_updateLjava_nio_ByteBufferLjava_nio_ByteBuffer.

public void test_updateLjava_nio_ByteBufferLjava_nio_ByteBuffer() throws Exception {
    byte[] b = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
    ByteBuffer bInput = ByteBuffer.allocate(256);
    ByteBuffer bOutput = ByteBuffer.allocate(256);
    Cipher c = Cipher.getInstance("DES/CBC/NoPadding");
    c.init(Cipher.ENCRYPT_MODE, CIPHER_KEY_DES);
    bInput.put(b, 0, 10);
    bInput.rewind();
    bOutput.rewind();
    c.update(bInput, bOutput);
    c = Cipher.getInstance("DES/CBC/NoPadding");
    try {
        c.update(bInput, bOutput);
        fail();
    } catch (IllegalStateException expected) {
    }
    c = Cipher.getInstance("DES/CBC/NoPadding");
    c.init(Cipher.ENCRYPT_MODE, CIPHER_KEY_DES);
    bInput = ByteBuffer.allocate(16);
    bInput.put(b, 0, 16);
    bInput.rewind();
    bOutput.rewind();
    c.update(bInput, bOutput);
    AlgorithmParameterSpec ap = new IvParameterSpec(IV);
    c = Cipher.getInstance("DES/CBC/PKCS5Padding");
    c.init(Cipher.DECRYPT_MODE, CIPHER_KEY_DES, ap);
    bInput = ByteBuffer.allocate(64);
    c = Cipher.getInstance("DES/CBC/NoPadding");
    c.init(Cipher.ENCRYPT_MODE, CIPHER_KEY_DES);
    bInput.put(b, 0, 16);
    bInput.rewind();
    try {
        c.update(bInput, bInput);
        fail();
    } catch (IllegalArgumentException expected) {
    }
    c = Cipher.getInstance("DES/CBC/NoPadding");
    c.init(Cipher.ENCRYPT_MODE, CIPHER_KEY_DES);
    bInput.put(b, 0, 16);
    bInput.rewind();
    bOutput.rewind();
    try {
        c.update(bInput, bOutput.asReadOnlyBuffer());
        fail();
    } catch (ReadOnlyBufferException expected) {
    }
    bInput.rewind();
    bInput.put(b, 0, 16);
    bInput.rewind();
    bOutput = ByteBuffer.allocate(8);
    c = Cipher.getInstance("DESede");
    c.init(Cipher.ENCRYPT_MODE, CIPHER_KEY_3DES);
    try {
        c.update(bInput, bOutput);
        fail();
    } catch (ShortBufferException expected) {
    }
}
Also used : ReadOnlyBufferException(java.nio.ReadOnlyBufferException) ShortBufferException(javax.crypto.ShortBufferException) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) MyCipher(org.apache.harmony.crypto.tests.support.MyCipher) ByteBuffer(java.nio.ByteBuffer) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec)

Example 52 with AlgorithmParameterSpec

use of java.security.spec.AlgorithmParameterSpec in project mobile-center-sdk-android by Microsoft.

the class CryptoDefaultKeyGeneratorMockTest method checkParametersPassingForKeyGenerator.

@Test
public void checkParametersPassingForKeyGenerator() throws Exception {
    mockStatic(KeyGenerator.class);
    KeyGenerator mockKeyGenerator = mock(KeyGenerator.class);
    when(KeyGenerator.getInstance(anyString(), anyString())).thenReturn(mockKeyGenerator);
    CryptoUtils.IKeyGenerator keyGenerator = CryptoUtils.DEFAULT_CRYPTO_FACTORY.getKeyGenerator("AES", "MockProvider");
    AlgorithmParameterSpec parameters = mock(AlgorithmParameterSpec.class);
    keyGenerator.init(parameters);
    verify(mockKeyGenerator).init(parameters);
    keyGenerator.generateKey();
    verify(mockKeyGenerator).generateKey();
}
Also used : KeyGenerator(javax.crypto.KeyGenerator) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 53 with AlgorithmParameterSpec

use of java.security.spec.AlgorithmParameterSpec in project jdk8u_jdk by JetBrains.

the class PKCS12KeyStore method encryptPrivateKey.

/*
     * Encrypt private key using Password-based encryption (PBE)
     * as defined in PKCS#5.
     *
     * NOTE: By default, pbeWithSHAAnd3-KeyTripleDES-CBC algorithmID is
     *       used to derive the key and IV.
     *
     * @return encrypted private key encoded as EncryptedPrivateKeyInfo
     */
private byte[] encryptPrivateKey(byte[] data, KeyStore.PasswordProtection passwordProtection) throws IOException, NoSuchAlgorithmException, UnrecoverableKeyException {
    byte[] key = null;
    try {
        String algorithm;
        AlgorithmParameters algParams;
        AlgorithmId algid;
        // Initialize PBE algorithm and parameters
        algorithm = passwordProtection.getProtectionAlgorithm();
        if (algorithm != null) {
            AlgorithmParameterSpec algParamSpec = passwordProtection.getProtectionParameters();
            if (algParamSpec != null) {
                algParams = AlgorithmParameters.getInstance(algorithm);
                algParams.init(algParamSpec);
            } else {
                algParams = getAlgorithmParameters(algorithm);
            }
        } else {
            // Check default key protection algorithm for PKCS12 keystores
            algorithm = AccessController.doPrivileged(new PrivilegedAction<String>() {

                public String run() {
                    String prop = Security.getProperty(KEY_PROTECTION_ALGORITHM[0]);
                    if (prop == null) {
                        prop = Security.getProperty(KEY_PROTECTION_ALGORITHM[1]);
                    }
                    return prop;
                }
            });
            if (algorithm == null || algorithm.isEmpty()) {
                algorithm = "PBEWithSHA1AndDESede";
            }
            algParams = getAlgorithmParameters(algorithm);
        }
        ObjectIdentifier pbeOID = mapPBEAlgorithmToOID(algorithm);
        if (pbeOID == null) {
            throw new IOException("PBE algorithm '" + algorithm + " 'is not supported for key entry protection");
        }
        // Use JCE
        SecretKey skey = getPBEKey(passwordProtection.getPassword());
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, skey, algParams);
        byte[] encryptedKey = cipher.doFinal(data);
        algid = new AlgorithmId(pbeOID, cipher.getParameters());
        if (debug != null) {
            debug.println("  (Cipher algorithm: " + cipher.getAlgorithm() + ")");
        }
        // wrap encrypted private key in EncryptedPrivateKeyInfo
        // as defined in PKCS#8
        EncryptedPrivateKeyInfo encrInfo = new EncryptedPrivateKeyInfo(algid, encryptedKey);
        key = encrInfo.getEncoded();
    } catch (Exception e) {
        UnrecoverableKeyException uke = new UnrecoverableKeyException("Encrypt Private Key failed: " + e.getMessage());
        uke.initCause(e);
        throw uke;
    }
    return key;
}
Also used : KeyStoreException(java.security.KeyStoreException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) UnrecoverableEntryException(java.security.UnrecoverableEntryException) DestroyFailedException(javax.security.auth.DestroyFailedException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SecretKey(javax.crypto.SecretKey) UnrecoverableKeyException(java.security.UnrecoverableKeyException) AlgorithmId(sun.security.x509.AlgorithmId) PrivilegedAction(java.security.PrivilegedAction) EncryptedPrivateKeyInfo(sun.security.pkcs.EncryptedPrivateKeyInfo) Cipher(javax.crypto.Cipher) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec) AlgorithmParameters(java.security.AlgorithmParameters) ObjectIdentifier(sun.security.util.ObjectIdentifier)

Example 54 with AlgorithmParameterSpec

use of java.security.spec.AlgorithmParameterSpec in project jdk8u_jdk by JetBrains.

the class CICODESFuncTest method runTest.

private static void runTest(Provider p, String algo, String mo, String pad, ReadModel whichRead) throws GeneralSecurityException, IOException {
    // Do initialization
    byte[] plainText = TestUtilities.generateBytes(TEXT_LENGTH);
    byte[] iv = TestUtilities.generateBytes(IV_LENGTH);
    AlgorithmParameterSpec aps = new IvParameterSpec(iv);
    try {
        KeyGenerator kg = KeyGenerator.getInstance(algo, p);
        out.println(algo + "/" + mo + "/" + pad + "/" + whichRead);
        SecretKey key = kg.generateKey();
        Cipher ci1 = Cipher.getInstance(algo + "/" + mo + "/" + pad, p);
        if ("CFB72".equalsIgnoreCase(mo) || "OFB20".equalsIgnoreCase(mo)) {
            throw new RuntimeException("NoSuchAlgorithmException not throw when mode" + " is CFB72 or OFB20");
        }
        Cipher ci2 = Cipher.getInstance(algo + "/" + mo + "/" + pad, p);
        if ("ECB".equalsIgnoreCase(mo)) {
            ci1.init(Cipher.ENCRYPT_MODE, key);
            ci2.init(Cipher.DECRYPT_MODE, key);
        } else {
            ci1.init(Cipher.ENCRYPT_MODE, key, aps);
            ci2.init(Cipher.DECRYPT_MODE, key, aps);
        }
        ByteArrayOutputStream baOutput = new ByteArrayOutputStream();
        try (CipherInputStream cInput = new CipherInputStream(new ByteArrayInputStream(plainText), ci1);
            CipherOutputStream ciOutput = new CipherOutputStream(baOutput, ci2)) {
            // Read from the input and write to the output using 2 types
            // of buffering : byte[] and int
            whichRead.read(cInput, ciOutput, ci1, plainText.length);
        }
        // Verify input and output are same.
        if (!Arrays.equals(plainText, baOutput.toByteArray())) {
            throw new RuntimeException("Test failed due to compare fail ");
        }
    } catch (NoSuchAlgorithmException nsaEx) {
        if ("CFB72".equalsIgnoreCase(mo) || "OFB20".equalsIgnoreCase(mo)) {
            out.println("NoSuchAlgorithmException is expected for CFB72 and OFB20");
        } else {
            throw new RuntimeException("Unexpected exception testing: " + algo + "/" + mo + "/" + pad + "/" + whichRead, nsaEx);
        }
    }
}
Also used : SecretKey(javax.crypto.SecretKey) CipherOutputStream(javax.crypto.CipherOutputStream) CipherInputStream(javax.crypto.CipherInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) ByteArrayOutputStream(java.io.ByteArrayOutputStream) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec) KeyGenerator(javax.crypto.KeyGenerator)

Example 55 with AlgorithmParameterSpec

use of java.security.spec.AlgorithmParameterSpec in project jdk8u_jdk by JetBrains.

the class TestSameBuffer method runTest.

public void runTest(String algo, String mo, String pad) throws Exception {
    Cipher ci = null;
    byte[] iv = null;
    AlgorithmParameterSpec aps = null;
    SecretKey key = null;
    try {
        // Initialization
        Random rdm = new Random();
        byte[] plainText = new byte[128];
        rdm.nextBytes(plainText);
        // keep the plain text
        byte[] tmpText = new byte[plainText.length];
        for (int i = 0; i < plainText.length; i++) {
            tmpText[i] = plainText[i];
        }
        ci = Cipher.getInstance(algo + "/" + mo + "/" + pad, PROVIDER);
        KeyGenerator kg = KeyGenerator.getInstance(algo, PROVIDER);
        kg.init(KEY_LENGTH);
        key = kg.generateKey();
        // encrypt
        ci.init(Cipher.ENCRYPT_MODE, key);
        int offset = ci.update(plainText, 0, plainText.length, plainText, 0);
        ci.doFinal(plainText, offset);
        if (!mo.equalsIgnoreCase("ECB")) {
            iv = ci.getIV();
            aps = new IvParameterSpec(iv);
        } else {
            aps = null;
        }
        ci.init(Cipher.DECRYPT_MODE, key, aps);
        byte[] recoveredText = new byte[ci.getOutputSize(plainText.length)];
        ci.doFinal(plainText, 0, plainText.length, recoveredText);
        // Comparison
        if (!java.util.Arrays.equals(tmpText, recoveredText)) {
            System.out.println("Original: ");
            dumpBytes(plainText);
            System.out.println("Recovered: ");
            dumpBytes(recoveredText);
            throw new RuntimeException("Original text is not equal with recovered text, with mode:" + mo);
        }
    } catch (NoSuchAlgorithmException e) {
        //CFB7 and CFB150 are for negative testing
        if (!mo.equalsIgnoreCase("CFB7") && !mo.equalsIgnoreCase("CFB150")) {
            System.out.println("Unexpected NoSuchAlgorithmException with mode: " + mo);
            throw new RuntimeException("Test failed!");
        }
    } catch (NoSuchProviderException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | ShortBufferException | IllegalBlockSizeException | BadPaddingException e) {
        System.out.println("Test failed!");
        throw e;
    }
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) BadPaddingException(javax.crypto.BadPaddingException) InvalidKeyException(java.security.InvalidKeyException) SecretKey(javax.crypto.SecretKey) Random(java.util.Random) ShortBufferException(javax.crypto.ShortBufferException) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) NoSuchProviderException(java.security.NoSuchProviderException) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec) KeyGenerator(javax.crypto.KeyGenerator)

Aggregations

AlgorithmParameterSpec (java.security.spec.AlgorithmParameterSpec)173 IvParameterSpec (javax.crypto.spec.IvParameterSpec)56 Cipher (javax.crypto.Cipher)55 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)49 InvalidKeyException (java.security.InvalidKeyException)42 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)37 SecretKey (javax.crypto.SecretKey)27 SecureRandom (java.security.SecureRandom)24 IllegalBlockSizeException (javax.crypto.IllegalBlockSizeException)24 BadPaddingException (javax.crypto.BadPaddingException)21 NoSuchPaddingException (javax.crypto.NoSuchPaddingException)20 BigInteger (java.math.BigInteger)19 RSAKeyGenParameterSpec (java.security.spec.RSAKeyGenParameterSpec)19 ShortBufferException (javax.crypto.ShortBufferException)19 Key (java.security.Key)18 SecretKeySpec (javax.crypto.spec.SecretKeySpec)18 AlgorithmParameters (java.security.AlgorithmParameters)16 KeyGenerator (javax.crypto.KeyGenerator)16 IOException (java.io.IOException)14 MyCipher (org.apache.harmony.crypto.tests.support.MyCipher)14