Search in sources :

Example 1 with PrivateKey

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

the class SignatureTests method createRouteBuilders.

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

        public void configure() throws Exception {
            // START SNIPPET: basic
            from("direct:keypair").to("crypto:sign:basic?privateKey=#myPrivateKey", "crypto:verify:basic?publicKey=#myPublicKey", "mock:result");
        // END SNIPPET: basic
        }
    }, new RouteBuilder() {

        public void configure() throws Exception {
            // START SNIPPET: algorithm
            keyPair = getKeyPair("RSA");
            PrivateKey privateKey = keyPair.getPrivate();
            PublicKey publicKey = keyPair.getPublic();
            // we can set the keys explicitly on the endpoint instances.
            context.getEndpoint("crypto:sign:rsa?algorithm=MD5withRSA", DigitalSignatureEndpoint.class).setPrivateKey(privateKey);
            context.getEndpoint("crypto:verify:rsa?algorithm=MD5withRSA", DigitalSignatureEndpoint.class).setPublicKey(publicKey);
            from("direct:algorithm").to("crypto:sign:rsa?algorithm=MD5withRSA", "crypto:verify:rsa?algorithm=MD5withRSA", "mock:result");
        // END SNIPPET: algorithm
        }
    }, new RouteBuilder() {

        public void configure() throws Exception {
            // START SNIPPET: rsa-sha1
            keyPair = getKeyPair("RSA");
            PrivateKey privateKey = keyPair.getPrivate();
            PublicKey publicKey = keyPair.getPublic();
            // we can set the keys explicitly on the endpoint instances.
            context.getEndpoint("crypto:sign:rsa?algorithm=SHA1withRSA", DigitalSignatureEndpoint.class).setPrivateKey(privateKey);
            context.getEndpoint("crypto:verify:rsa?algorithm=SHA1withRSA", DigitalSignatureEndpoint.class).setPublicKey(publicKey);
            from("direct:rsa-sha1").to("crypto:sign:rsa?algorithm=SHA1withRSA", "crypto:verify:rsa?algorithm=SHA1withRSA", "mock:result");
        // END SNIPPET: rsa-sha1
        }
    }, new RouteBuilder() {

        public void configure() throws Exception {
            // START SNIPPET: rsa-sha256
            keyPair = getKeyPair("RSA");
            PrivateKey privateKey = keyPair.getPrivate();
            PublicKey publicKey = keyPair.getPublic();
            // we can set the keys explicitly on the endpoint instances.
            context.getEndpoint("crypto:sign:rsa?algorithm=SHA256withRSA", DigitalSignatureEndpoint.class).setPrivateKey(privateKey);
            context.getEndpoint("crypto:verify:rsa?algorithm=SHA256withRSA", DigitalSignatureEndpoint.class).setPublicKey(publicKey);
            from("direct:rsa-sha256").to("crypto:sign:rsa?algorithm=SHA256withRSA", "crypto:verify:rsa?algorithm=SHA256withRSA", "mock:result");
        // END SNIPPET: rsa-sha256
        }
    }, new RouteBuilder() {

        public void configure() throws Exception {
            // START SNIPPET: buffersize
            from("direct:buffersize").to("crypto:sign:buffer?privateKey=#myPrivateKey&buffersize=1024", "crypto:verify:buffer?publicKey=#myPublicKey&buffersize=1024", "mock:result");
        // END SNIPPET: buffersize
        }
    }, new RouteBuilder() {

        public void configure() throws Exception {
            // START SNIPPET: provider
            from("direct:provider").to("crypto:sign:provider?privateKey=#myPrivateKey&provider=SUN", "crypto:verify:provider?publicKey=#myPublicKey&provider=SUN", "mock:result");
        // END SNIPPET: provider
        }
    }, new RouteBuilder() {

        public void configure() throws Exception {
            // START SNIPPET: certificate
            from("direct:certificate").to("crypto:sign:withcert?privateKey=#myPrivateKey", "crypto:verify:withcert?certificate=#myCert", "mock:result");
        // END SNIPPET: certificate
        }
    }, new RouteBuilder() {

        public void configure() throws Exception {
            // START SNIPPET: keystore
            from("direct:keystore").to("crypto:sign:keystore?keystore=#keystore&alias=bob&password=letmein", "crypto:verify:keystore?keystore=#keystore&alias=bob", "mock:result");
        // END SNIPPET: keystore
        }
    }, new RouteBuilder() {

        public void configure() throws Exception {
            // START SNIPPET: keystore
            from("direct:keystoreParameters").to("crypto:sign:keyStoreParameters?keyStoreParameters=#signatureParams&alias=bob&password=letmein", "crypto:verify:keyStoreParameters?keyStoreParameters=#signatureParams&alias=bob", "mock:result");
        // END SNIPPET: keystore
        }
    }, new RouteBuilder() {

        public void configure() throws Exception {
            // START SNIPPET: signature-header
            from("direct:signature-header").to("crypto:sign:another?privateKey=#myPrivateKey&signatureHeader=AnotherDigitalSignature", "crypto:verify:another?publicKey=#myPublicKey&signatureHeader=AnotherDigitalSignature", "mock:result");
        // END SNIPPET: signature-header
        }
    }, new RouteBuilder() {

        public void configure() throws Exception {
            // START SNIPPET: random
            from("direct:random").to("crypto:sign:another?privateKey=#myPrivateKey&secureRandom=#someRandom", "crypto:verify:another?publicKey=#myPublicKey&secureRandom=#someRandom", "mock:result");
        // END SNIPPET: random
        }
    }, new RouteBuilder() {

        public void configure() throws Exception {
            // START SNIPPET: alias
            from("direct:alias-sign").to("crypto:sign:alias?keystore=#keystore");
            from("direct:alias-verify").to("crypto:verify:alias?keystore=#keystore", "mock:result");
        // END SNIPPET: alias
        }
    }, new RouteBuilder() {

        public void configure() throws Exception {
            // START SNIPPET: headerkey
            from("direct:headerkey-sign").to("crypto:sign:alias");
            from("direct:headerkey-verify").to("crypto:verify:alias", "mock:result");
        // END SNIPPET: headerkey
        }
    }, new RouteBuilder() {

        public void configure() throws Exception {
            // START SNIPPET: clearheaders
            from("direct:headers").to("crypto:sign:headers?privateKey=#myPrivateKey", "crypto:verify:headers?publicKey=#myPublicKey&clearHeaders=false", "mock:result");
        // END SNIPPET: clearheaders
        }
    } };
}
Also used : PrivateKey(java.security.PrivateKey) RouteBuilder(org.apache.camel.builder.RouteBuilder) PublicKey(java.security.PublicKey)

Example 2 with PrivateKey

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

the class SignatureTests method testProvideCertificateInHeader.

@Test
public void testProvideCertificateInHeader() throws Exception {
    setupMock();
    Exchange unsigned = getMandatoryEndpoint("direct:signature-property").createExchange();
    unsigned.getIn().setBody(payload);
    // create a keypair
    KeyStore keystore = loadKeystore();
    Certificate certificate = keystore.getCertificate("bob");
    PrivateKey pk = (PrivateKey) keystore.getKey("bob", "letmein".toCharArray());
    // sign with the private key
    unsigned.getIn().setHeader(SIGNATURE_PRIVATE_KEY, pk);
    template.send("direct:headerkey-sign", unsigned);
    // verify with the public key
    Exchange signed = getMandatoryEndpoint("direct:alias-sign").createExchange();
    signed.getIn().copyFrom(unsigned.getOut());
    signed.getIn().setHeader(SIGNATURE_PUBLIC_KEY_OR_CERT, certificate);
    template.send("direct:headerkey-verify", signed);
    assertMockEndpointsSatisfied();
}
Also used : Exchange(org.apache.camel.Exchange) PrivateKey(java.security.PrivateKey) KeyStore(java.security.KeyStore) Certificate(java.security.cert.Certificate) Test(org.junit.Test)

Example 3 with PrivateKey

use of java.security.PrivateKey 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 4 with PrivateKey

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

the class RSAKeyPairIdentity method getSignature.

@Override
public byte[] getSignature(byte[] data) {
    PrivateKey prvKey = keyPair.getPrivate();
    Signature sig;
    try {
        sig = Signature.getInstance("SHA1withRSA");
        sig.initSign(prvKey);
        sig.update(data);
        byte[] sshRsa = ALGORITHM_TYPE.getBytes();
        byte[] signature = sig.sign();
        byte[] result = new byte[sshRsa.length + 4 + signature.length + 4];
        int index = 0;
        byte[] intAsByteArray = ByteBuffer.allocate(4).putInt(sshRsa.length).array();
        System.arraycopy(intAsByteArray, 0, result, index, 4);
        index += 4;
        System.arraycopy(sshRsa, 0, result, index, sshRsa.length);
        index += sshRsa.length;
        intAsByteArray = ByteBuffer.allocate(4).putInt(signature.length).array();
        System.arraycopy(intAsByteArray, 0, result, index, 4);
        index += 4;
        System.arraycopy(signature, 0, result, index, signature.length);
        return result;
    } catch (NoSuchAlgorithmException e) {
        log.error("Cannot sign", e);
    } catch (InvalidKeyException e) {
        log.error("Cannot sign", e);
    } catch (SignatureException e) {
        log.error("Cannot sign", e);
    }
    return null;
}
Also used : PrivateKey(java.security.PrivateKey) Signature(java.security.Signature) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SignatureException(java.security.SignatureException) InvalidKeyException(java.security.InvalidKeyException)

Example 5 with PrivateKey

use of java.security.PrivateKey in project tomcat by apache.

the class OpenSSLContext method init.

/**
     * Setup the SSL_CTX.
     *
     * @param kms Must contain a KeyManager of the type
     *            {@code OpenSSLKeyManager}
     * @param tms Must contain a TrustManager of the type
     *            {@code X509TrustManager}
     * @param sr Is not used for this implementation.
     */
@Override
public synchronized void init(KeyManager[] kms, TrustManager[] tms, SecureRandom sr) {
    if (initialized) {
        log.warn(sm.getString("openssl.doubleInit"));
        return;
    }
    try {
        if (sslHostConfig.getInsecureRenegotiation()) {
            SSLContext.setOptions(ctx, SSL.SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
        } else {
            SSLContext.clearOptions(ctx, SSL.SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
        }
        // client's)
        if (sslHostConfig.getHonorCipherOrder()) {
            SSLContext.setOptions(ctx, SSL.SSL_OP_CIPHER_SERVER_PREFERENCE);
        } else {
            SSLContext.clearOptions(ctx, SSL.SSL_OP_CIPHER_SERVER_PREFERENCE);
        }
        // Disable compression if requested
        if (sslHostConfig.getDisableCompression()) {
            SSLContext.setOptions(ctx, SSL.SSL_OP_NO_COMPRESSION);
        } else {
            SSLContext.clearOptions(ctx, SSL.SSL_OP_NO_COMPRESSION);
        }
        // Disable TLS Session Tickets (RFC4507) to protect perfect forward secrecy
        if (sslHostConfig.getDisableSessionTickets()) {
            SSLContext.setOptions(ctx, SSL.SSL_OP_NO_TICKET);
        } else {
            SSLContext.clearOptions(ctx, SSL.SSL_OP_NO_TICKET);
        }
        // Set session cache size, if specified
        if (sslHostConfig.getSessionCacheSize() > 0) {
            SSLContext.setSessionCacheSize(ctx, sslHostConfig.getSessionCacheSize());
        } else {
            // Get the default session cache size using SSLContext.setSessionCacheSize()
            long sessionCacheSize = SSLContext.setSessionCacheSize(ctx, 20480);
            // Revert the session cache size to the default value.
            SSLContext.setSessionCacheSize(ctx, sessionCacheSize);
        }
        // Set session timeout, if specified
        if (sslHostConfig.getSessionTimeout() > 0) {
            SSLContext.setSessionCacheTimeout(ctx, sslHostConfig.getSessionTimeout());
        } else {
            // Get the default session timeout using SSLContext.setSessionCacheTimeout()
            long sessionTimeout = SSLContext.setSessionCacheTimeout(ctx, 300);
            // Revert the session timeout to the default value.
            SSLContext.setSessionCacheTimeout(ctx, sessionTimeout);
        }
        // List the ciphers that the client is permitted to negotiate
        String opensslCipherConfig = sslHostConfig.getCiphers();
        this.jsseCipherNames = OpenSSLCipherConfigurationParser.parseExpression(opensslCipherConfig);
        SSLContext.setCipherSuite(ctx, opensslCipherConfig);
        // Load Server key and certificate
        if (certificate.getCertificateFile() != null) {
            // Set certificate
            SSLContext.setCertificate(ctx, SSLHostConfig.adjustRelativePath(certificate.getCertificateFile()), SSLHostConfig.adjustRelativePath(certificate.getCertificateKeyFile()), certificate.getCertificateKeyPassword(), SSL.SSL_AIDX_RSA);
            // Set certificate chain file
            SSLContext.setCertificateChainFile(ctx, SSLHostConfig.adjustRelativePath(certificate.getCertificateChainFile()), false);
            // Support Client Certificates
            SSLContext.setCACertificate(ctx, SSLHostConfig.adjustRelativePath(sslHostConfig.getCaCertificateFile()), SSLHostConfig.adjustRelativePath(sslHostConfig.getCaCertificatePath()));
            // Set revocation
            SSLContext.setCARevocation(ctx, SSLHostConfig.adjustRelativePath(sslHostConfig.getCertificateRevocationListFile()), SSLHostConfig.adjustRelativePath(sslHostConfig.getCertificateRevocationListPath()));
        } else {
            X509KeyManager keyManager = chooseKeyManager(kms);
            String alias = certificate.getCertificateKeyAlias();
            if (alias == null) {
                alias = "tomcat";
            }
            X509Certificate[] chain = keyManager.getCertificateChain(alias);
            if (chain == null) {
                alias = findAlias(keyManager, certificate);
                chain = keyManager.getCertificateChain(alias);
            }
            PrivateKey key = keyManager.getPrivateKey(alias);
            StringBuilder sb = new StringBuilder(BEGIN_KEY);
            sb.append(Base64.getMimeEncoder(64, new byte[] { '\n' }).encodeToString(key.getEncoded()));
            sb.append(END_KEY);
            SSLContext.setCertificateRaw(ctx, chain[0].getEncoded(), sb.toString().getBytes(StandardCharsets.US_ASCII), SSL.SSL_AIDX_RSA);
            for (int i = 1; i < chain.length; i++) {
                SSLContext.addChainCertificateRaw(ctx, chain[i].getEncoded());
            }
        }
        // Client certificate verification
        int value = 0;
        switch(sslHostConfig.getCertificateVerification()) {
            case NONE:
                value = SSL.SSL_CVERIFY_NONE;
                break;
            case OPTIONAL:
                value = SSL.SSL_CVERIFY_OPTIONAL;
                break;
            case OPTIONAL_NO_CA:
                value = SSL.SSL_CVERIFY_OPTIONAL_NO_CA;
                break;
            case REQUIRED:
                value = SSL.SSL_CVERIFY_REQUIRE;
                break;
        }
        SSLContext.setVerify(ctx, value, sslHostConfig.getCertificateVerificationDepth());
        if (tms != null) {
            final X509TrustManager manager = chooseTrustManager(tms);
            SSLContext.setCertVerifyCallback(ctx, new CertificateVerifier() {

                @Override
                public boolean verify(long ssl, byte[][] chain, String auth) {
                    X509Certificate[] peerCerts = certificates(chain);
                    try {
                        manager.checkClientTrusted(peerCerts, auth);
                        return true;
                    } catch (Exception e) {
                        log.debug(sm.getString("openssl.certificateVerificationFailed"), e);
                    }
                    return false;
                }
            });
        }
        if (negotiableProtocols != null && negotiableProtocols.size() > 0) {
            ArrayList<String> protocols = new ArrayList<>();
            protocols.addAll(negotiableProtocols);
            protocols.add("http/1.1");
            String[] protocolsArray = protocols.toArray(new String[0]);
            SSLContext.setAlpnProtos(ctx, protocolsArray, SSL.SSL_SELECTOR_FAILURE_NO_ADVERTISE);
            SSLContext.setNpnProtos(ctx, protocolsArray, SSL.SSL_SELECTOR_FAILURE_NO_ADVERTISE);
        }
        sessionContext = new OpenSSLSessionContext(ctx);
        sslHostConfig.setOpenSslContext(Long.valueOf(ctx));
        initialized = true;
    } catch (Exception e) {
        log.warn(sm.getString("openssl.errorSSLCtxInit"), e);
        destroy();
    }
}
Also used : PrivateKey(java.security.PrivateKey) ArrayList(java.util.ArrayList) X509Certificate(java.security.cert.X509Certificate) AbstractEndpoint(org.apache.tomcat.util.net.AbstractEndpoint) CertificateException(java.security.cert.CertificateException) SSLException(javax.net.ssl.SSLException) X509TrustManager(javax.net.ssl.X509TrustManager) CertificateVerifier(org.apache.tomcat.jni.CertificateVerifier) X509KeyManager(javax.net.ssl.X509KeyManager)

Aggregations

PrivateKey (java.security.PrivateKey)517 X509Certificate (java.security.cert.X509Certificate)217 KeyFactory (java.security.KeyFactory)169 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)144 Certificate (java.security.cert.Certificate)127 PublicKey (java.security.PublicKey)120 ByteArrayInputStream (java.io.ByteArrayInputStream)118 KeyStore (java.security.KeyStore)93 CertificateFactory (java.security.cert.CertificateFactory)92 IOException (java.io.IOException)81 Key (java.security.Key)74 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)73 PrivateKeyEntry (java.security.KeyStore.PrivateKeyEntry)70 Entry (java.security.KeyStore.Entry)60 TrustedCertificateEntry (java.security.KeyStore.TrustedCertificateEntry)60 KeyPair (java.security.KeyPair)59 SecretKey (javax.crypto.SecretKey)48 InvalidKeyException (java.security.InvalidKeyException)47 KeyStoreException (java.security.KeyStoreException)46 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)46