Aravind Piratla
Aravind Piratla

Reputation: 37

Hoe to add proxy to @aws-crypto/client-node

We are running our containers in an environment that requires a proxy to communicate with AWS services. I was able to set the proxy using AWS.config.update({ httpOptions: { agent } }), but it does not seem to apply when using the AWS Encryption SDK for encryption and decryption.

Here’s what I tried:

const {  buildClient,
    KmsKeyringNode,
    CommitmentPolicy,
    getClient, KMS} = require('@aws-crypto/client-node');
const { encrypt, decrypt } = buildClient(
    CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT
)
const AWS = require('aws-sdk');

AWS.config.update({
    region: 'me-central-1',
});

// Define the KMS key ARN (or Key ID)
const keyArn = 'arn:aws:kms:me-central-1:************:alias/GNS-ENC';
const keyring = new KmsKeyringNode({
  generatorKeyId: keyArn,  // Use the Key ARN or Key ID to initialize the Keyring
  keyIds:['arn:aws:kms:me-central-1:************:key/********************'],
  clientProvider:getClient(KMS,{
    credentials:{
      accessKeyId: 'AKIA****************',
      secretAccessKey:'********************************'
    }
  })
});
// Function to encrypt data
async function encryptData(plaintext) {
  try {
    // Encrypt the plaintext using the keyring
    const { result } = await encrypt(keyring, plaintext)

    // Convert the ciphertext to base64 and log
    console.log('Encrypted data (base64):', Buffer.from(result, 'utf-8').toString('base64'));
    return result; // Return the ciphertext to use for decryption
  } catch (err) {
    console.error('Encryption failed:', err);
  }
}

// Function to decrypt data
async function decryptData(encryptedData) {
  try {
    // Decrypt the ciphertext
    const ciphertext = Buffer.from(encryptedData, 'base64');  
    const { plaintext } = await decrypt(keyring, ciphertext);

    // Convert the decrypted data back to string and log
    const decryptedData = plaintext.toString('utf-8');
    console.log('Decrypted data:', decryptedData);
    return decryptedData;
  } catch (err) {
    console.error('Decryption failed:', err);
  }
}

// Main function to run the encryption and decryption flow
async function testEncryptionDecryption() {
  const plaintext = 'Hello, AWS Encryption SDK with KMSKeyringNode!';

  // Step 1: Encrypt the data
  const encryptedData = await encryptData(plaintext);

  // Step 2: Decrypt the data
  if (encryptedData) {
    await decryptData(encryptedData);
  }
}

// Run the test
testEncryptionDecryption();

Upvotes: 0

Views: 21

Answers (0)

Related Questions