학습 - 비밀번호 암호화 : crypto

YoonSuk Choi·2025년 1월 7일

7주차

목록 보기
8/10

암호화 crypto

  • 암호화는 데이터를 보호하기 위해 특정 알고리즘을 사용하여 원본 정보를 변환하는 과정이다.
  • 이를 통해 데이터는 외부 접근으로부터 안전하게 보호되며, 허가된 사용자 만이 정보를 복호화할 수 있다.

crypto란?

  • crypto는 Node.js에서 제공하는 내장 모듈 : 암호화와 복호화 기능을 제공
  • 주요 기능 : 해싱, 단방향 암호화, 양방향 암호화

crypto 구성

  1. 단방향 암호화

    • createHash: 해시 함수를 사용하여 암호화 (복호화 불가)
    • pbkdf2Sync: 솔트와 반복을 통해 강력한 해시 암호화 구현
  2. 양방향 암호화

    • createCipheriv: 암호화 기능 제공
    • createDecipheriv: 복호화 기능 제공

사용한 코드

단방향 암호화 코드 예제

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 모듈을 활용한 단방향 및 양방향 암호화 학습

핵심 요약

  • 단방향 암호화는 비밀번호 저장과 같은 데이터 검증에 유용하다. (해시 생성 및 검증)
  • 양방향 암호화는 데이터를 전송하거나 저장할 때 암호화 및 복호화가 필요할 때 유용하다.
profile
Name : 최윤석(YoonSuk Choi)

0개의 댓글