Blog>
Snippets

Secure Handling of Sensitive Data

Demonstrate encrypting and decrypting sensitive configuration information such as API keys using TanStack Config, highlighting best practices for maintaining data confidentiality.
require('dotenv').config();
const crypto = require('crypto');
const algorithm = 'aes-256-cbc';
const secretKey = process.env.SECRET_KEY;
const iv = crypto.randomBytes(16);
Initial setup that includes importing required modules and configuring the encryption algorithm. 'dotenv' is used for loading environmental variables where the secret key is stored securely. 'crypto' provides cryptographic functionality including the unique initialization vector (iv).
function encrypt(text) {
    let cipher = crypto.createCipheriv(algorithm, secretKey, iv);
    let encrypted = cipher.update(text, 'utf8', 'hex');
    encrypted += cipher.final('hex');
    return { iv: iv.toString('hex'), encryptedData: encrypted };
}
This function encrypts the sensitive data using AES-256-CBC with the secret key and iv. It returns an object containing the iv and encrypted data in hex format.
function decrypt(encrypted) {
    let iv = Buffer.from(encrypted.iv, 'hex');
    let decipher = crypto.createDecipheriv(algorithm, secretKey, iv);
    let decrypted = decipher.update(encrypted.encryptedData, 'hex', 'utf8');
    decrypted += decipher.final('utf8');
    return decrypted;
}
This function decrypts the previously encrypted data, reversing the process by utilizing the same secret key and iv. It converts the encrypted data and iv back to their original unencrypted form.
const sensitiveData = 'your_api_key_here';
const encryptedData = encrypt(sensitiveData);
console.log('Encrypted:', encryptedData);

const decryptedData = decrypt(encryptedData);
console.log('Decrypted:', decryptedData);
Usage example: Encrypting an `API key` and then decrypting it to demonstrate the process. This showcases how to use the encrypt and decrypt functions.