반응형

암호화 알고리즘 종류

    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);
    }
}
반응형

'JAVASCRIPT' 카테고리의 다른 글

(js) next js 에러  (0) 2023.05.03
(javascript) node js 파일 업로드  (0) 2023.02.21
(js) 파일 업로드 , 다운로드  (0) 2023.01.10
(javascript)상속  (0) 2022.06.27
(javascript)이스케이프 문자열 치환  (0) 2022.05.12

+ Recent posts