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);
}
}
}
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;
}
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
}
} };
}
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;
}
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();
}
Aggregations