import { KMSClient, EncryptCommand, DecryptCommand, EncryptionAlgorithmSpec, } from '@aws-sdk/client-kms' /** * Represents a Crypto class that provides encryption and decryption functionality using AWS KMS. */ export default class Crypto { /** * The KMSClient instance used for making requests to the Key Management Service (KMS). */ private readonly client: KMSClient /** * The AWS region of the object. This property is readonly and cannot be modified once set. */ private readonly region: string /** * The unique identifier for the KMS. * @readonly * @type {string} */ private readonly keyId: string /** * Specifies the encryption algorithm used for encryption. */ private readonly encryptionAlgorithm: EncryptionAlgorithmSpec /** * Constructs a new instance of a KeyManager with the provided region, keyId, and optional encryption algorithm. * @param {string} region - The region where the key is stored. * @param {string} keyId - The ID of the key. * @param {EncryptionAlgorithmSpec} [optEncryptionAlgorithm='RSAES_OAEP_SHA_256'] - The encryption algorithm to use (default is RSAES_OAEP_SHA_256). * @returns None */ constructor(region: string, keyId: string, optEncryptionAlgorithm?: EncryptionAlgorithmSpec) { this.region = region this.keyId = keyId this.encryptionAlgorithm = optEncryptionAlgorithm || 'RSAES_OAEP_SHA_256' this.client = new KMSClient({ region: this.region }) } /** * Encrypts the given data using RSAES_OAEP_SHA_256 encryption algorithm. * @param {string | any} data - The data to be encrypted. * @returns {Promise} - A promise that resolves to the encrypted data as a hexadecimal string. */ public async encryptData(data: string | any): Promise { try { const resp = await this.client.send( new EncryptCommand({ KeyId: this.keyId, EncryptionAlgorithm: this.encryptionAlgorithm, Plaintext: new TextEncoder().encode( typeof data === 'string' ? data : JSON.stringify(data) ), }) ) return Buffer.from(resp.CiphertextBlob as any, 'utf8').toString('hex') } catch (e) { console.error('Encryption failure', e) return null } } /** * Decrypts the given data using the RSAES_OAEP_SHA_256 encryption algorithm. * @param {string} data - The encrypted data to decrypt. * @returns {Promise} - A promise that resolves to the decrypted plaintext string. * If decryption fails, null is returned. */ public async decryptData(data: string): Promise { try { const resp = await this.client.send( new DecryptCommand({ KeyId: this.keyId, CiphertextBlob: Uint8Array.from(Buffer.from(data, 'hex')), EncryptionAlgorithm: this.encryptionAlgorithm, }) ) return new TextDecoder().decode(resp.Plaintext) } catch (e) { console.error('Decryption failure', e) return null } } }