Search in sources :

Example 1 with Key

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

the class CryptoDataFormat method marshal.

public void marshal(Exchange exchange, Object graph, OutputStream outputStream) throws Exception {
    byte[] iv = getInitializationVector(exchange);
    Key key = getKey(exchange);
    InputStream plaintextStream = ExchangeHelper.convertToMandatoryType(exchange, InputStream.class, graph);
    HMACAccumulator hmac = getMessageAuthenticationCode(key);
    if (plaintextStream != null) {
        inlineInitVector(outputStream, iv);
        byte[] buffer = new byte[bufferSize];
        int read;
        CipherOutputStream cipherStream = null;
        try {
            cipherStream = new CipherOutputStream(outputStream, initializeCipher(ENCRYPT_MODE, key, iv));
            while ((read = plaintextStream.read(buffer)) > 0) {
                cipherStream.write(buffer, 0, read);
                cipherStream.flush();
                hmac.encryptUpdate(buffer, read);
            }
            // only write if there is data to write (IBM JDK throws exception if no data)
            byte[] mac = hmac.getCalculatedMac();
            if (mac != null && mac.length > 0) {
                cipherStream.write(mac);
            }
        } finally {
            IOHelper.close(cipherStream, "cipher", LOG);
            IOHelper.close(plaintextStream, "plaintext", LOG);
        }
    }
}
Also used : CipherOutputStream(javax.crypto.CipherOutputStream) DataInputStream(java.io.DataInputStream) CipherInputStream(javax.crypto.CipherInputStream) InputStream(java.io.InputStream) Key(java.security.Key)

Example 2 with Key

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

the class CryptoDataFormat method unmarshal.

public Object unmarshal(final Exchange exchange, final InputStream encryptedStream) throws Exception {
    if (encryptedStream != null) {
        byte[] iv = getInlinedInitializationVector(exchange, encryptedStream);
        Key key = getKey(exchange);
        CipherInputStream cipherStream = null;
        OutputStreamBuilder osb = null;
        try {
            cipherStream = new CipherInputStream(encryptedStream, initializeCipher(DECRYPT_MODE, key, iv));
            osb = OutputStreamBuilder.withExchange(exchange);
            HMACAccumulator hmac = getMessageAuthenticationCode(key);
            byte[] buffer = new byte[bufferSize];
            hmac.attachStream(osb);
            int read;
            while ((read = cipherStream.read(buffer)) >= 0) {
                hmac.decryptUpdate(buffer, read);
            }
            hmac.validate();
            return osb.build();
        } finally {
            IOHelper.close(cipherStream, "cipher", LOG);
            IOHelper.close(osb, "plaintext", LOG);
        }
    }
    return null;
}
Also used : CipherInputStream(javax.crypto.CipherInputStream) OutputStreamBuilder(org.apache.camel.converter.stream.OutputStreamBuilder) Key(java.security.Key)

Example 3 with Key

use of java.security.Key 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 Key

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

the class CryptoDataFormat method createDataFormat.

@Override
protected DataFormat createDataFormat(RouteContext routeContext) {
    DataFormat cryptoFormat = super.createDataFormat(routeContext);
    if (ObjectHelper.isNotEmpty(keyRef)) {
        Key key = CamelContextHelper.mandatoryLookup(routeContext.getCamelContext(), keyRef, Key.class);
        setProperty(routeContext.getCamelContext(), cryptoFormat, "key", key);
    }
    if (ObjectHelper.isNotEmpty(algorithmParameterRef)) {
        AlgorithmParameterSpec spec = CamelContextHelper.mandatoryLookup(routeContext.getCamelContext(), algorithmParameterRef, AlgorithmParameterSpec.class);
        setProperty(routeContext.getCamelContext(), cryptoFormat, "AlgorithmParameterSpec", spec);
    }
    if (ObjectHelper.isNotEmpty(initVectorRef)) {
        byte[] iv = CamelContextHelper.mandatoryLookup(routeContext.getCamelContext(), initVectorRef, byte[].class);
        setProperty(routeContext.getCamelContext(), cryptoFormat, "InitializationVector", iv);
    }
    return cryptoFormat;
}
Also used : DataFormat(org.apache.camel.spi.DataFormat) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec) Key(java.security.Key)

Example 5 with Key

use of java.security.Key in project hadoop by apache.

the class TestCredentials method testReadWriteStorage.

@SuppressWarnings("unchecked")
@Test
public <T extends TokenIdentifier> void testReadWriteStorage() throws IOException, NoSuchAlgorithmException {
    // create tokenStorage Object
    Credentials ts = new Credentials();
    Token<T> token1 = new Token();
    Token<T> token2 = new Token();
    Text service1 = new Text("service1");
    Text service2 = new Text("service2");
    Collection<Text> services = new ArrayList<Text>();
    services.add(service1);
    services.add(service2);
    token1.setService(service1);
    token2.setService(service2);
    ts.addToken(new Text("sometoken1"), token1);
    ts.addToken(new Text("sometoken2"), token2);
    // create keys and put it in
    final KeyGenerator kg = KeyGenerator.getInstance(DEFAULT_HMAC_ALGORITHM);
    String alias = "alias";
    Map<Text, byte[]> m = new HashMap<Text, byte[]>(10);
    for (int i = 0; i < 10; i++) {
        Key key = kg.generateKey();
        m.put(new Text(alias + i), key.getEncoded());
        ts.addSecretKey(new Text(alias + i), key.getEncoded());
    }
    // create file to store
    File tmpFileName = new File(tmpDir, "tokenStorageTest");
    DataOutputStream dos = new DataOutputStream(new FileOutputStream(tmpFileName));
    ts.write(dos);
    dos.close();
    // open and read it back
    DataInputStream dis = new DataInputStream(new FileInputStream(tmpFileName));
    ts = new Credentials();
    ts.readFields(dis);
    dis.close();
    // get the tokens and compare the services
    Collection<Token<? extends TokenIdentifier>> list = ts.getAllTokens();
    assertEquals("getAllTokens should return collection of size 2", list.size(), 2);
    boolean foundFirst = false;
    boolean foundSecond = false;
    for (Token<? extends TokenIdentifier> token : list) {
        if (token.getService().equals(service1)) {
            foundFirst = true;
        }
        if (token.getService().equals(service2)) {
            foundSecond = true;
        }
    }
    assertTrue("Tokens for services service1 and service2 must be present", foundFirst && foundSecond);
    // compare secret keys
    int mapLen = m.size();
    assertEquals("wrong number of keys in the Storage", mapLen, ts.numberOfSecretKeys());
    for (Text a : m.keySet()) {
        byte[] kTS = ts.getSecretKey(a);
        byte[] kLocal = m.get(a);
        assertTrue("keys don't match for " + a, WritableComparator.compareBytes(kTS, 0, kTS.length, kLocal, 0, kLocal.length) == 0);
    }
    tmpFileName.delete();
}
Also used : TokenIdentifier(org.apache.hadoop.security.token.TokenIdentifier) HashMap(java.util.HashMap) DataOutputStream(java.io.DataOutputStream) ArrayList(java.util.ArrayList) Token(org.apache.hadoop.security.token.Token) Text(org.apache.hadoop.io.Text) DataInputStream(java.io.DataInputStream) FileInputStream(java.io.FileInputStream) FileOutputStream(java.io.FileOutputStream) KeyGenerator(javax.crypto.KeyGenerator) File(java.io.File) Credentials(org.apache.hadoop.security.Credentials) Key(java.security.Key) Test(org.junit.Test)

Aggregations

Key (java.security.Key)268 PrivateKey (java.security.PrivateKey)108 SecretKey (javax.crypto.SecretKey)77 KeyStore (java.security.KeyStore)62 PublicKey (java.security.PublicKey)58 X509Certificate (java.security.cert.X509Certificate)56 Cipher (javax.crypto.Cipher)54 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)46 IOException (java.io.IOException)39 ByteArrayInputStream (java.io.ByteArrayInputStream)38 Certificate (java.security.cert.Certificate)36 KeyFactory (java.security.KeyFactory)35 InvalidKeyException (java.security.InvalidKeyException)31 KeyGenerator (javax.crypto.KeyGenerator)31 SecretKeySpec (javax.crypto.spec.SecretKeySpec)27 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)26 Test (org.junit.Test)26 KeyStoreException (java.security.KeyStoreException)21 SecureRandom (java.security.SecureRandom)21 IvParameterSpec (javax.crypto.spec.IvParameterSpec)18