com.amazonaws.services.kms.AWSKMSClientBuilder Java Examples

The following examples show how to use com.amazonaws.services.kms.AWSKMSClientBuilder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RevokeGrant.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    final String USAGE =
        "To run this example, supply a key id or ARN and a grant id\n" +
        "Usage: RevokeGrant <key-id> <grant-id>\n" +
        "Example: RevokeGrant 1234abcd-12ab-34cd-56ef-1234567890ab grant1\n";

    if (args.length != 2) {
        System.out.println(USAGE);
        System.exit(1);
    }

    String keyId = args[0];
    String grantId = args[1];

    AWSKMS kmsClient = AWSKMSClientBuilder.standard().build();

    // Revoke a grant on a CMK

    RevokeGrantRequest request = new RevokeGrantRequest().withKeyId(keyId).withGrantId(grantId);
    kmsClient.revokeGrant(request);
}
 
Example #2
Source File: DeleteAlias.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    final String USAGE =
        "To run this example, supply an alias name\n" +
        "Usage: DeleteAlias <alias-name>\n" +
        "Example: DeleteAlias alias/projectKey1\n";

    if (args.length != 1) {
        System.out.println(USAGE);
        System.exit(1);
    }

    String aliasName = args[0];

    AWSKMS kmsClient = AWSKMSClientBuilder.standard().build();

    // Delete an alias for a CMK

    DeleteAliasRequest req = new DeleteAliasRequest().withAliasName(aliasName);
    kmsClient.deleteAlias(req);
}
 
Example #3
Source File: ListAliases.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    AWSKMS kmsClient = AWSKMSClientBuilder.standard().build();

    // List the aliases in this AWS account
    //
    Integer limit = 10;

    String nextMarker = null;
    do {
        ListAliasesRequest req = new ListAliasesRequest()
            .withMarker(nextMarker).withLimit(limit);
        ListAliasesResult result = kmsClient.listAliases(req);
        for (AliasListEntry alias : result.getAliases()) {
            System.out.printf("Found an alias named \"%s\".%n", alias.getAliasName());
        }
        nextMarker = result.getNextMarker();
    } while (nextMarker != null);

}
 
Example #4
Source File: UpdateAlias.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    final String USAGE =
        "To run this example, supply a key id or ARN and an alias name\n" +
        "Usage: UpdateAlias <target-key-id> <alias-name>\n" +
        "Example: UpdateAlias 1234abcd-12ab-34cd-56ef-1234567890ab " +
        "alias/projectKey1\n";

    if (args.length != 2) {
        System.out.println(USAGE);
        System.exit(1);
    }

    String targetKeyId = args[0];
    String aliasName = args[1];

    AWSKMS kmsClient = AWSKMSClientBuilder.standard().build();

    // Updating an alias

    UpdateAliasRequest req = new UpdateAliasRequest()
            .withAliasName(aliasName)
            .withTargetKeyId(targetKeyId);

    kmsClient.updateAlias(req);
}
 
Example #5
Source File: EnableCustomerMasterKey.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    final String USAGE =
        "To run this example, supply a key id or ARN\n" +
        "Usage: EnableCustomerMasterKey <key-id>\n" +
        "Example: EnableCustomerMasterKey 1234abcd-12ab-34cd-56ef-1234567890ab\n";

    if (args.length != 1) {
        System.out.println(USAGE);
        System.exit(1);
    }

    String keyId = args[0];

    AWSKMS kmsClient = AWSKMSClientBuilder.standard().build();

    // Enable a CMK

    EnableKeyRequest req = new EnableKeyRequest().withKeyId(keyId);
    kmsClient.enableKey(req);

}
 
Example #6
Source File: GetKeyPolicy.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    final String USAGE =
        "To run this example, supply a key id or ARN\n" +
        "Usage: GetKeyPolicy <key-id>\n" +
        "Example: GetKeyPolicy 1234abcd-12ab-34cd-56ef-1234567890ab\n";

    if (args.length != 1) {
        System.out.println(USAGE);
        System.exit(1);
    }

    String keyId = args[0];

    AWSKMS kmsClient = AWSKMSClientBuilder.standard().build();

    // Get the policy for a CMK
    String policyName = "default";

    GetKeyPolicyRequest req = new GetKeyPolicyRequest().withKeyId(keyId).withPolicyName(policyName);
    GetKeyPolicyResult result = kmsClient.getKeyPolicy(req);

    System.out.printf("Found key policy for %s:%n%s%n", keyId, result.getPolicy());

}
 
Example #7
Source File: DisableCustomerMasterKey.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    final String USAGE =
        "To run this example, supply a key id or ARN\n" +
        "Usage: DisableCustomerMasterKey <key-id>\n" +
        "Example: DisableCustomerMasterKey 1234abcd-12ab-34cd-56ef-1234567890ab\n";

    if (args.length != 1) {
        System.out.println(USAGE);
        System.exit(1);
    }

    String keyId = args[0];

    AWSKMS kmsClient = AWSKMSClientBuilder.standard().build();

    // Disable a CMK

    DisableKeyRequest req = new DisableKeyRequest().withKeyId(keyId);
    kmsClient.disableKey(req);

}
 
Example #8
Source File: KmsMasterKeyProvider.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
private AWSKMSClientBuilder cloneClientBuilder(final AWSKMSClientBuilder builder) {
    // We need to copy all arguments out of the builder in case it's mutated later on.
    // Unfortunately AWSKMSClientBuilder doesn't support .clone() so we'll have to do it by hand.

    if (builder.getEndpoint() != null) {
        // We won't be able to set the region later if a custom endpoint is set.
        throw new IllegalArgumentException("Setting endpoint configuration is not compatible with passing a " +
                                           "builder to the KmsMasterKeyProvider. Use withCustomClientFactory" +
                                           " instead.");
    }

    final AWSKMSClientBuilder newBuilder = AWSKMSClient.builder();
    newBuilder.setClientConfiguration(builder.getClientConfiguration());
    newBuilder.setCredentials(builder.getCredentials());
    newBuilder.setEndpointConfiguration(builder.getEndpoint());
    newBuilder.setMetricsCollector(builder.getMetricsCollector());
    if (builder.getRequestHandlers() != null) {
        newBuilder.setRequestHandlers(builder.getRequestHandlers().toArray(new RequestHandler2[0]));
    }
    return newBuilder;
}
 
Example #9
Source File: CreateAlias.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    final String USAGE =
        "To run this example, supply a key id or ARN and an alias name\n" +
        "Usage: CreateAlias <key-id> <alias-name>\n" +
        "Example: CreateAlias 1234abcd-12ab-34cd-56ef-1234567890ab " +
        "alias/projectKey1\n";

    if (args.length != 2) {
        System.out.println(USAGE);
        System.exit(1);
    }

    String targetKeyId = args[0];
    String aliasName = args[1];

    AWSKMS kmsClient = AWSKMSClientBuilder.standard().build();

    // Create an alias for a CMK

    CreateAliasRequest req = new CreateAliasRequest().withAliasName(aliasName).withTargetKeyId(targetKeyId);
    kmsClient.createAlias(req);
}
 
Example #10
Source File: KMSProviderBuilderIntegrationTests.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
public void whenHandlerConfigured_handlerIsInvoked() throws Exception {
    RequestHandler2 handler = spy(new RequestHandler2() {});
    KmsMasterKeyProvider mkp =
            KmsMasterKeyProvider.builder()
                                .withClientBuilder(
                                        AWSKMSClientBuilder.standard()
                                                           .withRequestHandlers(handler)
                                )
                                .withKeysForEncryption(KMSTestFixtures.TEST_KEY_IDS[0])
                                .build();

    new AwsCrypto().encryptData(mkp, new byte[1]);

    verify(handler).beforeRequest(any());
}
 
Example #11
Source File: Passwords.java    From bender with Apache License 2.0 6 votes vote down vote up
public static String decrypt(String str, Region region) throws UnsupportedEncodingException {
  if (isJUnitTest()) {
    return str;
  }

  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"));
}
 
Example #12
Source File: IntegrationTestHelper.java    From strongbox with Apache License 2.0 6 votes vote down vote up
private static void cleanUpKMSKeys(Regions testRegion, String testResourcePrefix, Date createdBeforeThreshold,
                                   AWSCredentialsProvider awsCredentials) {
    LOG.info("Cleaning KMS...");

    AWSKMS kmsClient = AWSKMSClientBuilder.standard()
            .withCredentials(awsCredentials)
            .withRegion(testRegion)
            .build();

    List<AliasListEntry> keys = kmsClient.listAliases().getAliases();
    for (AliasListEntry entry: keys) {
        if (!entry.getAliasName().startsWith("alias/" + testResourcePrefix)) {
            continue;
        }

        DescribeKeyRequest request = new DescribeKeyRequest().withKeyId(entry.getTargetKeyId());
        KeyMetadata metadata = kmsClient.describeKey(request).getKeyMetadata();

        if (KMSKeyState.fromString(metadata.getKeyState()) != KMSKeyState.PENDING_DELETION &&
                metadata.getCreationDate().before(createdBeforeThreshold)) {
            LOG.info("Scheduling KMS key for deletion:" + entry.getAliasName());
            scheduleKeyDeletion(kmsClient, entry);
        }
    }
}
 
Example #13
Source File: EncryptionContextOverridesWithDynamoDBMapper.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws GeneralSecurityException {
    final String cmkArn = args[0];
    final String region = args[1];
    final String encryptionContextTableName = args[2];

    AmazonDynamoDB ddb = null;
    AWSKMS kms = null;
    try {
        ddb = AmazonDynamoDBClientBuilder.standard().withRegion(region).build();
        kms = AWSKMSClientBuilder.standard().withRegion(region).build();
        encryptRecord(cmkArn, encryptionContextTableName, ddb, kms);
    } finally {
        if (ddb != null) {
            ddb.shutdown();
        }
        if (kms != null) {
            kms.shutdown();
        }
    }
}
 
Example #14
Source File: MetadataHandler.java    From aws-athena-query-federation with Apache License 2.0 6 votes vote down vote up
/**
 * @param sourceType Used to aid in logging diagnostic info when raising a support case.
 */
public MetadataHandler(String sourceType)
{
    this.sourceType = sourceType;
    this.spillBucket = System.getenv(SPILL_BUCKET_ENV);
    this.spillPrefix = System.getenv(SPILL_PREFIX_ENV) == null ?
            DEFAULT_SPILL_PREFIX : System.getenv(SPILL_PREFIX_ENV);
    if (System.getenv(DISABLE_SPILL_ENCRYPTION) == null ||
            !DISABLE_ENCRYPTION.equalsIgnoreCase(System.getenv(DISABLE_SPILL_ENCRYPTION))) {
        encryptionKeyFactory = (System.getenv(KMS_KEY_ID_ENV) != null) ?
                new KmsKeyFactory(AWSKMSClientBuilder.standard().build(), System.getenv(KMS_KEY_ID_ENV)) :
                new LocalKeyFactory();
    }
    else {
        encryptionKeyFactory = null;
    }

    this.secretsManager = new CachableSecretsManager(AWSSecretsManagerClientBuilder.defaultClient());
    this.athena = AmazonAthenaClientBuilder.defaultClient();
    this.verifier = new SpillLocationVerifier(AmazonS3ClientBuilder.standard().build());
}
 
Example #15
Source File: KmsMasterKeyProvider.java    From aws-encryption-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Returns an instance of this object with the supplied configuration and credentials. all keys
 * listed in {@code keyIds} will be used to protect data.
 */
public KmsMasterKeyProvider(final AWSCredentialsProvider creds, final Region region,
        final ClientConfiguration clientConfiguration, final List<String> keyIds) {
    this(builder().withClientBuilder(AWSKMSClientBuilder.standard()
                                                        .withClientConfiguration(clientConfiguration)
                                                        .withCredentials(creds))
                  .clientFactory(),
         region.getName(),
         keyIds
    );
}
 
Example #16
Source File: KmsMasterKeyProvider.java    From aws-encryption-sdk-java with Apache License 2.0 5 votes vote down vote up
private RegionalClientSupplier clientFactory() {
    if (regionalClientSupplier_ != null) {
        return regionalClientSupplier_;
    }

    // Clone again; this MKP builder might be reused to build a second MKP with different creds.
    AWSKMSClientBuilder builder = templateBuilder_ != null ? cloneClientBuilder(templateBuilder_)
                                                           : AWSKMSClientBuilder.standard();

    ConcurrentHashMap<String, AWSKMS> clientCache = new ConcurrentHashMap<>();
    snoopClientCache(clientCache);

    return region -> {
        AWSKMS kms = clientCache.get(region);

        if (kms != null) return kms;

        // We can't just use computeIfAbsent as we need to avoid leaking KMS clients if we're asked to decrypt
        // an EDK with a bogus region in its ARN. So we'll install a request handler to identify the first
        // successful call, and cache it when we see that.
        SuccessfulRequestCacher cacher = new SuccessfulRequestCacher(clientCache, region);
        ArrayList<RequestHandler2> handlers = new ArrayList<>();
        if (builder.getRequestHandlers() != null) {
            handlers.addAll(builder.getRequestHandlers());
        }
        handlers.add(cacher);

        kms = cloneClientBuilder(builder)
                .withRegion(region)
                .withRequestHandlers(handlers.toArray(new RequestHandler2[handlers.size()]))
                .build();
        cacher.client_ = kms;

        return kms;
    };
}
 
Example #17
Source File: KmsEncryptionConfiguration.java    From spring-cloud-config-aws-kms with Apache License 2.0 5 votes vote down vote up
@Bean
public AWSKMS kms() {
    final AWSKMSClientBuilder builder = AWSKMSClient.builder();

    if (Optional.ofNullable(properties.getEndpoint()).isPresent()) {
        builder.withEndpointConfiguration(new EndpointConfiguration(properties.getEndpoint().getServiceEndpoint(), properties.getEndpoint().getSigningRegion()));
    } else {
        Optional.ofNullable(properties.getRegion()).ifPresent(builder::setRegion);
    }

    return builder.build();
}
 
Example #18
Source File: KMSProviderBuilderIntegrationTests.java    From aws-encryption-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test
public void whenShortTimeoutSet_timesOut() throws Exception {
    // By setting a timeout of 1ms, it's not physically possible to complete both the us-west-2 and eu-central-1
    // requests due to speed of light limits.
    KmsMasterKeyProvider mkp = KmsMasterKeyProvider.builder()
                                                   .withClientBuilder(
                                                           AWSKMSClientBuilder.standard()
                                                            .withClientConfiguration(
                                                                    new ClientConfiguration()
                                                                        .withRequestTimeout(1)
                                                            )
                                                   )
                                                   .withKeysForEncryption(Arrays.asList(KMSTestFixtures.TEST_KEY_IDS))
                                                   .build();

    try {
        new AwsCrypto().encryptData(mkp, new byte[1]);
        fail("Expected exception");
    } catch (Exception e) {
        if (e instanceof AbortedException) {
            // ok - one manifestation of a timeout
        } else if (e.getCause() instanceof HttpRequestTimeoutException) {
            // ok - another kind of timeout
        } else {
            throw e;
        }
    }
}
 
Example #19
Source File: KmsMasterKeyProvider.java    From aws-encryption-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Configures the {@link KmsMasterKeyProvider} to use settings from this {@link AWSKMSClientBuilder} to
 * configure KMS clients. Note that the region set on this builder will be ignored, but all other settings
 * will be propagated into the regional clients.
 *
 * This method will overwrite any credentials set using {@link #withCredentials(AWSCredentialsProvider)}.
 *
 * @param builder
 * @return
 */
public Builder withClientBuilder(AWSKMSClientBuilder builder) {
    if (regionalClientSupplier_ != null) {
        throw clientSupplierComboException();
    }
    final AWSKMSClientBuilder newBuilder = cloneClientBuilder(builder);


    this.templateBuilder_ = newBuilder;

    return this;
}
 
Example #20
Source File: KmsMasterKeyProvider.java    From aws-encryption-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Configures the {@link KmsMasterKeyProvider} to use specific credentials. If a builder was previously set,
 * this will override whatever credentials it set.
 * @param credentialsProvider
 * @return
 */
public Builder withCredentials(AWSCredentialsProvider credentialsProvider) {
    if (regionalClientSupplier_ != null) {
        throw clientSupplierComboException();
    }

    if (templateBuilder_ == null) {
        templateBuilder_ = AWSKMSClientBuilder.standard();
    }

    templateBuilder_.setCredentials(credentialsProvider);

    return this;
}
 
Example #21
Source File: LocalstackContainerTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
@Test
public void kmsKeyCreationTest() {
    AWSKMS awskms = AWSKMSClientBuilder.standard()
        .withEndpointConfiguration(localstack.getEndpointConfiguration(KMS))
        .withCredentials(localstack.getDefaultCredentialsProvider())
        .build();

    String desc = String.format("AWS CMK Description");
    Tag createdByTag = new Tag().withTagKey("CreatedBy").withTagValue("StorageService");
    CreateKeyRequest req = new CreateKeyRequest().withDescription(desc).withTags(createdByTag);
    CreateKeyResult key = awskms.createKey(req);

    assertEquals("AWS KMS Customer Managed Key should be created ", key.getKeyMetadata().getDescription(), desc);
}
 
Example #22
Source File: KMSProviderBuilderIntegrationTests.java    From aws-encryption-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test
public void whenBuilderCloned_clientBuilderCustomizationIsRetained() throws Exception {
    RequestHandler2 handler = spy(new RequestHandler2() {});

    KmsMasterKeyProvider mkp = KmsMasterKeyProvider.builder()
            .withClientBuilder(
                    AWSKMSClientBuilder.standard().withRequestHandlers(handler)
            )
            .withKeysForEncryption(KMSTestFixtures.TEST_KEY_IDS[0])
            .clone().build();

    new AwsCrypto().encryptData(mkp, new byte[0]);

    verify(handler, atLeastOnce()).beforeRequest(any());
}
 
Example #23
Source File: KMSProviderBuilderIntegrationTests.java    From aws-encryption-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void whenBogusEndpointIsSet_constructionFails() throws Exception {
    KmsMasterKeyProvider.builder()
                        .withClientBuilder(
                                AWSKMSClientBuilder.standard()
                                                   .withEndpointConfiguration(
                                                           new AwsClientBuilder.EndpointConfiguration(
                                                                   "https://this.does.not.exist.example.com",
                                                                   "bad-region")
                                                   )
                        );
}
 
Example #24
Source File: ReencryptDataKey.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    AWSKMS kmsClient = AWSKMSClientBuilder.standard().build();
    // Re-encrypt a data key

    ByteBuffer sourceCiphertextBlob = ByteBuffer.wrap(new byte[]{Byte.parseByte("Place your ciphertext here")});


    // Replace the following fictitious CMK ARN with a valid CMK ID or ARN
    String destinationKeyId = "1234abcd-12ab-34cd-56ef-1234567890ab";

    ReEncryptRequest req = new ReEncryptRequest();
    req.setCiphertextBlob(sourceCiphertextBlob);
    req.setDestinationKeyId(destinationKeyId);
    ByteBuffer destinationCipherTextBlob = kmsClient.reEncrypt(req).getCiphertextBlob();
}
 
Example #25
Source File: KMSProviderBuilderIntegrationTests.java    From aws-encryption-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test
public void whenUserAgentsOverridden_originalUAsPreserved() throws Exception {
    RequestHandler2 handler = spy(new RequestHandler2() {});

    KmsMasterKeyProvider mkp = KmsMasterKeyProvider.builder()
                                                   .withClientBuilder(
                                                           AWSKMSClientBuilder.standard().withRequestHandlers(handler)
                                                           .withClientConfiguration(
                                                                   new ClientConfiguration()
                                                                       .withUserAgentPrefix("TEST-UA-PREFIX")
                                                                       .withUserAgentSuffix("TEST-UA-SUFFIX")
                                                           )
                                                   )
                                                   .withKeysForEncryption(KMSTestFixtures.TEST_KEY_IDS[0])
                                                   .clone().build();

    new AwsCrypto().encryptData(mkp, new byte[0]);

    ArgumentCaptor<Request> captor = ArgumentCaptor.forClass(Request.class);
    verify(handler, atLeastOnce()).beforeRequest(captor.capture());

    String ua = (String)captor.getValue().getHeaders().get("User-Agent");

    assertTrue(ua.contains("TEST-UA-PREFIX"));
    assertTrue(ua.contains("TEST-UA-SUFFIX"));
    assertTrue(ua.contains(VersionInfo.USER_AGENT));
}
 
Example #26
Source File: AwsPrivateKeyStore.java    From athenz with Apache License 2.0 5 votes vote down vote up
private static AWSKMS initAWSKMS() {
    String s3Region = System.getProperty(ATHENZ_PROP_AWS_KMS_REGION);
    ///CLOVER:OFF
    if (null != s3Region && !s3Region.isEmpty()) {
        return AWSKMSClientBuilder.standard().withRegion(s3Region).build();
    }
    return AWSKMSClientBuilder.defaultClient();
    ///CLOVER:ON
}
 
Example #27
Source File: RetireGrant.java    From aws-doc-sdk-examples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    AWSKMS kmsClient = AWSKMSClientBuilder.standard().build();

    // Retire a grant
    //
    String grantToken = "Place your grant token here";

    RetireGrantRequest request = new RetireGrantRequest().withGrantToken(grantToken);
    RetireGrantResult response = kmsClient.retireGrant(request);
}
 
Example #28
Source File: AwsKmsEncryptedObject.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
public static void encryptRecord(final String cmkArn, final String region) {
  // Sample object to be encrypted
  DataPoJo record = new DataPoJo();
  record.setPartitionAttribute("is this");
  record.setSortAttribute(55);
  record.setExample("data");
  record.setSomeNumbers(99);
  record.setSomeBinary(new byte[]{0x00, 0x01, 0x02});
  record.setLeaveMe("alone");

  // Set up our configuration and clients
  final AmazonDynamoDB ddb = AmazonDynamoDBClientBuilder.standard().withRegion(region).build();
  final AWSKMS kms = AWSKMSClientBuilder.standard().withRegion(region).build();
  final DirectKmsMaterialProvider cmp = new DirectKmsMaterialProvider(kms, cmkArn);
  // Encryptor creation
  final DynamoDBEncryptor encryptor = DynamoDBEncryptor.getInstance(cmp);
  // Mapper Creation
  // Please note the use of SaveBehavior.PUT (SaveBehavior.CLOBBER works as well).
  // Omitting this can result in data-corruption.
  DynamoDBMapperConfig mapperConfig = DynamoDBMapperConfig.builder().withSaveBehavior(SaveBehavior.PUT).build();
  DynamoDBMapper mapper = new DynamoDBMapper(ddb, mapperConfig, new AttributeEncryptor(encryptor));

  System.out.println("Plaintext Record: " + record);
  // Save the item to the DynamoDB table
  mapper.save(record);

  // Retrieve the encrypted item (directly without decrypting) from Dynamo so we can see it in our example
  final Map<String, AttributeValue> itemKey = new HashMap<>();
  itemKey.put("partition_attribute", new AttributeValue().withS("is this"));
  itemKey.put("sort_attribute", new AttributeValue().withN("55"));
  System.out.println("Encrypted Record: " + ddb.getItem("ExampleTable", itemKey).getItem());
  
  // Retrieve (and decrypt) it from DynamoDB
  DataPoJo decrypted_record = mapper.load(DataPoJo.class, "is this", 55);
  System.out.println("Decrypted Record: " + decrypted_record);
}
 
Example #29
Source File: KMSEncryptionFeature.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
private AWSKMS client(final Path container) throws BackgroundException {
    final AWSKMSClientBuilder builder = AWSKMSClientBuilder.standard()
        .withCredentials(AWSCredentialsConfigurator.toAWSCredentialsProvider(bookmark.getCredentials()))
        .withClientConfiguration(configuration);
    final Location.Name region = locationFeature.getLocation(container);
    if(Location.unknown.equals(region)) {
        builder.withRegion(Regions.DEFAULT_REGION);
    }
    else {
        builder.withRegion(region.getIdentifier());
    }
    return builder.build();
}
 
Example #30
Source File: KMSManager.java    From strongbox with Apache License 2.0 5 votes vote down vote up
public static KMSManager fromCredentials(AWSCredentialsProvider awsCredentials,
                                         ClientConfiguration clientConfiguration,
                                         SecretsGroupIdentifier groupIdentifier) {
    AWSKMS client = AWSKMSClientBuilder.standard()
        .withCredentials(awsCredentials)
        .withClientConfiguration(transformAndVerifyOrThrow(clientConfiguration))
        .withRegion(groupIdentifier.region.getName())
        .build();
    return new KMSManager(client, awsCredentials, clientConfiguration, groupIdentifier);
}