Example usage for com.amazonaws.services.kms.model DecryptResult getPlaintext

List of usage examples for com.amazonaws.services.kms.model DecryptResult getPlaintext

Introduction

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

Prototype


public java.nio.ByteBuffer getPlaintext() 

Source Link

Document

Decrypted plaintext data.

Usage

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

License:Open Source License

public static ByteBuffer computeSecretBytes(AWSCredentials creds, String masterKeyId, String algorithm,
        String encValueSecretKey, String endpoint) throws Base64DecodingException {
    Precondition.assertNonNullArgument("null credentials", creds);
    Precondition.assertNonEmptyString("null or blank master key id", masterKeyId);
    Precondition.assertNonEmptyString("null or blank encrypted value", encValueSecretKey);
    if (!StringUtils.nonEmptyString(algorithm)) {
        algorithm = DefaultAlgorithms.DEFAULT_AWS_KEY_ENCRYPTION_ALGORITHM;
    }// w w  w.  j  a  v  a 2  s . c  o m

    AWSKMSClient kms = new AWSKMSClient(creds);
    if (endpoint != null) {
        kms.setEndpoint(endpoint);
    }

    byte[] encBase64 = encValueSecretKey.getBytes();
    byte[] encBytes = Base64.decode(encBase64);
    ByteBuffer encryptedKey = ByteBuffer.wrap(encBytes);
    DecryptRequest request = new DecryptRequest().withCiphertextBlob(encryptedKey);
    DecryptResult result = kms.decrypt(request);
    ByteBuffer retVal = result.getPlaintext();

    return retVal;
}

From source file:com.google.crypto.tink.integration.awskms.AwsKmsAead.java

License:Apache License

@Override
public byte[] decrypt(final byte[] ciphertext, final byte[] associatedData) throws GeneralSecurityException {
    try {//from  w  ww  . j a v a 2  s  . c o  m
        DecryptRequest req = new DecryptRequest().withCiphertextBlob(ByteBuffer.wrap(ciphertext));
        if (associatedData != null && associatedData.length != 0) {
            req = req.addEncryptionContextEntry("associatedData", BinaryUtils.toHex(associatedData));
        }
        DecryptResult result = kmsClient.decrypt(req);
        if (!result.getKeyId().equals(keyArn)) {
            throw new GeneralSecurityException("decryption failed: wrong key id");
        }
        return result.getPlaintext().array();
    } catch (AmazonServiceException e) {
        throw new GeneralSecurityException("decryption failed", e);
    }
}

From source file:com.nextdoor.bender.utils.Passwords.java

License:Apache License

public static String decrypt(String str, Region region) throws UnsupportedEncodingException {
    if (isJUnitTest()) {
        return str;
    }/*from w  w w .  jav  a2s  .  c o m*/

    AWSKMS kms = AWSKMSClientBuilder.standard().withRegion(region.getName()).build();

    /*
     * The KMS ciphertext is base64 encoded and must be decoded before the request is made
     */
    String cipherString = str;
    byte[] cipherBytes = Base64.decode(cipherString);

    /*
     * Create decode request and decode
     */
    ByteBuffer cipherBuffer = ByteBuffer.wrap(cipherBytes);
    DecryptRequest req = new DecryptRequest().withCiphertextBlob(cipherBuffer);
    DecryptResult resp = kms.decrypt(req);

    /*
     * Convert the response plaintext bytes to a string
     */
    return new String(resp.getPlaintext().array(), Charset.forName("UTF-8"));
}

From source file:org.finra.dm.dao.impl.KmsDaoImpl.java

License:Apache License

/**
 * {@inheritDoc}//from w  w w. j a v a2s  .c  o  m
 */
@Override
public String decrypt(AwsParamsDto awsParamsDto, String base64ciphertextBlob) {
    // Construct a new AWS KMS service client using the specified client configuration.
    // A credentials provider chain will be used that searches for credentials in this order:
    // - Environment Variables - AWS_ACCESS_KEY_ID and AWS_SECRET_KEY
    // - Java System Properties - aws.accessKeyId and aws.secretKey
    // - Instance Profile Credentials - delivered through the Amazon EC2 metadata service
    AWSKMSClient awsKmsClient = new AWSKMSClient(awsHelper.getClientConfiguration(awsParamsDto));

    // Decode the base64 encoded ciphertext.
    ByteBuffer ciphertextBlob = ByteBuffer.wrap(Base64.decodeBase64(base64ciphertextBlob));

    // Create the decrypt request.
    DecryptRequest decryptRequest = new DecryptRequest().withCiphertextBlob(ciphertextBlob);

    // Call AWS KMS decrypt service method.
    DecryptResult decryptResult = kmsOperations.decrypt(awsKmsClient, decryptRequest);

    // Get decrypted plaintext data.
    ByteBuffer plainText = decryptResult.getPlaintext();

    // Return the plain text as a string.
    return new String(plainText.array(), StandardCharsets.UTF_8);
}

From source file:org.finra.herd.dao.impl.KmsDaoImpl.java

License:Apache License

@Override
public String decrypt(AwsParamsDto awsParamsDto, String base64ciphertextBlob) {
    // Construct a new AWS KMS service client using the specified client configuration.
    // A credentials provider chain will be used that searches for credentials in this order:
    // - Environment Variables - AWS_ACCESS_KEY_ID and AWS_SECRET_KEY
    // - Java System Properties - aws.accessKeyId and aws.secretKey
    // - Instance Profile Credentials - delivered through the Amazon EC2 metadata service
    AWSKMSClient awsKmsClient = new AWSKMSClient(awsHelper.getClientConfiguration(awsParamsDto));

    // Decode the base64 encoded ciphertext.
    ByteBuffer ciphertextBlob = ByteBuffer.wrap(Base64.decodeBase64(base64ciphertextBlob));

    // Create the decrypt request.
    DecryptRequest decryptRequest = new DecryptRequest().withCiphertextBlob(ciphertextBlob);

    // Call AWS KMS decrypt service method.
    DecryptResult decryptResult = kmsOperations.decrypt(awsKmsClient, decryptRequest);

    // Get decrypted plaintext data.
    ByteBuffer plainText = decryptResult.getPlaintext();

    // Return the plain text as a string.
    return new String(plainText.array(), StandardCharsets.UTF_8);
}

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

License:Apache License

private Settings getSettings(String accountId) {
    return accounts.computeIfAbsent(accountId, (id) -> {
        Settings settings = new Settings();
        ItemCollection<QueryOutcome> items = dynamodb.getTable("SalientProfile")
                .query(new QuerySpec().withHashKey("accountId", id));
        items.pages().forEach((page) -> {
            page.iterator().forEachRemaining((item) -> {
                try {
                    Profile profile = new Profile();
                    if (item.hasAttribute("aliases")) {
                        profile.setAliases(json.readValue(item.getJSON("aliases"), Map.class));
                    }//w  w w. j a  v a  2  s. c  o m
                    if (item.hasAttribute("properties")) {
                        if (item.get("properties") instanceof byte[]) {
                            log.info("Decrypt profile " + item.getString("profileName"));
                            DecryptResult decrypt = kms.decrypt(
                                    new DecryptRequest().addEncryptionContextEntry("accountId", accountId)
                                            .withCiphertextBlob(ByteBuffer.wrap(item.getBinary("properties"))));
                            profile.setProperties(
                                    json.readValue(decrypt.getPlaintext().array(), Properties.class));
                        } else {
                            Properties properties = new Properties();
                            properties.putAll(item.getMap("properties"));
                            profile.setProperties(properties);
                        }
                    }
                    if (item.hasAttribute("repositories")) {
                        profile.setRepositories(json.readValue(item.getJSON("repositories"),
                                json.getTypeFactory().constructCollectionType(Set.class, Repository.class)));
                    }
                    String name = item.getString("profileName");
                    Boolean active = item.getBoolean("active");
                    settings.withProfile(name, profile);
                    if (active) {
                        settings.withActiveProfile(name);
                    }
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            });
        });
        return settings;
    });
}

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  .  j  ava  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;
}