com.amazonaws.services.kms.AWSKMS Java Examples

The following examples show how to use com.amazonaws.services.kms.AWSKMS. 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: 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 #2
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 #3
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 #4
Source File: KmsTextEncryptorTest.java    From spring-cloud-config-aws-kms with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
    mockKms = mock(AWSKMS.class);
    textEncryptor = new KmsTextEncryptor(mockKms, KMS_KEY_ID, SYMMETRIC_DEFAULT.toString());

    expectedEncryptRequest = new EncryptRequest();
    expectedEncryptRequest.setKeyId(KMS_KEY_ID);
    expectedEncryptRequest.setPlaintext(wrap(PLAINTEXT.getBytes()));
    expectedEncryptRequest.setEncryptionAlgorithm(SYMMETRIC_DEFAULT.toString());

    encryptResult = new EncryptResult();
    encryptResult.setCiphertextBlob(wrap(CIPHER_TEXT.getBytes()));
    when(mockKms.encrypt(any(EncryptRequest.class))).thenReturn(encryptResult);

    expectedDecryptRequest = new DecryptRequest();
    expectedDecryptRequest.setCiphertextBlob(wrap(CIPHER_TEXT.getBytes()));
    expectedDecryptRequest.setEncryptionAlgorithm(SYMMETRIC_DEFAULT.toString());

    decryptResult = new DecryptResult();
    decryptResult.setPlaintext(wrap(PLAINTEXT.getBytes()));
    when(mockKms.decrypt(any(DecryptRequest.class))).thenReturn(decryptResult);
}
 
Example #5
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 #6
Source File: KmsService.java    From cerberus with Apache License 2.0 6 votes vote down vote up
/**
 * Gets all the KMS CMK ids for a given region
 *
 * @param regionName The region in which you want all the KMS CMK ids
 * @return A list of of the KMS CMK ids for the requested region.
 */
public Set<String> getKmsKeyIdsForRegion(String regionName) {
  AWSKMS kms = kmsClientFactory.getClient(regionName);

  Set<String> kmsKeyIdsForRegion = new HashSet<>();

  String marker = null;
  do {
    logger.debug("Fetching keys for region: {} and marker: {}", regionName, marker);
    ListKeysRequest listKeysRequest = new ListKeysRequest();
    if (marker != null) {
      listKeysRequest.withMarker(marker);
    }
    ListKeysResult listKeysResult = kms.listKeys(listKeysRequest);
    listKeysResult
        .getKeys()
        .forEach(keyListEntry -> kmsKeyIdsForRegion.add(keyListEntry.getKeyId()));
    marker = listKeysResult.getNextMarker();
  } while (marker != null);

  return kmsKeyIdsForRegion;
}
 
Example #7
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 #8
Source File: JCredStashTest.java    From jcredstash with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
    dynamoDBClient = Mockito.mock(AmazonDynamoDB.class);

    GenerateDataKeyResult generateDatakeyResult = new GenerateDataKeyResult();
    generateDatakeyResult.setCiphertextBlob(Mockito.mock(ByteBuffer.class));
    generateDatakeyResult.setPlaintext(Mockito.mock(ByteBuffer.class));

    DecryptResult decryptResult = new DecryptResult();
    decryptResult.setKeyId("alias/foo");
    decryptResult.setPlaintext(Mockito.mock(ByteBuffer.class));

    awskmsClient = Mockito.mock(AWSKMS.class);
    Mockito.when(awskmsClient.generateDataKey(Mockito.any(GenerateDataKeyRequest.class))).thenReturn(generateDatakeyResult);
    Mockito.when(awskmsClient.decrypt(Mockito.any(DecryptRequest.class))).thenReturn(decryptResult);
}
 
Example #9
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 #10
Source File: DirectKmsMaterialProvider.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
public DirectKmsMaterialProvider(AWSKMS kms, String encryptionKeyId, Map<String, String> materialDescription) {
    this.kms = kms;
    this.encryptionKeyId = encryptionKeyId;
    this.description = materialDescription != null ?
            Collections.unmodifiableMap(new HashMap<>(materialDescription)) :
                Collections.<String, String> emptyMap();

    dataKeyDesc = description
            .containsKey(WrappedRawMaterials.CONTENT_KEY_ALGORITHM) ? description
            .get(WrappedRawMaterials.CONTENT_KEY_ALGORITHM) : DEFAULT_ENC_ALG;

    String[] parts = dataKeyDesc.split("/", 2);
    this.dataKeyAlg = parts[0];
    this.dataKeyLength = parts.length == 2 ? Integer.parseInt(parts[1]) : 256;

    sigKeyDesc = description
            .containsKey(SIGNING_KEY_ALGORITHM) ? description
            .get(SIGNING_KEY_ALGORITHM) : DEFAULT_SIG_ALG;

    parts = sigKeyDesc.split("/", 2);
    this.sigKeyAlg = parts[0];
    this.sigKeyLength = parts.length == 2 ? Integer.parseInt(parts[1]) : 256;
}
 
Example #11
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 #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: KMSProviderBuilderIntegrationTests.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
public void whenOperationSuccessful_clientIsCached() {
    AtomicReference<ConcurrentHashMap<String, AWSKMS>> kmsCache = new AtomicReference<>();

    KmsMasterKeyProvider mkp = (new KmsMasterKeyProvider.Builder() {
        @Override protected void snoopClientCache(
                final ConcurrentHashMap<String, AWSKMS> map
        ) {
            kmsCache.set(map);
        }
    }).withKeysForEncryption(KMSTestFixtures.TEST_KEY_IDS[0])
      .build();

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

    AWSKMS kms = kmsCache.get().get("us-west-2");
    assertNotNull(kms);

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

    // Cache entry should stay the same
    assertEquals(kms, kmsCache.get().get("us-west-2"));
}
 
Example #14
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 #15
Source File: DirectKmsMaterialProviderTest.java    From aws-dynamodb-encryption-java with Apache License 2.0 6 votes vote down vote up
@Test
public void generateDataKeyIsCalledWith256NumberOfBits() {
    final AtomicBoolean gdkCalled = new AtomicBoolean(false);
    AWSKMS kmsSpy = new FakeKMS() {
        @Override
        public GenerateDataKeyResult generateDataKey(GenerateDataKeyRequest r) {
            gdkCalled.set(true);
            assertEquals((Integer) 32, r.getNumberOfBytes());
            assertNull(r.getKeySpec());
            return super.generateDataKey(r);
        }
    };
    assertFalse(gdkCalled.get());
    new DirectKmsMaterialProvider(kmsSpy, keyId).getEncryptionMaterials(ctx);
    assertTrue(gdkCalled.get());
}
 
Example #16
Source File: AbstractFernetKeyRotator.java    From fernet-java8 with Apache License 2.0 6 votes vote down vote up
protected AbstractFernetKeyRotator(final ObjectMapper mapper, final SecretsManager secretsManager, final AWSKMS kms,
        final SecureRandom random) {
    if (mapper == null) {
        throw new IllegalArgumentException("mapper cannot be null");
    }
    if (secretsManager == null) {
        throw new IllegalArgumentException("secretsManager cannot be null");
    }
    if (kms == null) {
        throw new IllegalArgumentException("kms cannot be null");
    }
    if (random == null) {
        throw new IllegalArgumentException("random cannot be null");
    }
    this.mapper = mapper;
    this.secretsManager = secretsManager;
    this.kms = kms;
    this.random = random;
}
 
Example #17
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 #18
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 #19
Source File: AwsPrivateKeyStoreTest.java    From athenz with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetKMS() {
    AWSKMS kms = mock(AWSKMS.class);
    AmazonS3 s3 = mock(AmazonS3.class);
    AwsPrivateKeyStore privateKeyStore = new AwsPrivateKeyStore(s3, kms);

    assertEquals(privateKeyStore.getKMS(), kms);
}
 
Example #20
Source File: KmsMasterKeyProvider.java    From aws-encryption-sdk-java with Apache License 2.0 5 votes vote down vote up
private SuccessfulRequestCacher(
        final ConcurrentHashMap<String, AWSKMS> cache,
        final String region
) {
    this.region_ = region;
    this.cache_ = cache;
}
 
Example #21
Source File: KmsTextEncryptor.java    From spring-cloud-config-aws-kms with Apache License 2.0 5 votes vote down vote up
/**
 * @param kms                 The AWS KMS client
 * @param kmsKeyId            The ID or full ARN of the KMS key, e.g.
 *                            arn:aws:kms:eu-west-1:089972051332:key/9d9fca31-54c5-4de5-ba4f-128dfb9a5031. Must not be blank,
 * @param encryptionAlgorithm the encryption algorithm that should be used
 */
public KmsTextEncryptor(final AWSKMS kms, final String kmsKeyId, final String encryptionAlgorithm) {
    Assert.notNull(kms, "KMS client must not be null");
    Assert.notNull(encryptionAlgorithm, "encryptionAlgorithm must not be null");
    this.kms = kms;
    this.kmsKeyId = kmsKeyId;
    this.encryptionAlgorithm = encryptionAlgorithm;

    checkAlgorithm(encryptionAlgorithm);
}
 
Example #22
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 #23
Source File: AwsPrivateKeyStoreTest.java    From athenz with Apache License 2.0 5 votes vote down vote up
@Test
public void testAwsPrivateKeyStore() {
    System.setProperty("athenz.aws.s3.region", "us-east-1");
    System.setProperty(ATHENZ_AWS_KMS_REGION, "us-east-1");
    String bucketName = "my_bucket";
    String keyName = "my_key";
    String expected = "my_value";

    System.setProperty(ATHENZ_PROP_ZTS_BUCKET_NAME, bucketName);
    System.setProperty("athenz.aws.zts.key_name", keyName);

    AmazonS3 s3 = mock(AmazonS3.class);
    AWSKMS kms = mock(AWSKMS.class);
    S3Object s3Object = mock(S3Object.class);
    Mockito.when(s3.getObject(bucketName, keyName)).thenReturn(s3Object);
    InputStream is = new ByteArrayInputStream( expected.getBytes() );
    S3ObjectInputStream s3ObjectInputStream = new S3ObjectInputStream(is, null);
    Mockito.when(s3Object.getObjectContent()).thenReturn(s3ObjectInputStream);

    ByteBuffer buffer = ByteBuffer.wrap(expected.getBytes());
    DecryptResult decryptResult = mock(DecryptResult.class);
    Mockito.when(kms.decrypt(Mockito.any(DecryptRequest.class))).thenReturn(decryptResult);
    Mockito.when(decryptResult.getPlaintext()).thenReturn(buffer);

    AwsPrivateKeyStore awsPrivateKeyStore = new AwsPrivateKeyStore(s3, kms);
    String actual = awsPrivateKeyStore.getApplicationSecret(bucketName, keyName);
    StringBuilder privateKeyId = new StringBuilder(keyName);
    awsPrivateKeyStore.getPrivateKey("zts", "testServerHostName", privateKeyId);
    Assert.assertEquals(actual, expected);
    Mockito.when(s3Object.getObjectContent()).thenAnswer(invocation -> { throw new IOException("test IOException"); });
    awsPrivateKeyStore.getPrivateKey("zts", "testServerHostName", privateKeyId);

    System.clearProperty("athenz.aws.s3.region");
    System.clearProperty(ATHENZ_AWS_KMS_REGION);
}
 
Example #24
Source File: AwsPrivateKeyStoreTest.java    From athenz with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetApplicationSecret() {
    System.setProperty("athenz.aws.s3.region", "us-east-1");
    System.setProperty(ATHENZ_AWS_KMS_REGION, "us-east-1");
    String bucketName = "my_bucket";
    String keyName = "my_key";
    String expected = "my_value";

    AmazonS3 s3 = mock(AmazonS3.class);
    AWSKMS kms = mock(AWSKMS.class);
    S3Object s3Object = mock(S3Object.class);
    Mockito.when(s3.getObject(bucketName, keyName)).thenReturn(s3Object);
    InputStream is = new ByteArrayInputStream( expected.getBytes() );
    S3ObjectInputStream s3ObjectInputStream = new S3ObjectInputStream(is, null);
    Mockito.when(s3Object.getObjectContent()).thenReturn(s3ObjectInputStream);

    ByteBuffer buffer = ByteBuffer.wrap(expected.getBytes());
    DecryptResult decryptResult = mock(DecryptResult.class);
    Mockito.when(kms.decrypt(Mockito.any(DecryptRequest.class))).thenReturn(decryptResult);
    Mockito.when(decryptResult.getPlaintext()).thenReturn(buffer);

    System.setProperty("athenz.aws.store_kms_decrypt", "true");
    AwsPrivateKeyStore awsPrivateKeyStore = new AwsPrivateKeyStore();
    AwsPrivateKeyStore spyAWS = Mockito.spy(awsPrivateKeyStore);
    doReturn(s3).when(spyAWS).getS3();
    doReturn(kms).when(spyAWS).getKMS();
    String actual = spyAWS.getApplicationSecret(bucketName, keyName);
    Assert.assertEquals(actual, expected);
    System.clearProperty("athenz.aws.s3.region");
    System.clearProperty(ATHENZ_AWS_KMS_REGION);
}
 
Example #25
Source File: AwsPrivateKeyStoreTest.java    From athenz with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetEncryptedDataException() {
    System.setProperty("athenz.aws.s3.region", "us-east-1");
    System.setProperty(ATHENZ_AWS_KMS_REGION, "us-east-1");
    String bucketName = "my_bucket";
    String keyName = "my_key";
    String expected = "my_value";

    AmazonS3 s3 = mock(AmazonS3.class);
    AWSKMS kms = mock(AWSKMS.class);
    S3Object s3Object = mock(S3Object.class);
    Mockito.when(s3.getObject(bucketName, keyName)).thenReturn(s3Object);
    InputStream is = new ByteArrayInputStream( expected.getBytes() );
    given(s3Object.getObjectContent()).willAnswer(invocation -> { throw new IOException();});

    ByteBuffer buffer = ByteBuffer.wrap(expected.getBytes());
    DecryptResult decryptResult = mock(DecryptResult.class);
    Mockito.when(kms.decrypt(Mockito.any(DecryptRequest.class))).thenReturn(decryptResult);
    Mockito.when(decryptResult.getPlaintext()).thenReturn(buffer);

    System.setProperty("athenz.aws.store_kms_decrypt", "true");
    AwsPrivateKeyStore awsPrivateKeyStore = new AwsPrivateKeyStore();
    AwsPrivateKeyStore spyAWS = Mockito.spy(awsPrivateKeyStore);
    doReturn(s3).when(spyAWS).getS3();

    doReturn(kms).when(spyAWS).getKMS();
    assertEquals(spyAWS.getKMS(), kms);

    System.clearProperty("athenz.aws.s3.region");
    System.clearProperty(ATHENZ_AWS_KMS_REGION);
}
 
Example #26
Source File: KMSProviderBuilderIntegrationTests.java    From aws-encryption-sdk-java with Apache License 2.0 5 votes vote down vote up
@Test
public void whenBogusRegionsDecrypted_doesNotLeakClients() throws Exception {
    AtomicReference<ConcurrentHashMap<String, AWSKMS>> kmsCache = new AtomicReference<>();

    KmsMasterKeyProvider mkp = (new KmsMasterKeyProvider.Builder() {
        @Override protected void snoopClientCache(
                final ConcurrentHashMap<String, AWSKMS> map
        ) {
            kmsCache.set(map);
        }
    }).build();

    try {
        mkp.decryptDataKey(
                CryptoAlgorithm.ALG_AES_128_GCM_IV12_TAG16_HKDF_SHA256,
                Collections.singleton(
                        new KeyBlob("aws-kms",
                                    "arn:aws:kms:us-bogus-1:123456789010:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f"
                                            .getBytes(StandardCharsets.UTF_8),
                                    new byte[40]
                        )
                ),
                new HashMap<>()
        );
        fail("Expected CannotUnwrapDataKeyException");
    } catch (CannotUnwrapDataKeyException e) {
        // ok
    }

    assertTrue(kmsCache.get().isEmpty());
}
 
Example #27
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 #28
Source File: KmsMasterKeyProvider.java    From aws-encryption-sdk-java with Apache License 2.0 5 votes vote down vote up
@Override
public KmsMasterKey getMasterKey(final String provider, final String keyId) throws UnsupportedProviderException,
        NoSuchMasterKeyException {
    if (!canProvide(provider)) {
        throw new UnsupportedProviderException();
    }

    String regionName = parseRegionfromKeyArn(keyId);

    if (regionName == null && defaultRegion_ != null) {
        regionName = defaultRegion_;
    }

    String regionName_ = regionName;

    Supplier<AWSKMS> kmsSupplier = () -> {
        AWSKMS kms = regionalClientSupplier_.getClient(regionName_);
        if (kms == null) {
            throw new AwsCryptoException("Can't use keys from region " + regionName_);
        }
        return kms;
    };

    final KmsMasterKey result = KmsMasterKey.getInstance(kmsSupplier, keyId, this);
    result.setGrantTokens(grantTokens_);
    return result;
}
 
Example #29
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 #30
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();
}