MrsBookik
MrsBookik

Reputation: 1153

How to decrypt data using AWS-KMS and fix the error "unencryptedDataKey has not been set"?

I am using AWS KMS, following their official Tutorial, to encrypt data using a Master Key, which I have setup accordingly in AWS Management Console.

Encryption seems to work fine.

But when I want to decrypt the encrypted cypher-text, I get the following error:

unencryptedDataKey has not been set

This is my code:

const generatorKeyId = 'arn:aws:kms:eu-central-1:51426*****:alias/my-key';
const keyIds = [];

const keyring = new KmsKeyringNode({ generatorKeyId, keyIds });

console.log(keyring);

This shows me:

KmsKeyringNode {
  clientProvider: [Function (anonymous)],
  keyIds: [],
  generatorKeyId: 'arn:aws:kms:eu-central-1:51426*****:alias/my-key',
  grantTokens: undefined,
  isDiscovery: false,
  discoveryFilter: undefined
}

Continue code:

const context = {
  stage: 'demo',
  purpose: 'simple demonstration app',
  origin: 'eu-central-1',
};

/* Create a string to encrypt */
const cleartext = 'my-cypher-teststring';

const { encrypt, decrypt } = buildClient(CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT);

const { result } = await encrypt(keyring, cleartext, { encryptionContext: context });
console.log("RESULT", result)

Console looks like this then:

RESULT <Buffer 02 05 78 02 4b 48 c9 96 75 f8 08 5e 33 d0 91 18 67 51 31 4c 7a 9d a9 ac bd df e

const { plaintext, messageHeader } = await decrypt(keyring, result);
console.log("Plaintext", plaintext)
console.log("MessageHeader", messageHeader)

Decrypt will throw the following exception:

Error  AM [ExceptionsHandler] unencryptedDataKey has not been set - {
    stack: [
      'Error: unencryptedDataKey has not been set\n' +
        '    at needs (/Users/xxxxx/xxxx/node_modules/@aws-crypto/material-management/src/needs.ts:21:11)\n' +
        '    at NodeDecryptionMaterial.getUnencryptedDataKey (/Users/xxxx/xxxx/node_modules/@aws-crypto/material-management/src/cryptographic_material.ts:417:10)\n' +
        '    at NodeDefaultCryptographicMaterialsManager.decryptMaterials (/Users/xxxxxx/yyyyyy/node_modules/@aws-crypto/material-management-node/src/node_cryptographic_materials_manager.ts:109:20)\n' +
        '    at processTicksAndRejections (node:internal/process/task_queues:96:5)'
    ]
  }

What do I miss here?

Upvotes: 3

Views: 3929

Answers (1)

sareno
sareno

Reputation: 696

I had the same issue. Turns out I used the wrong values for generatorKeyId and keyIds, see below:

Wrong:

const generatorKeyId = 'alias/MyKms'
const keyIds = ['arn:aws:kms:us-west-2:************:alias/MyKms']

const keyring = new KmsKeyringNode({ generatorKeyId, keyIds })

Correct (see example from official doc):

const generatorKeyId = 'arn:aws:kms:us-west-2:************:alias/MyKms'
const keyIds = ['arn:aws:kms:us-west-2:************:key/1234abcd-12ab-34cd-56ef-1234567890ab']

const keyring = new KmsKeyringNode({ generatorKeyId, keyIds })

Upvotes: 2

Related Questions