허가된 사용자 만이 정보를 복호화할 수 있다.crypto는 Node.js에서 제공하는 내장 모듈 : 암호화와 복호화 기능을 제공단방향 암호화
양방향 암호화
const crypto = require("crypto");
// createHash 예제
const createHashPW = (pw) => {
return crypto.createHash("sha512").update(pw).digest("base64");
};
console.log(createHashPW("1234"));
// pbkdf2Sync 예제
function saltAndHashPw(pw) {
const salt = crypto.randomBytes(16).toString("base64");
const iterations = 100;
const keylen = 64;
const algorithm = "sha512";
const hash = crypto
.pbkdf2Sync(pw, salt, iterations, keylen, algorithm)
.toString("base64");
return { salt, hash };
}
console.log(saltAndHashPw("1234"));
// 비밀번호 검증
function checkPw(inputPw, savedSalt, savedHash) {
const iterations = 100;
const keylen = 64;
const algorithm = "sha512";
const hash = crypto
.pbkdf2Sync(inputPw, savedSalt, iterations, keylen, algorithm)
.toString("base64");
return hash === savedHash;
}
const data = saltAndHashPw("qwer1234");
console.log(checkPw("qwer1234", data.salt, data.hash));
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);
const algorithm = "aes-256-cbc";
const originalMessage = "hello, world!";
// 암호화
function encrypt(text) {
const cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = cipher.update(text, "utf8", "base64");
encrypted += cipher.final("base64");
return encrypted;
}
// 복호화
function decrypt(encryptedText) {
const decipher = crypto.createDecipheriv(algorithm, key, iv);
let decrypted = decipher.update(encryptedText, "base64", "utf8");
decrypted += decipher.final("utf8");
return decrypted;
}
const encryptedMessage = encrypt(originalMessage);
console.log("암호화된 문장", encryptedMessage);
const decryptedMessage = decrypt(encryptedMessage);
console.log("복호화된 문장", decryptedMessage);
crypto 모듈을 활용한 단방향 및 양방향 암호화 학습