kdanedesigns / kdpcapstone-AD440-2023-EasilySendDataSecurely

Winter 2023 AD440 Cloud Practicum Team Project
GNU General Public License v3.0
2 stars 0 forks source link

Write a lambda function for encrypting data #57

Closed kdpcapstone closed 1 year ago

zenwattage commented 1 year ago

here is a working encryption lambda function:

const crypto = require('crypto');

exports.handler = async (event) => { console.log(event); const plainText = event.plainText; let key = event.key;

const minKeyLength = 32; if (key.length < minKeyLength) { key = key.padEnd(minKeyLength, '0'); }

const encrypt = (plainText, key) => { const iv = crypto.randomBytes(16); const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv); let encrypted = cipher.update(plainText); encrypted = Buffer.concat([encrypted, cipher.final()]); return ${iv.toString('hex')}:${encrypted.toString('hex')}; };

const encrypted = encrypt(plainText, key); return { event, encrypted }; };

kdpcapstone commented 1 year ago

final code:

const crypto = require('crypto');

exports.handler = async (event) => { console.log(event); const plainText = event.plainText; let key = event.key;

const minKeyLength = 32; if (key.length < minKeyLength) { key = key.padEnd(minKeyLength, '0'); }

const encrypt = (plainText, key) => { // add salt const iv = crypto.randomBytes(16); // create the key with the aes encryption algorithym, the key provided, and the salt const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv); let encrypted = cipher.update(plainText); encrypted = Buffer.concat([encrypted, cipher.final()]); return ${iv.toString('hex')}:${encrypted.toString('hex')}; };

const encrypted = encrypt(plainText, key); return { event, encrypted }; };