Home crypto 모듈
Post
X

crypto 모듈

crypto 모듈로 암호화해보자.


Crypto 모듈

crypto 모듈은 Node.js 에 내장되어 있는 내장 모듈 중 하나로 문자열을 암호화, 복호화, 해싱할 수 있도록 도와주는 모듈입니다.


예제

  • 첫번째 방법 - createHash + update + digest

    동기적으로 salt를 만든 후 비밀번호+salt를 sha512 해시 알고리즘으로 해싱한 후 base64로 인코딩합니다.

    • 주요 메서드

      • createHash(algorithm[, options])
        사용할 해시 알고리즘을 입력합니다. (sha256, sha512, aes-256-cbc)
      • update(data[, inputEncoding])
        변환할 문자열을 입력합니다.
      • digest([encoding])
        인코딩할 알고리즘을 입력합니다. (base64, hex, latin1 등)
      • randomBytes(size[, callback])
        인자로 받은 size 크기 만큼의 랜덤 문자열을 반환합니다.

      callback 함수 생략시 동기적으로 실행됩니다.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    
    import crypto from "crypto";
    
    const password = "testpw01";
    const password2 = "testpw01";
    
    const createHashedPassword = (password) => {
      const salt = crypto.randomBytes(64).toString("base64");
    
      return crypto
        .createHash("sha512") //해시 알고리즘
        .update(password + salt) //변환할 문자열
        .digest("base64"); //인코딩 알고리즘
    
    const hashPassword = createHashedPassword(password);
    
    const verifyPassword = createHashedPassword(password2);
    
    console.log(hashPassword);
    console.log(verifyPassword);
    
    
  • 두번째 방법 - pbkdf2Sync

    crypto에서 제공하는 pbkdf2 메서드가 callback을 사용해 비동기적으로 실행했다면, pbkdf2Sync 메서드를 사용해 동기적으로 해싱할 수 있습니다.

    • 주요 메서드

      • pbkdf2Sync(password, salt, iterations, keylen, digest, callback)
        pbkdf2 방식의 키 스트레칭을 동기적으로 구현합니다.
        • password : 해싱하려는 비밀번호
        • salt : 사용할 Salt
        • iterations : 이터레이션 반복획수 지정
        • keylen : Digest의 길이 지정
        • digest : 암호화 알고리즘
        • callback : 실행될 콜백 함수
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    
    import crypto from "crypto";
    
    const password = "testpw01";
    const password2 = "testpw01";
    
    const createHashedPassword = (password) => {
      const salt = crypto.randomBytes(64).toString("base64");
    
      return crypto
        .pbkdf2Sync(password, salt, 104906, 64, "sha512")
        .toString("base64");
    };
    
    const hashPassword = createHashedPassword(password);
    
    const verifyPassword = createHashedPassword(password2);
    
    console.log(hashPassword);
    console.log(verifyPassword);
    

    단반향 암호화 방벙으로 해시 함수를 이용하는 방법을 알아보았습니다.
    추가로 양방향 암호화 방법도 가볍게 알아보겠습니다.


양방향 암호화 방법

이번 포스트에선 crypto 모듈을 이용해 양방향 암호화 중 대칭형 암호화를 하는 방법을 알아보겠습니다.

  • 암호화에 사용되는 메서드

    • createCipheriv(algorithm, key, iv[, options])
      암호화 알고리즘, key 값, iv 값 을 넣어 줍니다. (iv : 더 강력한 암호화를 위한 초기화 벡터 값)
    • encrypt.update(data[,inputEncoding][,outputEncoding])
      암호화 할 문자열, 문자열의 인코딩, 출력 문자열의 인코딩을 입력합니다.
    • encrypt.final([outputEncoding])
      출력된 문자열의 인코딩을 입력합니다.
  • 복호화에 사용되는 메서드

    • createDecipheriv(algorithm, key, iv[,options])
      복호화 할 때 사용하는 메서드입니다. 암호화에 사용했던 알고리즘, key 값, iv 값을 입력합니다.
    • decode.update(data[,inputEncoding][,outputencoding])
      암호화된 문자열, 암호화된 문자열의 인코딩, 복호화 할 인코딩을 순서대로 입력합니다.
    • decode.final[outputEncoding])
      복호화 결과의 인코딩을 입력합니다.
  • 간단 예제

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    
    const password = "qpmz0192";
    const password2 = "2910zmpq";
    
    const key = "gracefulife"; // 대칭형 키
    
    // 암호화 메서드
    const cipher = (password, key) => {
      const encrypt = crypto.createCipher("des", key); // des알고리즘과 키를 설정
      const encryptResult =
        encrypt.update(password, "utf8", "base64") + // 암호화
        encrypt.final("base64"); // 인코딩
    
      console.log(encryptResult);
      return encryptResult;
    };
    
    // 복호화 메서드
    const decipher = (password, key) => {
      const decode = crypto.createDecipher("des", key);
      const decodeResult =
        decode.update(password, "base64", "utf8") + // 암호화된 문자열, 암호화 했던 인코딩 종류, 복호화 할 인코딩 종류 설정
        decode.final("utf8"); // 복호화 결과의 인코딩
    
      console.log(decodeResult);
    };
    
    const encrypt = cipher(password, key); // dzzmUb9NevZXKjSIZiZbHQ
    const encrypt2 = cipher(password2, key); // vPwzzznk4gezbixB1Fr9wA
    
    decipher(encrypt, key); // qpmz0192
    decipher(encrypt2, key); // 2910zmpq
    

참조

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.