/** * Decrypts the secured CEK via KMS; involves network calls. * * @return the CEK (in plaintext). */ private static SecretKey cekByKMS(byte[] cekSecured, String keyWrapAlgo, EncryptionMaterials materials, ContentCryptoScheme contentCryptoScheme, AWSKMS kms) { DecryptRequest kmsreq = new DecryptRequest() .withEncryptionContext(materials.getMaterialsDescription()) .withCiphertextBlob(ByteBuffer.wrap(cekSecured)); DecryptResult result = kms.decrypt(kmsreq); return new SecretKeySpec(copyAllBytesFrom(result.getPlaintext()), contentCryptoScheme.getKeyGeneratorAlgorithm()); }
@Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getCiphertextBlob() == null) ? 0 : getCiphertextBlob().hashCode()); hashCode = prime * hashCode + ((getEncryptionContext() == null) ? 0 : getEncryptionContext().hashCode()); hashCode = prime * hashCode + ((getGrantTokens() == null) ? 0 : getGrantTokens().hashCode()); return hashCode; }
/** * <p> * A list of grant tokens. * </p> * <p> * For more information, see <a * href="http://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#grant_token">Grant Tokens</a> in the * <i>AWS Key Management Service Developer Guide</i>. * </p> * * @param grantTokens * A list of grant tokens.</p> * <p> * For more information, see <a * href="http://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#grant_token">Grant Tokens</a> in * the <i>AWS Key Management Service Developer Guide</i>. * @return Returns a reference to this object so that method calls can be chained together. */ public DecryptRequest withGrantTokens(java.util.Collection<String> grantTokens) { setGrantTokens(grantTokens); return this; }
@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); } }
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()];
@Override public byte[] decrypt(final byte[] ciphertext, final byte[] associatedData) throws GeneralSecurityException { try { DecryptRequest req = new DecryptRequest().withCiphertextBlob(ByteBuffer.wrap(ciphertext)); if (associatedData != null && associatedData.length != 0) { req = req.addEncryptionContextEntry("associatedData", BinaryUtils.toHex(associatedData)); } DecryptResult result = kmsClient.decrypt(req); if (!result.getKeyId().equals(keyArn)) { throw new GeneralSecurityException("decryption failed: wrong key id"); } return result.getPlaintext().array(); } catch (AmazonServiceException e) { throw new GeneralSecurityException("decryption failed", e); } } }
@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 = kms.decrypt(request); 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); }
if (getGrantTokens() == null) { this.grantTokens = new java.util.ArrayList<String>(grantTokens.length);
@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; } }
@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); } }
@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); }
if (getGrantTokens() == null) { this.grantTokens = new java.util.ArrayList<String>(grantTokens.length);
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DecryptRequest == false) return false; DecryptRequest other = (DecryptRequest) obj; if (other.getCiphertextBlob() == null ^ this.getCiphertextBlob() == null) return false; if (other.getCiphertextBlob() != null && other.getCiphertextBlob().equals(this.getCiphertextBlob()) == false) return false; if (other.getEncryptionContext() == null ^ this.getEncryptionContext() == null) return false; if (other.getEncryptionContext() != null && other.getEncryptionContext().equals(this.getEncryptionContext()) == false) return false; if (other.getGrantTokens() == null ^ this.getGrantTokens() == null) return false; if (other.getGrantTokens() != null && other.getGrantTokens().equals(this.getGrantTokens()) == false) return false; return true; }
/** * Decrypts the secured CEK via KMS; involves network calls. * * @return the CEK (in plaintext). */ private static SecretKey cekByKMS(byte[] cekSecured, String keyWrapAlgo, EncryptionMaterials materials, ContentCryptoScheme contentCryptoScheme, AWSKMSClient kms) { final DecryptRequest kmsreq = new DecryptRequest() .withEncryptionContext(materials.getMaterialsDescription()) .withCiphertextBlob(ByteBuffer.wrap(cekSecured)); final DecryptResult result = kms.decrypt(kmsreq); return new SecretKeySpec(copyAllBytesFrom(result.getPlaintext()), contentCryptoScheme.getKeyGeneratorAlgorithm()); }
@Override public KeyProvider build() { if ( null == key || 0 == key.length ) { return new KeyProviderImpl(null); } else if ( 16 == key.length ) { return new KeyProviderImpl(new SecretKeySpec(key, "AES")); } AWSKMS kms = _amazonWebServiceClients.withEndpoint( new AWSKMSClient( _credProviderFactory.create(credProvider), _clientConfigurations.withProxy(new ClientConfiguration(), proxy)), endpoint); key = kms.decrypt(new DecryptRequest() .withCiphertextBlob(ByteBuffer.wrap(key))) .getPlaintext().array(); if ( 16 != key.length ) { LOG.warn("Expected decrypted key to be exactly 16 bytes, got "+key.length+" bytes. Please "+ "verify the key was not base64 encoded before encrypting with KMS"); return new KeyProviderImpl(null); } return new KeyProviderImpl(new SecretKeySpec(key, "AES")); } }
setGrantTokens(new com.amazonaws.internal.SdkInternalList<String>(grantTokens.length));
if (getGrantTokens() == null) { this.grantTokens = new java.util.ArrayList<String>(grantTokens.length);
/** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getCiphertextBlob() != null) sb.append("CiphertextBlob: ").append(getCiphertextBlob()).append(","); if (getEncryptionContext() != null) sb.append("EncryptionContext: ").append(getEncryptionContext()).append(","); if (getGrantTokens() != null) sb.append("GrantTokens: ").append(getGrantTokens()); sb.append("}"); return sb.toString(); }
/** * Decrypts the secured CEK via KMS; involves network calls. * * @return the CEK (in plaintext). */ private static SecretKey cekByKMS(byte[] cekSecured, String keyWrapAlgo, EncryptionMaterials materials, ContentCryptoScheme contentCryptoScheme, AWSKMSClient kms) { final DecryptRequest kmsreq = new DecryptRequest() .withEncryptionContext(materials.getMaterialsDescription()) .withCiphertextBlob(ByteBuffer.wrap(cekSecured)); final DecryptResult result = kms.decrypt(kmsreq); return new SecretKeySpec(copyAllBytesFrom(result.getPlaintext()), contentCryptoScheme.getKeyGeneratorAlgorithm()); }
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")); } }