Search in sources :

Example 1 with SecureRandom

use of java.security.SecureRandom in project camel by apache.

the class PGPKeyAccessDataFormat method marshal.

public void marshal(Exchange exchange, Object graph, OutputStream outputStream) throws Exception {
    //NOPMD
    List<String> userids = determineEncryptionUserIds(exchange);
    List<PGPPublicKey> keys = publicKeyAccessor.getEncryptionKeys(exchange, userids);
    if (keys.isEmpty()) {
        throw new IllegalArgumentException("Cannot PGP encrypt message. No public encryption key found for the User Ids " + userids + " in the public keyring. Either specify other User IDs or add correct public keys to the keyring.");
    }
    exchange.getOut().setHeader(NUMBER_OF_ENCRYPTION_KEYS, Integer.valueOf(keys.size()));
    InputStream input = ExchangeHelper.convertToMandatoryType(exchange, InputStream.class, graph);
    if (armored) {
        outputStream = new ArmoredOutputStream(outputStream);
    }
    PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(new JcePGPDataEncryptorBuilder(findAlgorithm(exchange)).setWithIntegrityPacket(integrity).setSecureRandom(new SecureRandom()).setProvider(getProvider()));
    // several keys can be added
    for (PGPPublicKey key : keys) {
        encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(key));
    }
    OutputStream encOut = encGen.open(outputStream, new byte[BUFFER_SIZE]);
    OutputStream comOut;
    if (withCompressedDataPacket) {
        PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(findCompressionAlgorithm(exchange));
        comOut = new BufferedOutputStream(comData.open(encOut));
    } else {
        comOut = encOut;
        LOG.debug("No Compressed Data packet is added");
    }
    List<PGPSignatureGenerator> sigGens = createSignatureGenerator(exchange, comOut);
    PGPLiteralDataGenerator litData = new PGPLiteralDataGenerator();
    String fileName = findFileName(exchange);
    OutputStream litOut = litData.open(comOut, PGPLiteralData.BINARY, fileName, new Date(), new byte[BUFFER_SIZE]);
    try {
        byte[] buffer = new byte[BUFFER_SIZE];
        int bytesRead;
        while ((bytesRead = input.read(buffer)) != -1) {
            litOut.write(buffer, 0, bytesRead);
            if (sigGens != null && !sigGens.isEmpty()) {
                for (PGPSignatureGenerator sigGen : sigGens) {
                    // not nested therefore it is the same for all
                    // can this be improved that we only do it for one sigGen and set the result on the others?
                    sigGen.update(buffer, 0, bytesRead);
                }
            }
            litOut.flush();
        }
    } finally {
        IOHelper.close(litOut);
        if (sigGens != null && !sigGens.isEmpty()) {
            // reverse order
            for (int i = sigGens.size() - 1; i > -1; i--) {
                PGPSignatureGenerator sigGen = sigGens.get(i);
                sigGen.generate().encode(comOut);
            }
        }
        IOHelper.close(comOut, encOut, outputStream, input);
    }
}
Also used : PGPSignatureGenerator(org.bouncycastle.openpgp.PGPSignatureGenerator) InputStream(java.io.InputStream) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) ArmoredOutputStream(org.bouncycastle.bcpg.ArmoredOutputStream) PGPCompressedDataGenerator(org.bouncycastle.openpgp.PGPCompressedDataGenerator) PGPPublicKey(org.bouncycastle.openpgp.PGPPublicKey) ArmoredOutputStream(org.bouncycastle.bcpg.ArmoredOutputStream) SecureRandom(java.security.SecureRandom) PGPLiteralDataGenerator(org.bouncycastle.openpgp.PGPLiteralDataGenerator) PGPEncryptedDataGenerator(org.bouncycastle.openpgp.PGPEncryptedDataGenerator) Date(java.util.Date) JcePublicKeyKeyEncryptionMethodGenerator(org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyKeyEncryptionMethodGenerator) BufferedOutputStream(java.io.BufferedOutputStream) JcePGPDataEncryptorBuilder(org.bouncycastle.openpgp.operator.jcajce.JcePGPDataEncryptorBuilder)

Example 2 with SecureRandom

use of java.security.SecureRandom in project camel by apache.

the class PGPDataFormatTest method createEncryptedNonCompressedData.

void createEncryptedNonCompressedData(ByteArrayOutputStream bos, String keyringPath) throws Exception, IOException, PGPException, UnsupportedEncodingException {
    PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(new JcePGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.CAST5).setSecureRandom(new SecureRandom()).setProvider(getProvider()));
    encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(readPublicKey(keyringPath)));
    OutputStream encOut = encGen.open(bos, new byte[512]);
    PGPLiteralDataGenerator litData = new PGPLiteralDataGenerator();
    OutputStream litOut = litData.open(encOut, PGPLiteralData.BINARY, PGPLiteralData.CONSOLE, new Date(), new byte[512]);
    try {
        litOut.write("Test Message Without Compression".getBytes("UTF-8"));
        litOut.flush();
    } finally {
        IOHelper.close(litOut);
        IOHelper.close(encOut, bos);
    }
}
Also used : BCPGOutputStream(org.bouncycastle.bcpg.BCPGOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) SecureRandom(java.security.SecureRandom) PGPLiteralDataGenerator(org.bouncycastle.openpgp.PGPLiteralDataGenerator) PGPEncryptedDataGenerator(org.bouncycastle.openpgp.PGPEncryptedDataGenerator) Date(java.util.Date) JcePGPDataEncryptorBuilder(org.bouncycastle.openpgp.operator.jcajce.JcePGPDataEncryptorBuilder) JcePublicKeyKeyEncryptionMethodGenerator(org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyKeyEncryptionMethodGenerator)

Example 3 with SecureRandom

use of java.security.SecureRandom in project camel by apache.

the class CryptoDataFormatTest method createRouteBuilders.

protected RouteBuilder[] createRouteBuilders() throws Exception {
    return new RouteBuilder[] { new RouteBuilder() {

        public void configure() throws Exception {
            // START SNIPPET: basic
            KeyGenerator generator = KeyGenerator.getInstance("DES");
            CryptoDataFormat cryptoFormat = new CryptoDataFormat("DES", generator.generateKey());
            from("direct:basic-encryption").marshal(cryptoFormat).to("mock:encrypted").unmarshal(cryptoFormat).to("mock:unencrypted");
        // END SNIPPET: basic
        }
    }, new RouteBuilder() {

        public void configure() throws Exception {
            // START SNIPPET: init-vector
            KeyGenerator generator = KeyGenerator.getInstance("DES");
            byte[] initializationVector = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };
            CryptoDataFormat cryptoFormat = new CryptoDataFormat("DES/CBC/PKCS5Padding", generator.generateKey());
            cryptoFormat.setInitializationVector(initializationVector);
            from("direct:init-vector").marshal(cryptoFormat).to("mock:encrypted").unmarshal(cryptoFormat).to("mock:unencrypted");
        // END SNIPPET: init-vector
        }
    }, new RouteBuilder() {

        public void configure() throws Exception {
            // START SNIPPET: inline-init-vector
            KeyGenerator generator = KeyGenerator.getInstance("DES");
            byte[] initializationVector = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };
            SecretKey key = generator.generateKey();
            CryptoDataFormat cryptoFormat = new CryptoDataFormat("DES/CBC/PKCS5Padding", key);
            cryptoFormat.setInitializationVector(initializationVector);
            cryptoFormat.setShouldInlineInitializationVector(true);
            CryptoDataFormat decryptFormat = new CryptoDataFormat("DES/CBC/PKCS5Padding", key);
            decryptFormat.setShouldInlineInitializationVector(true);
            from("direct:inline").marshal(cryptoFormat).to("mock:encrypted").unmarshal(decryptFormat).to("mock:unencrypted");
        // END SNIPPET: inline-init-vector
        }
    }, new RouteBuilder() {

        public void configure() throws Exception {
            // START SNIPPET: hmac
            KeyGenerator generator = KeyGenerator.getInstance("DES");
            CryptoDataFormat cryptoFormat = new CryptoDataFormat("DES", generator.generateKey());
            cryptoFormat.setShouldAppendHMAC(true);
            from("direct:hmac").marshal(cryptoFormat).to("mock:encrypted").unmarshal(cryptoFormat).to("mock:unencrypted");
        // END SNIPPET: hmac
        }
    }, new RouteBuilder() {

        public void configure() throws Exception {
            // START SNIPPET: hmac-algorithm
            KeyGenerator generator = KeyGenerator.getInstance("DES");
            CryptoDataFormat cryptoFormat = new CryptoDataFormat("DES", generator.generateKey());
            cryptoFormat.setShouldAppendHMAC(true);
            cryptoFormat.setMacAlgorithm("HmacMD5");
            from("direct:hmac-algorithm").marshal(cryptoFormat).to("mock:encrypted").unmarshal(cryptoFormat).to("mock:unencrypted");
        // END SNIPPET: hmac-algorithm
        }
    }, new RouteBuilder() {

        public void configure() throws Exception {
            // START SNIPPET: hmac-sha256-algorithm
            KeyGenerator generator = KeyGenerator.getInstance("DES");
            CryptoDataFormat cryptoFormat = new CryptoDataFormat("DES", generator.generateKey());
            cryptoFormat.setShouldAppendHMAC(true);
            cryptoFormat.setMacAlgorithm("HmacSHA256");
            from("direct:hmac-sha-256-algorithm").marshal(cryptoFormat).to("mock:encrypted").unmarshal(cryptoFormat).to("mock:unencrypted");
        // END SNIPPET: hmac-sha256-algorithm
        }
    }, new RouteBuilder() {

        public void configure() throws Exception {
            // START SNIPPET: key-in-header
            CryptoDataFormat cryptoFormat = new CryptoDataFormat("DES", null);
            /**
                 * Note: the header containing the key should be cleared after
                 * marshalling to stop it from leaking by accident and
                 * potentially being compromised. The processor version below is
                 * arguably better as the key is left in the header when you use
                 * the DSL leaks the fact that camel encryption was used.
                 */
            from("direct:key-in-header-encrypt").marshal(cryptoFormat).removeHeader(CryptoDataFormat.KEY).to("mock:encrypted");
            from("direct:key-in-header-decrypt").unmarshal(cryptoFormat).process(new Processor() {

                public void process(Exchange exchange) throws Exception {
                    exchange.getIn().getHeaders().remove(CryptoDataFormat.KEY);
                    exchange.getOut().copyFrom(exchange.getIn());
                }
            }).to("mock:unencrypted");
        // END SNIPPET: key-in-header
        }
    }, new RouteBuilder() {

        public void configure() throws Exception {
            // START SNIPPET: 3DES-ECB
            KeyGenerator generator = KeyGenerator.getInstance("DESede");
            CryptoDataFormat cryptoFormat = new CryptoDataFormat("DESede/ECB/PKCS5Padding", generator.generateKey());
            from("direct:3des-ecb-encryption").marshal(cryptoFormat).to("mock:encrypted").unmarshal(cryptoFormat).to("mock:unencrypted");
        // END SNIPPET: 3DES-ECB
        }
    }, new RouteBuilder() {

        public void configure() throws Exception {
            // START SNIPPET: 3DES-CBC
            KeyGenerator generator = KeyGenerator.getInstance("DES");
            byte[] iv = new byte[8];
            SecureRandom random = new SecureRandom();
            random.nextBytes(iv);
            Key key = generator.generateKey();
            CryptoDataFormat encCryptoFormat = new CryptoDataFormat("DES/CBC/PKCS5Padding", key);
            encCryptoFormat.setInitializationVector(iv);
            encCryptoFormat.setShouldInlineInitializationVector(true);
            CryptoDataFormat decCryptoFormat = new CryptoDataFormat("DES/CBC/PKCS5Padding", key);
            decCryptoFormat.setShouldInlineInitializationVector(true);
            from("direct:3des-cbc-encryption").marshal(encCryptoFormat).to("mock:encrypted").unmarshal(decCryptoFormat).to("mock:unencrypted");
        // END SNIPPET: 3DES-CBC
        }
    }, new RouteBuilder() {

        public void configure() throws Exception {
            // START SNIPPET: AES-128-ECB
            KeyGenerator generator = KeyGenerator.getInstance("AES");
            CryptoDataFormat cryptoFormat = new CryptoDataFormat("AES/ECB/PKCS5Padding", generator.generateKey());
            from("direct:aes-128-ecb-encryption").marshal(cryptoFormat).to("mock:encrypted").unmarshal(cryptoFormat).to("mock:unencrypted");
        // END SNIPPET: AES-128-ECB
        }
    } };
}
Also used : Exchange(org.apache.camel.Exchange) SecretKey(javax.crypto.SecretKey) Processor(org.apache.camel.Processor) RouteBuilder(org.apache.camel.builder.RouteBuilder) SecureRandom(java.security.SecureRandom) KeyGenerator(javax.crypto.KeyGenerator) Key(java.security.Key) SecretKey(javax.crypto.SecretKey)

Example 4 with SecureRandom

use of java.security.SecureRandom in project camel by apache.

the class SigningProcessor method initSignatureService.

protected Signature initSignatureService(Exchange exchange) throws Exception {
    PrivateKey pk = getPrivateKeyFromKeystoreOrExchange(exchange);
    SecureRandom random = config.getSecureRandom();
    Signature service = createSignatureService();
    if (random != null) {
        service.initSign(pk, random);
    } else {
        service.initSign(pk);
    }
    return service;
}
Also used : PrivateKey(java.security.PrivateKey) Signature(java.security.Signature) SecureRandom(java.security.SecureRandom)

Example 5 with SecureRandom

use of java.security.SecureRandom in project camel by apache.

the class SSLContextParameters method createSSLContext.

/**
     * Creates an {@link SSLContext} based on the related configuration options
     * of this instance. Namely, {@link #keyManagers}, {@link #trustManagers}, and
     * {@link #secureRandom}, but also respecting the chosen provider and secure
     * socket protocol as well.
     *
     * @param camelContext  The camel context
     *
     * @return a newly configured instance
     *
     * @throws GeneralSecurityException if there is a problem in this instances
     *             configuration or that of its nested configuration options
     * @throws IOException if there is an error reading a key/trust store
     */
public SSLContext createSSLContext(CamelContext camelContext) throws GeneralSecurityException, IOException {
    if (camelContext != null) {
        // setup CamelContext before creating SSLContext
        setCamelContext(camelContext);
        if (keyManagers != null) {
            keyManagers.setCamelContext(camelContext);
        }
        if (trustManagers != null) {
            trustManagers.setCamelContext(camelContext);
        }
        if (secureRandom != null) {
            secureRandom.setCamelContext(camelContext);
        }
        if (clientParameters != null) {
            clientParameters.setCamelContext(camelContext);
        }
        if (serverParameters != null) {
            serverParameters.setCamelContext(camelContext);
        }
    }
    LOG.trace("Creating SSLContext from SSLContextParameters [{}].", this);
    LOG.info("Available providers: {}.", Security.getProviders());
    KeyManager[] keyManagers = this.keyManagers == null ? null : this.keyManagers.createKeyManagers();
    TrustManager[] trustManagers = this.trustManagers == null ? null : this.trustManagers.createTrustManagers();
    SecureRandom secureRandom = this.secureRandom == null ? null : this.secureRandom.createSecureRandom();
    SSLContext context;
    if (this.getProvider() == null) {
        context = SSLContext.getInstance(this.parsePropertyValue(this.getSecureSocketProtocol()));
    } else {
        context = SSLContext.getInstance(this.parsePropertyValue(this.getSecureSocketProtocol()), this.parsePropertyValue(this.getProvider()));
    }
    if (this.getCertAlias() != null && keyManagers != null) {
        for (int idx = 0; idx < keyManagers.length; idx++) {
            if (keyManagers[idx] instanceof X509KeyManager) {
                try {
                    keyManagers[idx] = new AliasedX509ExtendedKeyManager(this.getCertAlias(), (X509KeyManager) keyManagers[idx]);
                } catch (Exception e) {
                    throw new GeneralSecurityException(e);
                }
            }
        }
    }
    LOG.debug("SSLContext [{}], initialized from [{}], is using provider [{}], protocol [{}], key managers {}, trust managers {}, and secure random [{}].", new Object[] { context, this, context.getProvider(), context.getProtocol(), keyManagers, trustManagers, secureRandom });
    context.init(keyManagers, trustManagers, secureRandom);
    this.configureSSLContext(context);
    // Decorate the context.
    context = new SSLContextDecorator(new SSLContextSpiDecorator(context, this.getSSLEngineConfigurers(context), this.getSSLSocketFactoryConfigurers(context), this.getSSLServerSocketFactoryConfigurers(context)));
    return context;
}
Also used : GeneralSecurityException(java.security.GeneralSecurityException) SecureRandom(java.security.SecureRandom) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) GeneralSecurityException(java.security.GeneralSecurityException) TrustManager(javax.net.ssl.TrustManager) X509KeyManager(javax.net.ssl.X509KeyManager) X509KeyManager(javax.net.ssl.X509KeyManager) KeyManager(javax.net.ssl.KeyManager)

Aggregations

SecureRandom (java.security.SecureRandom)639 SSLContext (javax.net.ssl.SSLContext)94 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)87 IOException (java.io.IOException)68 Test (org.junit.Test)62 SecretKey (javax.crypto.SecretKey)59 KeyGenerator (javax.crypto.KeyGenerator)53 X509Certificate (java.security.cert.X509Certificate)50 TrustManager (javax.net.ssl.TrustManager)50 Cipher (javax.crypto.Cipher)43 X509TrustManager (javax.net.ssl.X509TrustManager)40 KeyPairGenerator (java.security.KeyPairGenerator)38 BigInteger (java.math.BigInteger)35 InvalidKeyException (java.security.InvalidKeyException)34 CertificateException (java.security.cert.CertificateException)33 KeyPair (java.security.KeyPair)30 KeyStore (java.security.KeyStore)29 Random (java.util.Random)28 SecretKeySpec (javax.crypto.spec.SecretKeySpec)28 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)27