how to pass proxy server in @aws-crypto/client-node node js encryption client

777 Views Asked by At

I am using @aws-crypto/client-node npm module to encrypt decrypt file using KMS key. but when I run the following code. I get error 'Missing credentials in config'

const {
  KmsKeyringNode,
  encrypt,
  decrypt
} = require("@aws-crypto/client-node");
const encryptData = async (plainText, context) => {
  try {
    const {
      result
    } = await encrypt(keyring, plainText, {
      encryptionContext: context
    });
    return result;
  } catch (e) {
    console.log(e);
  }
};

encryptData('hello world', {
  stage: "test",
  purpose: "poc",
  origin: "us-east-1"
})
1

There are 1 best solutions below

0
On

I can see couple of issues with this code:

  1. You are trying to import encrypt and decrypt functions directly from the module. This is not how aws-crypto works. You need to use build client to create instance which will hold these methods.
  2. You are using keyring variable, but keyring is never declared? You need to create a keyring using .KmsKeyringNode method.

In order to properly use AWS/KMS to encrypt and decrypt data, take a look into the example bellow. (Make a note that this example does not use a context for its simplicity, nor additional keys which you can add. Also this example assumes that you are using same key for encryption and decryption as well)

const {
  AMAZON_ENCRYPTION_KEY_ARN
} = process.env;

const awsCrypto = require('@aws-crypto/client-node');

const awsEncryptionClient = awsCrypto.buildClient(
  awsCrypto.CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT
);
const keyring = new awsCrypto.KmsKeyringNode({
  generatorKeyId: AMAZON_ENCRYPTION_KEY_ARN
});


const encrypt = async (data) => {
  try {
    const { result } = await awsEncryptionClient.encrypt(keyring, data);
    return result.toString('base64');
  }
  catch(err) {
    console.log('Encryption error: ', err);
    throw err;
  }
};

const decrypt = async (encryptedData) => {
  try {
    const encryptedBuffer = Buffer.from(encryptedData, 'base64');
    const { plaintext } = await awsEncryptionClient.decrypt(keyring, encryptedBuffer);
    return plaintext.toString('utf8');
  }
  catch(err) {
    console.log('Decryption error: ', err);
    throw err;
  }
};

module.exports = {
  encrypt,
  decrypt
};

You can create a file using code above and invoke functions by importing this file somewhere else. You will need to add encryption/decryption key arn. Beside encryption and decryption, encoding and decoding to base64 is added, so final result is suitable for storage (database for example)

For additional code examples take a look here.