암호화 알고리즘 종류
type CipherCCMTypes = 'aes-128-ccm' | 'aes-192-ccm' | 'aes-256-ccm' | 'chacha20-poly1305';
type CipherGCMTypes = 'aes-128-gcm' | 'aes-192-gcm' | 'aes-256-gcm';
type CipherOCBTypes = 'aes-128-ocb' | 'aes-192-ocb' | 'aes-256-ocb';
client-side
Encypt
const CryptoJS = require('crypto-js');
const jsonData = {
name: 'Alice',
age: 30
};
// Generate a random key, IV, and salt
const key = CryptoJS.lib.WordArray.random(256/8);
const iv = CryptoJS.lib.WordArray.random(128/8);
const salt = CryptoJS.lib.WordArray.random(128/8);
// Encrypt the JSON data using AES-256-CBC
const encrypted = CryptoJS.AES.encrypt(
JSON.stringify(jsonData),
key,
{ iv: iv, salt: salt }
);
// Send the encrypted data and metadata to the server
const dataToSend = {
data: encrypted.toString(),
key: key.toString(),
iv: iv.toString(),
salt: salt.toString()
};
server-side
Decrypt
const crypto = require('crypto');
async function decryptData(encryptedData, key, iv, salt) {
try {
// Decrypt the data using AES-256-CBC
const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
// decipher.setAuthTag(salt); // Set the authentication tag
let decryptedData = '';
decryptedData += decipher.update(encryptedData, 'base64', 'utf8');
decryptedData += decipher.final('utf8');
const jsonData = JSON.parse(decryptedData);
console.log(jsonData); // Output: { name: 'Alice', age: 30 }
} catch (error) {
console.error(error);
}
}
Encrypt
async function encryptData(plaintext, key, iv, salt) {
try {
// Derive a key using PBKDF2 with the salt and 100000 iterations
const derivedKey = await crypto.pbkdf2Sync(key, salt, 100000, 32, 'sha256');
// Encrypt the data using AES-256-CBC
const cipher = crypto.createCipheriv('aes-256-cbc', derivedKey, iv);
let encryptedData = '';
encryptedData += cipher.update(plaintext, 'utf8', 'base64');
encryptedData += cipher.final('base64');
console.log('Encrypted data:', encryptedData);
// Send the encrypted data and metadata to the client
const metadata = { key: key.toString('hex'), iv: iv.toString('hex'), salt: salt.toString('hex') };
console.log('Metadata:', metadata);
} catch (error) {
console.error(error);
}
}