Yuvraj Jagga
Yuvraj Jagga

Reputation: 83

Decrypt cypherTextBlob using AWS KMS programmatically in Java ? InvalidCiphertextException

I am a bit new to cryptography and never used AWS KMS to encrypt data before. I am using AWS SDK for Java for KMS. But while trying to encrypt and decrypt using AWS KMS API Operations, I am facing the exception InvalidCiphertextException

<dependency>
      <groupId>software.amazon.awssdk</groupId>
      <artifactId>kms</artifactId>
      <version>2.15.19</version>
  </dependency>

Encrypt part

String encrypt(String plainText){
EncryptRequest encryptRequest = new EncryptRequest().withKeyId(keyId).withPlaintext(plainText);

//calling encrypt function here 
EncryptResult response = kmsClient.encrypt(encryptRequest);
cipherText =  new String(response.getCiphertextBlob().array());
//calling decrypt function here
return decrypt(cipherText);
}

Decrypt part in decrypt method

public String decrypt(String cipherText){
ByteBuffer cyphertextBlob = ByteBuffer.wrap(cipherText.getBytes());

//Point 1: Exception is thrown at this point while calling decrypt operation API.

DecryptRequest request = new DecryptRequest().withKeyId(keyId).withCiphertextBlob(cyphertextBlob);
}

The problem is I get the following error at the point of making the api call (Point 1)

com.amazonaws.services.kms.model.InvalidCiphertextException: null (Service: AWSKMS; Status Code: 400; Error Code: InvalidCiphertextException; Request ID: 45720b33-3637-490a-8c6a-d7491ccadf94; Proxy: null)

InvalidCiphertextException. While going through AWS documents, here are the points I understood,

Do I need to do any other step to manipulate/transform the cipher text before using decryption request ?

can anyone help with this please ?

Upvotes: 1

Views: 2997

Answers (2)

Pritesh
Pritesh

Reputation: 1

I am also faced same problem.Then i realised i am converting to String directly. But we can Store as ByteBuffer. so i did it and retrived it. the problem is resolved.

  EncryptResponse response = kmsClient.encrypt(encryptRequest);

  CreateSecretRequest createSecretRequest = CreateSecretRequest.builder()
      .name("dev/encrypte******")
      .kmsKeyId(config.getArn())
      .secretBinary(response.ciphertextBlob())
      .build();

  -- --Decryption-- --

  DecryptResponse decryptResponse = kmsClient.decrypt(decryptRequest);
  String decrypted = new String(decryptResponse.plaintext().asByteArray());

Upvotes: -1

Yuvraj Jagga
Yuvraj Jagga

Reputation: 83

Just to update here in case anyone got stock at this problem.

While debugging found out that, the capacity and the limit of ByteBuffer object obtained using the get methods of the KMS response was different than the default capacity and limit while creating one from the cipherText in the decrypt method. So this caused the exception.

Upvotes: 1

Related Questions