com.amazonaws.services.kms.model.DecryptRequest Java Examples

The following examples show how to use com.amazonaws.services.kms.model.DecryptRequest. 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: 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 #2
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 #3
Source File: AsymmetricEncryptionNotAvailableTest.java    From spring-cloud-config-aws-kms with Apache License 2.0 6 votes vote down vote up
@Test
void testAsymmetricDecryptionIsNotAvailable(CapturedOutput output) {
    doThrow(InvalidCiphertextException.class).when(mockKms).decrypt(any(DecryptRequest.class));

    try {
        // Asymmetric algorithm is not available, because an outdated AWS SDK is used. The textEncryptor will
        // print a warning and fall back to symmetric algorithm.
        // Trying to use an asymmetric key with the symmetric algorithm will lead to an exception.
        textEncryptor.decrypt(CIPHERTEXT);
        failBecauseExceptionWasNotThrown(InvalidCiphertextException.class);
    } catch (InvalidCiphertextException ignored) {
        assertThat(output).contains(VERSION_HINT);
        final DecryptRequest expectedRequest = new DecryptRequest()
                .withCiphertextBlob(ByteBuffer.wrap(Base64.getDecoder().decode(CIPHERTEXT.getBytes())));
        verify(mockKms).decrypt(eq(expectedRequest));
    }
}
 
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: KMSProviderBuilderMockTests.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testUserAgentPassthrough() throws Exception {
    MockKMSClient client = spy(new MockKMSClient());

    String key1 = client.createKey().getKeyMetadata().getArn();
    String key2 = client.createKey().getKeyMetadata().getArn();

    KmsMasterKeyProvider mkp = KmsMasterKeyProvider.builder()
                                                   .withKeysForEncryption(key1, key2)
                                                   .withCustomClientFactory(ignored -> client)
                                                   .build();

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

    ArgumentCaptor<GenerateDataKeyRequest> gdkr = ArgumentCaptor.forClass(GenerateDataKeyRequest.class);
    verify(client, times(1)).generateDataKey(gdkr.capture());
    assertTrue(getUA(gdkr.getValue()).contains(VersionInfo.USER_AGENT));

    ArgumentCaptor<EncryptRequest> encr = ArgumentCaptor.forClass(EncryptRequest.class);
    verify(client, times(1)).encrypt(encr.capture());
    assertTrue(getUA(encr.getValue()).contains(VersionInfo.USER_AGENT));

    ArgumentCaptor<DecryptRequest> decr = ArgumentCaptor.forClass(DecryptRequest.class);
    verify(client, times(1)).decrypt(decr.capture());
    assertTrue(getUA(decr.getValue()).contains(VersionInfo.USER_AGENT));
}
 
Example #6
Source File: MockKMSClient.java    From aws-encryption-sdk-java with Apache License 2.0 6 votes vote down vote up
@Override
public DecryptResult decrypt(DecryptRequest req) throws AmazonServiceException, AmazonClientException {
    DecryptResult result = results_.get(new DecryptMapKey(req));
    if (result != null) {
        // Copy it to avoid external modification
        DecryptResult copy = new DecryptResult();
        copy.setKeyId(retrieveArn(result.getKeyId()));
        byte[] pt = new byte[result.getPlaintext().limit()];
        result.getPlaintext().get(pt);
        result.getPlaintext().rewind();
        copy.setPlaintext(ByteBuffer.wrap(pt));
        return copy;
    } else {
        throw new InvalidCiphertextException("Invalid Ciphertext");
    }
}
 
Example #7
Source File: ConfigServerTest.java    From spring-cloud-config-aws-kms with Apache License 2.0 6 votes vote down vote up
@Test
void testGetConfigFromServer() {
    final ResponseEntity<String> response = rest.getForEntity("/my-test-app/default", String.class);
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
    final JsonContent<?> jsonBody = json.from(response.getBody());
    System.out.println(jsonBody.getJson());
    assertThat(jsonBody).extractingJsonPathValue("$.name")
            .isEqualTo("my-test-app");
    assertThat(jsonBody).extractingJsonPathArrayValue("$.profiles")
            .containsExactly("default");
    assertThat(jsonBody).extractingJsonPathArrayValue("$.propertySources..source['info.foo']")
            .containsExactly("bar");
    assertThat(jsonBody).extractingJsonPathArrayValue("$.propertySources..source['top.secret']")
            .containsExactly("Hello World");

    final DecryptRequest expectedRequest = new DecryptRequest()
            .withCiphertextBlob(ByteBuffer.wrap(Base64.getDecoder().decode("c2VjcmV0".getBytes())));
    verify(mockKms, atLeastOnce()).decrypt(eq(expectedRequest));
}
 
Example #8
Source File: AsymmetricEncryptionAlgorithmTest.java    From spring-cloud-config-aws-kms with Apache License 2.0 5 votes vote down vote up
@Test
void testDecryptAsymmetricProperty() {
    assertThat(decryptedSecret1).isEqualTo(PLAINTEXT);

    final DecryptRequest decryptRequest = new DecryptRequest();
    decryptRequest.withCiphertextBlob(CIPHER_TEXT_BLOB1);
    decryptRequest.withEncryptionAlgorithm(RSAES_OAEP_SHA_1);
    decryptRequest.withKeyId("asymmetric-sha1-sample-key");
    verify(mockKms, atLeastOnce()).decrypt(eq(decryptRequest));
}
 
Example #9
Source File: KmsEncryptionTest.java    From spring-cloud-config-aws-kms with Apache License 2.0 5 votes vote down vote up
@Test
public void testPropertyHasBeenDecrypted() {

    assertThat(decryptedSecret).isEqualTo(MockAwsKmsConfig.PLAINTEXT);

    final DecryptRequest decryptRequest = new DecryptRequest();
    decryptRequest.setCiphertextBlob(CIPHER_TEXT_BLOB);
    verify(mockKms, atLeastOnce()).decrypt(decryptRequest);
}
 
Example #10
Source File: AsymmetricEncryptionAlgorithmTest.java    From spring-cloud-config-aws-kms with Apache License 2.0 5 votes vote down vote up
@Test
void testAlgorithmsCanBeMixed() {
    assertThat(decryptedSecret2).isEqualTo(PLAINTEXT);

    final DecryptRequest decryptRequest = new DecryptRequest();
    decryptRequest.withCiphertextBlob(CIPHER_TEXT_BLOB2);
    decryptRequest.withEncryptionAlgorithm(SYMMETRIC_DEFAULT);
    verify(mockKms, atLeastOnce()).decrypt(eq(decryptRequest));
}
 
Example #11
Source File: AsymmetricEncryptionAlgorithmTest.java    From spring-cloud-config-aws-kms with Apache License 2.0 5 votes vote down vote up
@Test
void testSecretWithCustomKeyId() {
    assertThat(decryptedSecret3).isEqualTo(PLAINTEXT);

    final DecryptRequest decryptRequest = new DecryptRequest();
    decryptRequest.withCiphertextBlob(CIPHER_TEXT_BLOB3);
    decryptRequest.withEncryptionAlgorithm(RSAES_OAEP_SHA_256);
    decryptRequest.withKeyId("different-key");
    verify(mockKms, atLeastOnce()).decrypt(eq(decryptRequest));
}
 
Example #12
Source File: AsymmetricEncryptionMissingKeyIdTest.java    From spring-cloud-config-aws-kms with Apache License 2.0 5 votes vote down vote up
@Test
void testDecryptFails() {
    final String someCipher = Base64.getEncoder().encodeToString("SOME_CIPHER".getBytes());
    try {
        textEncryptor.decrypt(someCipher);
        failBecauseExceptionWasNotThrown(RuntimeException.class);
    } catch (Exception e) {
        assertThat(e).hasMessageContaining("kmsKeyId must not be blank. Asymmetric decryption requires the key to be known");
    }
    verify(mockKms, never()).decrypt(any(DecryptRequest.class));
}
 
Example #13
Source File: KmsTextEncryptor.java    From spring-cloud-config-aws-kms with Apache License 2.0 5 votes vote down vote up
@Override
public String decrypt(final String encryptedText) {
    if (encryptedText == null || encryptedText.isEmpty()) {
        return EMPTY_STRING;
    } else {

        final EncryptedToken token = EncryptedToken.parse(encryptedText);

        final DecryptRequest decryptRequest = new DecryptRequest()
                .withCiphertextBlob(token.getCipherBytes())
                .withEncryptionContext(token.getEncryptionContext());
        final KmsTextEncryptorOptions options = token.getOptions();
        final String keyId = Optional.ofNullable(options.getKeyId()).orElse(kmsKeyId);
        final String algorithm = Optional.ofNullable(options.getEncryptionAlgorithm()).orElse(encryptionAlgorithm);

        checkAlgorithm(algorithm);

        if (IS_ALGORITHM_AVAILABLE) {
            decryptRequest.setEncryptionAlgorithm(algorithm);
            if (isAsymmetricEncryption(algorithm)) {
                Assert.hasText(keyId, "kmsKeyId must not be blank. Asymmetric decryption requires the key to be known");
                decryptRequest.setKeyId(keyId);
            }
        }

        return extractString(kms.decrypt(decryptRequest).getPlaintext(), options.getOutputMode());
    }
}
 
Example #14
Source File: KmsDaoImpl.java    From herd with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #15
Source File: MockKmsOperationsImpl.java    From herd with Apache License 2.0 5 votes vote down vote up
@Override
public DecryptResult decrypt(AWSKMSClient awsKmsClient, DecryptRequest decryptRequest)
{
    // Check the cipher text.
    if (decryptRequest.getCiphertextBlob().equals(ByteBuffer.wrap(Base64.decodeBase64(MOCK_CIPHER_TEXT_INVALID))))
    {
        throw new InvalidCiphertextException("(Service: AWSKMS; Status Code: 400; Error Code: InvalidCiphertextException; Request ID: NONE)");
    }

    DecryptResult decryptResult = new DecryptResult();

    // Convert the test plain text to byte buffer and set the plain text return value.
    decryptResult.setPlaintext(ByteBuffer.wrap(MOCK_PLAIN_TEXT.getBytes()));

    return decryptResult;
}
 
Example #16
Source File: DirectKmsMaterialProvider.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
@Override
public DecryptionMaterials getDecryptionMaterials(EncryptionContext context) {
    final Map<String, String> materialDescription = context.getMaterialDescription();

    final Map<String, String> ec = new HashMap<>();
    final String providedEncAlg = materialDescription.get(CONTENT_KEY_ALGORITHM);
    final String providedSigAlg = materialDescription.get(SIGNING_KEY_ALGORITHM);

    ec.put("*" + CONTENT_KEY_ALGORITHM + "*", providedEncAlg);
    ec.put("*" + SIGNING_KEY_ALGORITHM + "*", providedSigAlg);

    populateKmsEcFromEc(context, ec);

    DecryptRequest request = appendUserAgent(new DecryptRequest());
    request.setCiphertextBlob(ByteBuffer.wrap(Base64.decode(materialDescription.get(ENVELOPE_KEY))));
    request.setEncryptionContext(ec);
    final DecryptResult decryptResult = decrypt(request, context);
    validateEncryptionKeyId(decryptResult.getKeyId(), context);

    final Hkdf kdf;
    try {
        kdf = Hkdf.getInstance(KDF_ALG);
    } catch (NoSuchAlgorithmException e) {
        throw new DynamoDBMappingException(e);
    }
    kdf.init(toArray(decryptResult.getPlaintext()));

    final String[] encAlgParts = providedEncAlg.split("/", 2);
    int encLength = encAlgParts.length == 2 ? Integer.parseInt(encAlgParts[1]) : 256;
    final String[] sigAlgParts = providedSigAlg.split("/", 2);
    int sigLength = sigAlgParts.length == 2 ? Integer.parseInt(sigAlgParts[1]) : 256;

    final SecretKey encryptionKey = new SecretKeySpec(kdf.deriveKey(KDF_ENC_INFO, encLength / 8), encAlgParts[0]);
    final SecretKey macKey = new SecretKeySpec(kdf.deriveKey(KDF_SIG_INFO, sigLength / 8), sigAlgParts[0]);

    return new SymmetricRawMaterials(encryptionKey, macKey, materialDescription);
}
 
Example #17
Source File: FakeKMS.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
@Override
public DecryptResult decrypt(DecryptRequest req) throws AmazonServiceException,
        AmazonClientException {
    DecryptResult result = results_.get(new DecryptMapKey(req));
    if (result != null) {
        return result;
    } else {
        throw new InvalidCiphertextException("Invalid Ciphertext");
    }
}
 
Example #18
Source File: FakeKMS.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
public DecryptMapKey(DecryptRequest req) {
    cipherText = req.getCiphertextBlob().asReadOnlyBuffer();
    if (req.getEncryptionContext() != null) {
        ec = Collections.unmodifiableMap(new HashMap<String, String>(req
                .getEncryptionContext()));
    } else {
        ec = Collections.emptyMap();
    }
}
 
Example #19
Source File: ConfigDecryptor.java    From xyz-hub with Apache License 2.0 5 votes vote down vote up
private static String decryptSymmetricKey(String encryptedKey) throws CryptoException {
  ByteBuffer cipherTextBlob = ByteBuffer.wrap(Base64.getDecoder().decode(encryptedKey));
  DecryptRequest req = new DecryptRequest().withCiphertextBlob(cipherTextBlob);
  try {
    ByteBuffer plainTextBytes = getKmsClient().decrypt(req).getPlaintext();
    return new String(Base64.getEncoder().encode(plainTextBytes.array()));
  } catch (RuntimeException e) {
    throw new CryptoException("Error when trying to decrypt symmetric key. Please check the following:\n"
        + "\t- Does the application use an IAM role?\n"
        + "\t- Does the application's role have the permission to use the CMK the value was encrypted with?\n"
        + "More information on that topic: https://confluence.in.here.com/display/CMECMCPDOWS/Encryption+of+secrets");
  }
}
 
Example #20
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 #21
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 #22
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 #23
Source File: AwsPrivateKeyStore.java    From athenz with Apache License 2.0 5 votes vote down vote up
private String getDecryptedData(final String bucketName, final String keyName) {
    
    String keyValue = "";
    S3Object s3Object = getS3().getObject(bucketName, keyName);
    
    if (LOG.isDebugEnabled()) {
        LOG.debug("retrieving appName {}, key {}", bucketName, keyName);
    }
    
    if (null == s3Object) {
        LOG.error("error retrieving key {}, from bucket {}", keyName, bucketName);
        return keyValue;
    }
    
    try (S3ObjectInputStream s3InputStream = s3Object.getObjectContent(); 
            ByteArrayOutputStream result = new ByteArrayOutputStream()) {
        
        byte[] buffer = new byte[1024];
        int length;
        ///CLOVER:OFF
        while ((length = s3InputStream.read(buffer)) != -1) {
            result.write(buffer, 0, length);
        }
        ///CLOVER:ON
        // if key should be decrypted, do so with KMS

        if (kmsDecrypt) {
            DecryptRequest req = new DecryptRequest().withCiphertextBlob(ByteBuffer.wrap(result.toByteArray()));
            ByteBuffer plainText = getKMS().decrypt(req).getPlaintext();
            keyValue = new String(plainText.array());
        } else {
            keyValue = result.toString();
        }
        
    } catch (IOException e) {
        LOG.error("error getting application secret.", e);
    }

    return keyValue.trim();
}
 
Example #24
Source File: MockKMSClient.java    From aws-encryption-sdk-java with Apache License 2.0 5 votes vote down vote up
public DecryptMapKey(DecryptRequest req) {
    cipherText = req.getCiphertextBlob().asReadOnlyBuffer();
    if (req.getEncryptionContext() != null) {
        ec = Collections.unmodifiableMap(new HashMap<String, String>(req.getEncryptionContext()));
    } else {
        ec = Collections.emptyMap();
    }
}
 
Example #25
Source File: KmsMasterKey.java    From aws-encryption-sdk-java with Apache License 2.0 5 votes vote down vote up
@Override
public DataKey<KmsMasterKey> decryptDataKey(final CryptoAlgorithm algorithm,
        final Collection<? extends EncryptedDataKey> encryptedDataKeys,
        final Map<String, String> encryptionContext)
        throws UnsupportedProviderException, AwsCryptoException {
    final List<Exception> exceptions = new ArrayList<>();
    for (final EncryptedDataKey edk : encryptedDataKeys) {
        try {
            final DecryptResult decryptResult = kms_.get().decrypt(updateUserAgent(
                    new DecryptRequest()
                            .withCiphertextBlob(ByteBuffer.wrap(edk.getEncryptedDataKey()))
                            .withEncryptionContext(encryptionContext)
                            .withGrantTokens(grantTokens_)));
            if (decryptResult.getKeyId().equals(id_)) {
                final byte[] rawKey = new byte[algorithm.getDataKeyLength()];
                decryptResult.getPlaintext().get(rawKey);
                if (decryptResult.getPlaintext().remaining() > 0) {
                    throw new IllegalStateException("Received an unexpected number of bytes from KMS");
                }
                return new DataKey<>(
                        new SecretKeySpec(rawKey, algorithm.getDataKeyAlgo()),
                        edk.getEncryptedDataKey(),
                        edk.getProviderInformation(), this);
            }
        } catch (final AmazonServiceException awsex) {
            exceptions.add(awsex);
        }
    }

    throw buildCannotDecryptDksException(exceptions);
}
 
Example #26
Source File: DecryptDataKey.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();
    // Decrypt a data key
    //

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

    DecryptRequest req = new DecryptRequest().withCiphertextBlob(ciphertextBlob);
    ByteBuffer plainText = kmsClient.decrypt(req).getPlaintext();

}
 
Example #27
Source File: AwsKms.java    From sfs with Apache License 2.0 5 votes vote down vote up
@Override
public Observable<byte[]> decrypt(VertxContext<Server> vertxContext, byte[] cipherBytes) {
    SfsVertx sfsVertx = vertxContext.vertx();
    return Observable.defer(() -> RxHelper.executeBlocking(sfsVertx.getOrCreateContext(), sfsVertx.getBackgroundPool(), () -> {
        DecryptRequest req =
                new DecryptRequest()
                        .withCiphertextBlob(ByteBuffer.wrap(cipherBytes.clone()));
        ByteBuffer buffer = kms.decrypt(req).getPlaintext();
        byte[] b = new byte[buffer.remaining()];
        buffer.get(b);
        return b;
    }));
}
 
Example #28
Source File: KMSProviderBuilderMockTests.java    From aws-encryption-sdk-java with Apache License 2.0 4 votes vote down vote up
@Test
public void testGrantTokenPassthrough_usingMKPWithers() throws Exception {
    MockKMSClient client = spy(new MockKMSClient());

    RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
    when(supplier.getClient(any())).thenReturn(client);

    String key1 = client.createKey().getKeyMetadata().getArn();
    String key2 = client.createKey().getKeyMetadata().getArn();

    KmsMasterKeyProvider mkp0 = KmsMasterKeyProvider.builder()
                                                    .withDefaultRegion("us-west-2")
                                                    .withCustomClientFactory(supplier)
                                                    .withKeysForEncryption(key1, key2)
                                                    .build();

    MasterKeyProvider<?> mkp = mkp0.withGrantTokens("foo");

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

    ArgumentCaptor<GenerateDataKeyRequest> gdkr = ArgumentCaptor.forClass(GenerateDataKeyRequest.class);
    verify(client, times(1)).generateDataKey(gdkr.capture());

    assertEquals(key1, gdkr.getValue().getKeyId());
    assertEquals(1, gdkr.getValue().getGrantTokens().size());
    assertEquals("foo", gdkr.getValue().getGrantTokens().get(0));

    ArgumentCaptor<EncryptRequest> er = ArgumentCaptor.forClass(EncryptRequest.class);
    verify(client, times(1)).encrypt(er.capture());

    assertEquals(key2, er.getValue().getKeyId());
    assertEquals(1, er.getValue().getGrantTokens().size());
    assertEquals("foo", er.getValue().getGrantTokens().get(0));

    mkp = mkp0.withGrantTokens(Arrays.asList("bar"));

    new AwsCrypto().decryptData(mkp, ciphertext);

    ArgumentCaptor<DecryptRequest> decrypt = ArgumentCaptor.forClass(DecryptRequest.class);
    verify(client, times(1)).decrypt(decrypt.capture());

    assertEquals(1, decrypt.getValue().getGrantTokens().size());
    assertEquals("bar", decrypt.getValue().getGrantTokens().get(0));

    verify(supplier, atLeastOnce()).getClient("us-west-2");
    verifyNoMoreInteractions(supplier);
}
 
Example #29
Source File: KmsOperationsImpl.java    From herd with Apache License 2.0 4 votes vote down vote up
@Override
public DecryptResult decrypt(AWSKMSClient awsKmsClient, DecryptRequest decryptRequest)
{
    // Call AWS KMS decrypt service method.
    return awsKmsClient.decrypt(decryptRequest);
}
 
Example #30
Source File: KMSProviderBuilderMockTests.java    From aws-encryption-sdk-java with Apache License 2.0 4 votes vote down vote up
@Test
public void testGrantTokenPassthrough_usingMKsetCall() throws Exception {
    MockKMSClient client = spy(new MockKMSClient());

    RegionalClientSupplier supplier = mock(RegionalClientSupplier.class);
    when(supplier.getClient(any())).thenReturn(client);

    String key1 = client.createKey().getKeyMetadata().getArn();
    String key2 = client.createKey().getKeyMetadata().getArn();

    KmsMasterKeyProvider mkp0 = KmsMasterKeyProvider.builder()
                                                   .withDefaultRegion("us-west-2")
                                                   .withCustomClientFactory(supplier)
                                                   .withKeysForEncryption(key1, key2)
                                                   .build();
    KmsMasterKey mk1 = mkp0.getMasterKey(key1);
    KmsMasterKey mk2 = mkp0.getMasterKey(key2);

    mk1.setGrantTokens(singletonList("foo"));
    mk2.setGrantTokens(singletonList("foo"));

    MasterKeyProvider<?> mkp = buildMultiProvider(mk1, mk2);

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

    ArgumentCaptor<GenerateDataKeyRequest> gdkr = ArgumentCaptor.forClass(GenerateDataKeyRequest.class);
    verify(client, times(1)).generateDataKey(gdkr.capture());

    assertEquals(key1, gdkr.getValue().getKeyId());
    assertEquals(1, gdkr.getValue().getGrantTokens().size());
    assertEquals("foo", gdkr.getValue().getGrantTokens().get(0));

    ArgumentCaptor<EncryptRequest> er = ArgumentCaptor.forClass(EncryptRequest.class);
    verify(client, times(1)).encrypt(er.capture());

    assertEquals(key2, er.getValue().getKeyId());
    assertEquals(1, er.getValue().getGrantTokens().size());
    assertEquals("foo", er.getValue().getGrantTokens().get(0));

    new AwsCrypto().decryptData(mkp, ciphertext);

    ArgumentCaptor<DecryptRequest> decrypt = ArgumentCaptor.forClass(DecryptRequest.class);
    verify(client, times(1)).decrypt(decrypt.capture());

    assertEquals(1, decrypt.getValue().getGrantTokens().size());
    assertEquals("foo", decrypt.getValue().getGrantTokens().get(0));

    verify(supplier, atLeastOnce()).getClient("us-west-2");
    verifyNoMoreInteractions(supplier);
}