Node
Node.js 의 Crypto - Cipher, Decipher 사용하기
citron031
2023. 2. 9. 21:59
- Cipher를 통해 암호화하고, Decipher를 통해 복호화한다.
- 암호화와 복호화에 사용되는 key, iv값은 동일해야 한다. 그렇지 않으면 에러가 발생한다.
const { createCipheriv, createDecipheriv } = require('crypto');
const stringToBuffer = (str: string) => {
const buffer = Buffer.from(str, 'utf8');
return buffer;
};
const utilsDecipher = () => {
const algorithm = 'aes-192-cbc';
const key = stringToBuffer('a123b456c789dabc0254f123');
// The IV is usually passed along with the ciphertext.
const iv = Buffer.alloc(16, 0); // Initialization vector.
// CIPHER 암호화
const cipher = createCipheriv(algorithm, key, iv);
let encrypted = cipher.update('test test 123', 'utf8', 'hex'); // uft8 to hex
encrypted += cipher.final('hex');
// DECIPHER 복호화
const decipher = createDecipheriv(algorithm, key, iv);
let decrypted = decipher.update(encrypted, 'hex', 'utf8'); // hex to utf8
decrypted += decipher.final('utf8');
console.log(decrypted); // test test 123
};
module.exports = { utilsDecipher };
- 위의 코드는 공식문서에서 제공하는 코드를 바탕으로 암호화와 복호화 과정을 작성하였다.
- 보면, 생소한 변수명과 단어들이 많은데 의미는 다음과 같다.
- iv: Initialization vector, 데이터 암호화를 위해서 비밀 키와 함께 사용되는 값으로, 해커의 공격을 막기위해 사용된다.
- key: 키의 값은 사용되는 알고리즘의 종류에 따라서 달라지고, 'aes-192-cbc'를 사용하면 192bit(24bytes), 'aes-256-cbc'를 사용하면, 256bit(32bytes) 길이의 key값을 사용해야 한다.
- final 메서드를 사용한 뒤에는 해당 객체를 더 이상 사용할 수 없다. final은 객체당 단 한번만 호출되고 두번째 호출 시 에러가 발생한다.
createCipher와 createDecipher 메서드도 있었지만, Deprecated되었다. 공식문서에서도 그 대신 iv가 추가된 메서드를 사용하도록 권하고 있다.
https://nodejs.org/api/crypto.html
Crypto | Node.js v19.5.0 Documentation
nodejs.org
HTTPS in Nodejs - error:06065064 digital envelope routines evp_decryptfinal_ex bad decrypt
We tried to install our Hapis (Nodejs Version 14) Web service on our customer's server. It ran under HTTP for months, but when we went to enable HTTPS with the appropriate paths to the cert and key...
stackoverflow.com