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

The following examples show how to use com.amazonaws.services.kms.model.DecryptResult. 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: 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 #3
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 #4
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 #5
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 #6
Source File: MockKMSClient.java    From aws-encryption-sdk-java with Apache License 2.0 5 votes vote down vote up
private EncryptResult encrypt0(EncryptRequest req) throws AmazonServiceException, AmazonClientException {
    final byte[] cipherText = new byte[512];
    rnd.nextBytes(cipherText);
    DecryptResult dec = new DecryptResult();
    dec.withKeyId(retrieveArn(req.getKeyId())).withPlaintext(req.getPlaintext().asReadOnlyBuffer());
    ByteBuffer ctBuff = ByteBuffer.wrap(cipherText);

    results_.put(new DecryptMapKey(ctBuff, req.getEncryptionContext()), dec);

    String arn = retrieveArn(req.getKeyId());
    return new EncryptResult().withCiphertextBlob(ctBuff).withKeyId(arn);
}
 
Example #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
Source File: FakeKMS.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
@Override
public EncryptResult encrypt(EncryptRequest req) throws AmazonServiceException,
        AmazonClientException {
    final byte[] cipherText = new byte[512];
    rnd.nextBytes(cipherText);
    DecryptResult dec = new DecryptResult();
    dec.withKeyId(req.getKeyId()).withPlaintext(req.getPlaintext().asReadOnlyBuffer());
    ByteBuffer ctBuff = ByteBuffer.wrap(cipherText);

    results_.put(new DecryptMapKey(ctBuff, req.getEncryptionContext()), dec);

    return new EncryptResult().withCiphertextBlob(ctBuff).withKeyId(req.getKeyId());
}
 
Example #15
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 #16
Source File: DirectKmsMaterialProviderTest.java    From aws-dynamodb-encryption-java with Apache License 2.0 4 votes vote down vote up
@Override
protected DecryptResult decrypt(DecryptRequest request, EncryptionContext context) {
    return super.decrypt(request, context);
}
 
Example #17
Source File: JCredStash.java    From jcredstash with Apache License 2.0 3 votes vote down vote up
protected ByteBuffer decryptKeyWithKMS(byte[] encryptedKeyBytes, Map<String, String> context) {
    ByteBuffer blob = ByteBuffer.wrap(encryptedKeyBytes);

    DecryptResult decryptResult = awskmsClient.decrypt(new DecryptRequest().withCiphertextBlob(blob).withEncryptionContext(context));

    return decryptResult.getPlaintext();
}
 
Example #18
Source File: KmsOperations.java    From herd with Apache License 2.0 2 votes vote down vote up
/**
 * Executes the decrypt request by calling the AWS KMS service.
 *
 * @param awsKmsClient the client for accessing the AWS KMS service
 * @param decryptRequest the decrypt request
 *
 * @return the response from the decrypt service method, as returned by AWS KMS service
 */
public DecryptResult decrypt(AWSKMSClient awsKmsClient, DecryptRequest decryptRequest);
 
Example #19
Source File: DirectKmsMaterialProvider.java    From aws-dynamodb-encryption-java with Apache License 2.0 2 votes vote down vote up
/**
 * Decrypts ciphertext. The default implementation calls KMS to decrypt the ciphertext using the parameters
 * provided in the {@link DecryptRequest}. Subclass can override the default implementation to provide
 * additional request parameters using attributes within the {@link EncryptionContext}.
 *
 * @param request request parameters to decrypt the given ciphertext.
 * @param context additional useful data to decrypt the ciphertext.
 * @return the decrypted plaintext for the given ciphertext.
 */
protected DecryptResult decrypt(final DecryptRequest request, final EncryptionContext context) {
    return kms.decrypt(request);
}