crypto-js 암호화/복호화

 

crypto-js를 사용해서 aes256 암호화/복호화를 해보았다.

처음에는 crypto 라이브러리로 테스트 해보았는데 패딩 적용, 제거가 잘 안되어서 crypto-js로 바꿔서 하니 바로 되었다.

 

crypto-js document는 아래 링크를 참고한다.

https://www.npmjs.com/package/crypto-js

 

crypto-js

JavaScript library of crypto standards.. Latest version: 4.1.1, last published: a year ago. Start using crypto-js in your project by running `npm i crypto-js`. There are 7891 other projects in the npm registry using crypto-js.

www.npmjs.com

 

암호화/복호화에서 사용할 블록은 aes256, 블록 암호화모드는 cbc mode와 pkcs7을 사용했다.

 

var CryptoJS = require("crypto-js");

const key = 'cryptojstest1234cryptojstest1234';
const iv = 'thisis*test#6&78';
const text = '나는 내일 놀러갈거야';

let encodeText = encode(text,key,iv)
console.log(encodeText);
console.log(decode(encodeText,key,iv));

// aes 256 암호화 
function encode(data, key, iv) {
    
    const cipher = CryptoJS.AES.encrypt(data, CryptoJS.enc.Utf8.parse(key), {
        iv: CryptoJS.enc.Utf8.parse(iv),
        padding: CryptoJS.pad.Pkcs7, // 패딩 적용
        mode: CryptoJS.mode.CBC // cbc 모드 
    });

    const encodedData = cipher.toString();
    const encodeURL = encodeURIComponent(encodedData);

    return encodeURL; 
}

// aes 256 복호화 
function decode(data, key, iv) {
    // 데이터 url 디코딩 
    data = decodeURIComponent(data);

    // aes 디코딩
    const cipher = CryptoJS.AES.decrypt(data, CryptoJS.enc.Utf8.parse(key), {
        iv: CryptoJS.enc.Utf8.parse(iv), 
        padding: CryptoJS.pad.Pkcs7, //패딩 제거 
        mode: CryptoJS.mode.CBC 
    });

    let decodedData = cipher.toString(CryptoJS.enc.Utf8);    		

    return decodedData;
    
    
}

 

 

+ Recent posts