길용쓰 2023. 8. 6. 20:28
const crypto = require('crypto');

const data = 'Hello, World!';
const algorithm = 'sha256';

const hash = crypto.createHash(algorithm).update(data).digest('hex');
console.log(hash);

기본적인 해싱 -> 16진수 출력 예제

reateHash()는 단순히 해시값을 리턴하는게 아닌 하나의 해시 객체를 생성하는 메서드이기에

한 객체에 대해 update()를 여러번 사용할 수 있으며,

반대로 digest는 한 객체당 한번밖에 불가능하다.

 

출력은 hex외에 base64, binary, utf8, ascii 등을 사용 가능

해시 함수는 sha-256이 추천되며

md5, sha-1는 보안상의 이유로 비추천.

가장 최신의 알고리즘은 blake2b라고 한다.

const crypto = require('crypto');
const fs = require('fs');

const fileBuffer = fs.readFileSync('myfile.js');
const hashSum = crypto.createHash('sha256');
hashSum.update(fileBuffer);

const hex = hashSum.digest('hex');

console.log(hex);

readFileSync로 파일을 읽어 해싱하는 예제

 

 

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}`);
  }
});

createReadStream으로 파일을 읽어 해싱하는 예제

 

function exploreAllFiles(path){
    fs.readdirSync(path, {withFileTypes:true}).forEach(p=>{
        const fileName = p.name;
        const filePath = path+"/"+fileName
        if(p.isDirectory()){ //디렉토리인 경우
            exploreAllFiles(filePath);
        }
        else{ //파일인 경우
            const fileBuffer = fs.readFileSync(path+"/"+fileName);
            hash.update(fileBuffer);
        }
    })
    return hash;
}

디렉토리를 순회하며 모든 파일에 대한 해시값을 얻는 예제