crypto-js 를 활용한 암호화 / 복호화 코드를 정리한다.
> 작성일 : 2023-04-06
<1> 설치
https://www.npmjs.com/package/crypto-js
npm install crypto-js
<2> Key / IV 정의의
const encKey = 'opendocsdocs20230626abcdefghij!@'; // 32Byte
const encIV = 'opendocsdocs2023'; // 16Byte
<3> AES256 암호화 / 복호화 함수
const encAES = (str, key, iv) => {
const cipher = Crypto.AES.encrypt(str, Crypto.enc.Utf8.parse(key), {
iv: Crypto.enc.Utf8.parse(iv),
padding: Crypto.pad.Pkcs7,
mode: Crypto.mode.CBC
});
return cipher.toString();
};
const decAES = (str, key, iv) => {
const cipher = Crypto.AES.decrypt(str, Crypto.enc.Utf8.parse(key), {
iv: Crypto.enc.Utf8.parse(iv),
padding: Crypto.pad.Pkcs7,
mode: Crypto.mode.CBC
});
return cipher.toString(Crypto.enc.Utf8);
};
<4> Base64 인코딩 / 디코딩 함수
const encBase64 = (str) => {
const wordArray = Crypto.enc.Utf8.parse(str);
return Crypto.enc.Base64.stringify(wordArray);
};
const decBase64 = (str) => {
const parsedWordArray = Crypto.enc.Base64.parse(str);
return parsedWordArray.toString(Crypto.enc.Utf8);
};
<5> 암호화 / 복호화 샘플
// Enc
const encValue = encAES('7a4d1829-0683-465b-8c79-0de27739d887', encKey, encIV);
const encResult = encBase64(encValue);
console.log(`endode str : ${encResult}`);
// Dec
const devValue = decBase64(encResult);
const decResult = decAES(devValue, encKey, encIV);
console.log(`decode str : ${decResult}`);
'Source' 카테고리의 다른 글
[Source | MySQL or MariaDB] 데이터베이스 백업설정 및 데이터 이관 (0) | 2025.01.09 |
---|---|
[Source | Java] DB 부하를 줄이기 위한 MyBatis 쿼리캐싱 기능 (0) | 2025.01.03 |
[Source | MySQL or MariaDB] 데이터베이스 생성 및 접속 설정 (0) | 2025.01.03 |