Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

Node.jsでSHA1ハッシュを計算する

More than 3 years have passed since last update.

プログラム内でとある文字列のSHA1ハッシュを計算して、その16進数値を求めたかった。
Node.jsの標準モジュールcryptoを使うと簡単に実装できた。

'use strict'

const crypto = require('crypto');
const shasum = crypto.createHash('sha1');
shasum.update('my data'); // ここの引数にハッシュを計算したい文字列を渡す
let hash = shasum.digest('hex');

console.log(hash); // -> fee95d29ae5926af3375e2eb3a688471de0a2c3e

ファイルの内容から計算する時はfsモジュールでデータを丸々読み込むのが簡単。

'use strict'

const crypto = require('crypto');
const fs = require('fs');
const shasum = crypto.createHash('sha1');

fs.readFile('target/file/path', (err, data) => {
  shasum.update(data);
  console.log(shasum.digest('hex'));
});

一度に全てを読み込みきれない大きなファイルの場合は、Streamを使って読み込む。

'use strict'

const crypto = require('crypto');
const fs = require('fs');
const shasum = crypto.createHash('sha1');

let stream = fs.createReadStream('target/file/path');
stream.on('data', chunk => shasum.update(chunk));
stream.on('close', _ => console.log(shasum.digest('hex')));

ラムダ式がよくわからない方はこちら

'use strict'

const crypto = require('crypto');
const fs = require('fs');
const shasum = crypto.createHash('sha1');

let stream = fs.createReadStream('target/file/path');

stream.on('data', function(chunk) {
  shasum.update(chunk);
});

stream.on('close', function() {
  console.log(shasum.digest('hex'));
});

関数にしてみた

'use strict'

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

function calculateSHA1(filePath, resultFormat) {
  return new Promise((resolve, reject) => {

    const shasum = crypto.createHash('sha1');
    let stream = fs.createReadStream(filePath);
    stream.on('data', chunk => shasum.update(chunk));
    stream.on('close', _ => resolve(shasum.digest(resultFormat)));

  });
}

// 使い方
calculateSHA1('target/file/path', 'hex')
  .then(result => console.log(result));
niusounds
REALITYで活動中のスマホアプリエンジニアです。シンフォニックメタルとフォークメタルが好き。 VSCodeおじさん。
https://niusounds.github.io
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away