Example usage for com.amazonaws.services.kms.model GenerateDataKeyResult getCiphertextBlob

List of usage examples for com.amazonaws.services.kms.model GenerateDataKeyResult getCiphertextBlob

Introduction

In this page you can find the example usage for com.amazonaws.services.kms.model GenerateDataKeyResult getCiphertextBlob.

Prototype


public java.nio.ByteBuffer getCiphertextBlob() 

Source Link

Document

The encrypted copy of the data key.

Usage

From source file:com.choicemaker.xmlencryption.AwsKmsSecretKeyInfoFactory.java

License:Open Source License

public static SecretKeyInfo createSessionKey(AWSCredentials creds, String masterKeyId, String algorithm,
        String endpoint) {//  w ww . ja  v  a  2s  . c  o  m
    GenerateDataKeyResult dataKeyResult = AwsKmsUtils.generateDataKey(creds, masterKeyId, algorithm, endpoint);

    ByteBuffer plaintextKey = dataKeyResult.getPlaintext();
    final byte[] key = new byte[plaintextKey.remaining()];
    plaintextKey.get(key);

    ByteBuffer encryptedKey = dataKeyResult.getCiphertextBlob();
    final byte[] encKey = new byte[encryptedKey.remaining()];
    encryptedKey.get(encKey);

    Document doc = DOMUtils.newDocument();
    final Element keyInfoElement = doc.createElementNS(WSS4JConstants.SIG_NS,
            WSS4JConstants.SIG_PREFIX + ":" + WSS4JConstants.KEYINFO_LN);
    keyInfoElement.setAttributeNS(WSS4JConstants.XMLNS_NS, "xmlns:" + WSS4JConstants.SIG_PREFIX,
            WSS4JConstants.SIG_NS);
    Element keyNameElement = doc.createElementNS(WSS4JConstants.SIG_NS, WSS4JConstants.SIG_PREFIX + ":KeyName");
    keyNameElement.setTextContent(masterKeyId);
    keyInfoElement.appendChild(keyNameElement);

    SecretKeyInfo retVal = new SecretKeyInfo(key, encKey, keyInfoElement);
    logger.fine(retVal.toString());

    return retVal;
}

From source file:com.choicemaker.xmlencryption.AwsKmsUtils.java

License:Open Source License

public static ByteBuffer createSessionKey(AWSCredentials creds, String masterKeyId, String algorithm,
        String endpoint) {/*from w  w  w  . j a v  a 2s  .c om*/

    GenerateDataKeyResult dataKeyResult = AwsKmsUtils.generateDataKey(creds, masterKeyId, algorithm, endpoint);

    ByteBuffer plaintextKey = dataKeyResult.getPlaintext();
    final byte[] key = new byte[plaintextKey.remaining()];
    plaintextKey.get(key);

    ByteBuffer retVal = dataKeyResult.getCiphertextBlob();
    final byte[] encKey = new byte[retVal.remaining()];
    retVal.get(encKey);

    return retVal;
}

From source file:org.apache.coheigea.cxf.kms.common.CommonCallbackHandler.java

License:Apache License

public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
    for (int i = 0; i < callbacks.length; i++) {
        if (callbacks[i] instanceof WSPasswordCallback) {
            WSPasswordCallback pc = (WSPasswordCallback) callbacks[i];
            if (pc.getUsage() == WSPasswordCallback.SECRET_KEY) {
                final AWSCredentials creds = new BasicAWSCredentials(accessKey, secretKey);

                AWSKMSClient kms = new AWSKMSClient(creds);
                kms.setEndpoint(endpoint);

                if (pc.getEncryptedSecret() != null) {
                    ByteBuffer encryptedKey = ByteBuffer.wrap(pc.getEncryptedSecret());

                    DecryptRequest req = new DecryptRequest().withCiphertextBlob(encryptedKey);
                    ByteBuffer plaintextKey = kms.decrypt(req).getPlaintext();

                    byte[] key = new byte[plaintextKey.remaining()];
                    plaintextKey.get(key);
                    pc.setKey(key);/*from  w ww.  ja v a  2  s.  co  m*/
                } else {

                    GenerateDataKeyRequest dataKeyRequest = new GenerateDataKeyRequest();
                    dataKeyRequest.setKeyId(masterKeyId);
                    String algorithm = "AES_128";
                    if (pc.getAlgorithm() != null && pc.getAlgorithm().contains("aes256")) {
                        algorithm = "AES_256";
                    }
                    dataKeyRequest.setKeySpec(algorithm);

                    GenerateDataKeyResult dataKeyResult = kms.generateDataKey(dataKeyRequest);

                    ByteBuffer plaintextKey = dataKeyResult.getPlaintext();
                    byte[] key = new byte[plaintextKey.remaining()];
                    plaintextKey.get(key);
                    pc.setKey(key);

                    ByteBuffer encryptedKey = dataKeyResult.getCiphertextBlob();
                    byte[] encKey = new byte[encryptedKey.remaining()];
                    encryptedKey.get(encKey);
                    pc.setEncryptedSecret(encKey);

                    // Create a KeyName pointing to the encryption key
                    Document doc = DOMUtils.newDocument();
                    Element keyInfoElement = doc.createElementNS(WSConstants.SIG_NS,
                            WSConstants.SIG_PREFIX + ":" + WSConstants.KEYINFO_LN);
                    keyInfoElement.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:" + WSConstants.SIG_PREFIX,
                            WSConstants.SIG_NS);
                    Element keyNameElement = doc.createElementNS(WSConstants.SIG_NS,
                            WSConstants.SIG_PREFIX + ":KeyName");
                    keyNameElement.setTextContent("1c84a3f2-51cc-4c66-9045-68f51ef8b1eb");
                    keyInfoElement.appendChild(keyNameElement);
                    pc.setKeyInfoReference(keyInfoElement);
                }
            }
        }
    }
}

From source file:ws.salient.aws.dynamodb.DynamoDBStore.java

License:Apache License

public Session get(Command command, KnowledgeRepository repository, Properties properties,
        Injector parentInjector, Sessions sessions, QuerySpec sessionQuery) {
    String sessionId = command.getSessionId();
    String accountId = command.getAccountId();

    SecretKeySpec secretKey;//from w w  w .ja  va 2 s  .co  m
    ByteBuffer encryptedKey;
    Session session = new Session(sessionId);
    Page<Item, QueryOutcome> page = dynamodb.getTable("SalientSession").query(sessionQuery).firstPage();
    if (page != null && page.size() > 0) {

        try {
            Item result = page.iterator().next();

            encryptedKey = ByteBuffer.wrap((byte[]) result.getMap("secretKey").get("encrypted"));
            if (encryptedKey != null) {
                DecryptResult decrypt = kms.decrypt(new DecryptRequest()
                        .addEncryptionContextEntry("accountId", accountId)
                        .addEncryptionContextEntry("sessionId", sessionId).withCiphertextBlob(encryptedKey));
                byte[] key = decrypt.getPlaintext().array();
                secretKey = new SecretKeySpec(key, (String) result.getMap("secretKey").get("algorithm"));
            } else {
                secretKey = null;
            }

            result = decrypt(result, secretKey, "properties", "session");

            properties = json.readValue(result.getBinary("properties"), Properties.class);
            String knowledgeBaseId = result.getString("knowledgeBaseId");
            KnowledgeBase knowledgeBase = repository.getKnowledgeBase(knowledgeBaseId);
            String timestamp = result.getString("timestamp");

            session.init(knowledgeBase, properties, parentInjector, Instant.parse(timestamp),
                    result.getBinary("session"), sessions);

            int processCount = session.getProcessCount();

            List<Item> eventItems = new LinkedList();
            ItemCollection<QueryOutcome> query = dynamodb.getTable("SalientSessionEvent")
                    .query(new QuerySpec().withConsistentRead(true).withHashKey("sessionId", sessionId)
                            .withRangeKeyCondition(new RangeKeyCondition("timestamp").gt(timestamp)));
            query.pages().forEach((eventPage) -> {
                eventPage.forEach((eventItem) -> {
                    eventItems.add(eventItem);
                });
            });

            List<Command> commands = new LinkedList();

            eventItems.forEach((eventItem) -> {
                try {
                    eventItem = decrypt(eventItem, secretKey, "command");
                    byte[] value = eventItem.getBinary("command");
                    ObjectInputStream objectIn = new ObjectInputStream(new ByteArrayInputStream(value)) {
                        protected Class<?> resolveClass(ObjectStreamClass desc)
                                throws IOException, ClassNotFoundException {
                            return session.getKnowledgeBase().getContainer().getClassLoader()
                                    .loadClass(desc.getName());
                        }
                    };
                    Command event = (Command) objectIn.readObject();
                    if (event instanceof WorkItem) {
                        session.getWorkItemHandlers().forEach((handler) -> {
                            handler.getCompletedWorkItemIds().add(((WorkItem) event).getWorkItemId());
                        });
                    }
                    commands.add(event);
                } catch (ClassNotFoundException | IOException ex) {
                    throw new RuntimeException(ex);
                }
            });
            commands.forEach((event) -> {
                session.accept(event);
            });
            session.getWorkItemHandlers().forEach((handler) -> {
                handler.getCompletedWorkItemIds().clear();
            });

        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    } else {
        GenerateDataKeyResult dataKey = generateEncryptionKey(accountId, sessionId);
        byte[] key = dataKey.getPlaintext().array();
        secretKey = new SecretKeySpec(key, "AES");
        encryptedKey = dataKey.getCiphertextBlob();
        KnowledgeBase knowledgeBase = repository.getKnowledgeBase(command.getKnowledgeBaseId());
        session.init(knowledgeBase, properties, parentInjector, command.getTimestamp(), sessions);
    }
    session.setEncryptedKey(encryptedKey);
    session.setSecretKey(secretKey);
    return session;
}