Search in sources :

Example 76 with AlgorithmParameterSpec

use of java.security.spec.AlgorithmParameterSpec in project santuario-java by apache.

the class XMLCipher method encryptData.

private EncryptedData encryptData(Document context, Element element, String type, InputStream serializedData) throws /* XMLEncryption */
Exception {
    contextDocument = context;
    if (algorithm == null) {
        throw new XMLEncryptionException("empty", "XMLCipher instance without transformation specified");
    }
    if (serializer instanceof AbstractSerializer) {
        ((AbstractSerializer) serializer).setSecureValidation(secureValidation);
    }
    if (element != null && element.getParentNode() == null) {
        throw new XMLEncryptionException("empty", "The element can't be serialized as it has no parent");
    }
    byte[] serializedOctets = null;
    if (serializedData == null) {
        if (type.equals(EncryptionConstants.TYPE_CONTENT)) {
            NodeList children = element.getChildNodes();
            if (null != children) {
                serializedOctets = serializer.serializeToByteArray(children);
            } else {
                throw new XMLEncryptionException("empty", "Element has no content.");
            }
        } else {
            serializedOctets = serializer.serializeToByteArray(element);
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("Serialized octets:\n" + new String(serializedOctets, StandardCharsets.UTF_8));
        }
    }
    byte[] encryptedBytes = null;
    // Now create the working cipher if none was created already
    Cipher c;
    if (contextCipher == null) {
        c = constructCipher(algorithm, null);
    } else {
        c = contextCipher;
    }
    // Now perform the encryption
    int ivLen = JCEMapper.getIVLengthFromURI(algorithm) / 8;
    byte[] iv = XMLSecurityConstants.generateBytes(ivLen);
    try {
        AlgorithmParameterSpec paramSpec = constructBlockCipherParameters(algorithm, iv);
        c.init(cipherMode, key, paramSpec);
    } catch (InvalidKeyException ike) {
        throw new XMLEncryptionException(ike);
    }
    try {
        if (serializedData != null) {
            int numBytes;
            byte[] buf = new byte[8192];
            try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
                while ((numBytes = serializedData.read(buf)) != -1) {
                    byte[] data = c.update(buf, 0, numBytes);
                    baos.write(data);
                }
                baos.write(c.doFinal());
                encryptedBytes = baos.toByteArray();
            }
        } else {
            encryptedBytes = c.doFinal(serializedOctets);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Expected cipher.outputSize = " + Integer.toString(c.getOutputSize(serializedOctets.length)));
            }
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("Actual cipher.outputSize = " + Integer.toString(encryptedBytes.length));
        }
    } catch (IllegalStateException ise) {
        throw new XMLEncryptionException(ise);
    } catch (IllegalBlockSizeException ibse) {
        throw new XMLEncryptionException(ibse);
    } catch (BadPaddingException bpe) {
        throw new XMLEncryptionException(bpe);
    } catch (UnsupportedEncodingException uee) {
        throw new XMLEncryptionException(uee);
    }
    // the original IV that was generated
    if (c.getIV() != null) {
        iv = c.getIV();
    }
    // Now build up to a properly XML Encryption encoded octet stream
    byte[] finalEncryptedBytes = new byte[iv.length + encryptedBytes.length];
    System.arraycopy(iv, 0, finalEncryptedBytes, 0, iv.length);
    System.arraycopy(encryptedBytes, 0, finalEncryptedBytes, iv.length, encryptedBytes.length);
    String base64EncodedEncryptedOctets = Base64.getMimeEncoder().encodeToString(finalEncryptedBytes);
    LOG.debug("Encrypted octets:\n{}", base64EncodedEncryptedOctets);
    LOG.debug("Encrypted octets length = {}", base64EncodedEncryptedOctets.length());
    try {
        CipherData cd = ed.getCipherData();
        CipherValue cv = cd.getCipherValue();
        cv.setValue(base64EncodedEncryptedOctets);
        if (type != null) {
            ed.setType(new URI(type).toString());
        }
        EncryptionMethod method = factory.newEncryptionMethod(new URI(algorithm).toString());
        method.setDigestAlgorithm(digestAlg);
        ed.setEncryptionMethod(method);
    } catch (URISyntaxException ex) {
        throw new XMLEncryptionException(ex);
    }
    return ed;
}
Also used : NodeList(org.w3c.dom.NodeList) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) BadPaddingException(javax.crypto.BadPaddingException) URISyntaxException(java.net.URISyntaxException) InvalidKeyException(java.security.InvalidKeyException) URI(java.net.URI) Cipher(javax.crypto.Cipher) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec)

Example 77 with AlgorithmParameterSpec

use of java.security.spec.AlgorithmParameterSpec in project keepass2android by PhilippC.

the class WrapCipherSpi method engineInit.

@SuppressWarnings("unchecked")
protected void engineInit(int opmode, Key key, AlgorithmParameters params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException {
    AlgorithmParameterSpec paramSpec = null;
    if (params != null) {
        for (int i = 0; i != availableSpecs.length; i++) {
            try {
                paramSpec = params.getParameterSpec(availableSpecs[i]);
                break;
            } catch (Exception e) {
            // try next spec
            }
        }
        if (paramSpec == null) {
            throw new InvalidAlgorithmParameterException("can't handle parameter " + params.toString());
        }
    }
    engineParams = params;
    engineInit(opmode, key, paramSpec, random);
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) InvalidCipherTextException(org.bouncycastle.crypto.InvalidCipherTextException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) ShortBufferException(javax.crypto.ShortBufferException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) BadPaddingException(javax.crypto.BadPaddingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) NoSuchProviderException(java.security.NoSuchProviderException)

Example 78 with AlgorithmParameterSpec

use of java.security.spec.AlgorithmParameterSpec in project keepass2android by PhilippC.

the class JCEBlockCipher method engineInit.

protected void engineInit(int opmode, Key key, AlgorithmParameters params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException {
    AlgorithmParameterSpec paramSpec = null;
    if (params != null) {
        for (int i = 0; i != availableSpecs.length; i++) {
            try {
                paramSpec = params.getParameterSpec(availableSpecs[i]);
                break;
            } catch (Exception e) {
            // try again if possible
            }
        }
        if (paramSpec == null) {
            throw new InvalidAlgorithmParameterException("can't handle parameter " + params.toString());
        }
    }
    engineInit(opmode, key, paramSpec, random);
    engineParams = params;
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) InvalidCipherTextException(org.bouncycastle.crypto.InvalidCipherTextException) DataLengthException(org.bouncycastle.crypto.DataLengthException) InvalidParameterException(java.security.InvalidParameterException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) ShortBufferException(javax.crypto.ShortBufferException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) BadPaddingException(javax.crypto.BadPaddingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException)

Example 79 with AlgorithmParameterSpec

use of java.security.spec.AlgorithmParameterSpec in project keepass2android by PhilippC.

the class JCEStreamCipher method engineInit.

protected void engineInit(int opmode, Key key, AlgorithmParameters params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException {
    AlgorithmParameterSpec paramSpec = null;
    if (params != null) {
        for (int i = 0; i != availableSpecs.length; i++) {
            try {
                paramSpec = params.getParameterSpec(availableSpecs[i]);
                break;
            } catch (Exception e) {
                continue;
            }
        }
        if (paramSpec == null) {
            throw new InvalidAlgorithmParameterException("can't handle parameter " + params.toString());
        }
    }
    engineInit(opmode, key, paramSpec, random);
    engineParams = params;
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) DataLengthException(org.bouncycastle.crypto.DataLengthException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) ShortBufferException(javax.crypto.ShortBufferException) InvalidKeyException(java.security.InvalidKeyException)

Example 80 with AlgorithmParameterSpec

use of java.security.spec.AlgorithmParameterSpec in project santuario-java by apache.

the class CanonicalizationMethodTest method testConstructor.

@org.junit.Test
public void testConstructor() throws Exception {
    // test newAlgorithmMethod(String algorithm,
    // AlgorithmParameterSpec params)
    // for generating CanonicalizationMethod objects
    CanonicalizationMethod cm;
    for (int i = 0; i < C14N_ALGOS.length; i++) {
        String algo = C14N_ALGOS[i];
        cm = factory.newCanonicalizationMethod(algo, (C14NMethodParameterSpec) null);
        assertNotNull(cm);
        assertEquals(cm.getAlgorithm(), algo);
        assertNull(cm.getParameterSpec());
        try {
            cm = factory.newCanonicalizationMethod(algo, new TestUtils.MyOwnC14nParameterSpec());
            fail("Should raise an IAPE for invalid c14n parameters");
        } catch (InvalidAlgorithmParameterException iape) {
        } catch (Exception ex) {
            fail("Should raise a IAPE instead of " + ex);
        }
        if (algo.equals(CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS) || algo.equals(CanonicalizationMethod.EXCLUSIVE)) {
            cm = factory.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, new ExcC14NParameterSpec());
            AlgorithmParameterSpec aps = cm.getParameterSpec();
            assertNotNull(aps);
            assertTrue(aps instanceof ExcC14NParameterSpec);
        }
    }
    try {
        cm = factory.newCanonicalizationMethod(null, (C14NMethodParameterSpec) null);
        fail("Should raise a NPE for null algo");
    } catch (NullPointerException npe) {
    } catch (Exception ex) {
        fail("Should raise a NPE instead of " + ex);
    }
    try {
        cm = factory.newCanonicalizationMethod("non-existent", (C14NMethodParameterSpec) null);
        fail("Should raise an NSAE for non-existent algos");
    } catch (NoSuchAlgorithmException nsae) {
    } catch (Exception ex) {
        fail("Should raise an NSAE instead of " + ex);
    }
}
Also used : ExcC14NParameterSpec(javax.xml.crypto.dsig.spec.ExcC14NParameterSpec) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec) C14NMethodParameterSpec(javax.xml.crypto.dsig.spec.C14NMethodParameterSpec)

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