Skip to content

Instantly share code, notes, and snippets.

@drakestone
Last active December 19, 2018 23:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drakestone/dd074ec54df9b51807852de7162db71d to your computer and use it in GitHub Desktop.
Save drakestone/dd074ec54df9b51807852de7162db71d to your computer and use it in GitHub Desktop.
const crypto = require('crypto');
// Encrypting...
// WARNING: createCipher() is deprecated
const cipher = crypto.createCipher('aes-256-cbc', '0000');
let alphabetUpperCase = `ABCDEFGHIJKLMNOPQRSTUVWXYZ`;
let cipherText = cipher.update(alphabetUpperCase, 'utf8', 'base64');
console.log(`cipher.update('${alphabetUpperCase}') returns `, `'${cipherText}'`);
let alphabetLowerCase = `abcdefghijklmnopqrstuvwxyz`;
cipherText += cipher.update(alphabetLowerCase, 'utf8', 'base64');
console.log(`cipher.update('${alphabetLowerCase}') returns `, `'${cipherText}'`);
cipherText += cipher.final('base64');
console.log("cipher.final() returns", `'${cipherText}'`);
// Decrypting...
const decipher = crypto.createDecipher('aes-256-cbc', '0000');
let updateDecipherText = decipher.update(cipherText, 'base64', 'utf8');
console.log(`decipher.update('${cipherText}) returns `, `'${updateDecipherText}'`);
plainText = decipher.final('utf8');
console.log(`decipher.final() returns`, `'${plainText}'`);
@drakestone
Copy link
Author

drakestone commented Dec 19, 2018

$node cipher
cipher.update('Hello Node') returns ''
cipher.final() returns 'u81KJiz9WjqjwIKywulirw=='
decipher.update('u81KJiz9WjqjwIKywulirw==) returns ''
decipher.final() returns 'Hello Node'

@drakestone
Copy link
Author

drakestone commented Dec 19, 2018

plainText 가 짧으면 cipher.update() 는 아무것도 리턴하지 않지만, 크기가 커지면 암호화의 일부(!)만 리턴한다. 따라서 cipher.final() 의 결과와 합쳐야 한다.

@drakestone
Copy link
Author

cipher.update() 는 cipher.final() 호출 전까지 여러번 호출할 수 있다. 중복 호출된 cipher.update() 의 결과 역시 기억하고 있어야 하고, 최종적으로 cipher.final() 의 결과와 합쳐야 한다. 결론적으로 Cipher 객체는 암호화 결과를 기억하고 있지 않기 때문에 Cipher 를 사용하는 쪽에서 cipher.update() 결과를 잘 관리하고 있어야 하고, cipher.final() 을 통해서 최종 암호데이터가 만들어진다는 점을 유의하자.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment