본문으로 바로가기

[Node.js] 해시값 계산 : Crypto 모듈

category 프로그래밍/JS+Node.js 2019. 6. 12. 16:42

Node.js 내장모듈인 Crypto를 이용해 특정 파일의 해시값을 생성하 코드

const filename = process.argv[2]; // 읽을 파일 이름을 매개 변수로 써준다
const crypto = require('crypto');
const fs = require('fs');

const hash = crypto.createHash('sha256'); // sha-256 알고리즘 사용

const input = fs.createReadStream(filename);
input.on('readable', () => {
  const data = input.read();
  if (data)
    hash.update(data);
  else {
    console.log(`${hash.digest('hex')} ${filename}`);
  }
});

 

SHA-256을 비롯해 MD5, SHA-2 등을 지원한다.

 

 

Node.js Crypto 레퍼런스 : https://nodejs.org/api/crypto.html

 

Crypto | Node.js v12.4.0 Documentation

Crypto# The crypto module provides cryptographic functionality that includes a set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions. Use require('crypto') to access this module. const crypto = require('crypto'); const secr

nodejs.org