0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Node.jsでハッシュ値を生成する

Posted at

Node.js でSHA1, SHA256のハッシュ値を作成するには、Web Cryptography APIのdigest メソッドを使用します。

もう一つの方法は、Node.js の Crypto モジュールのcreateHash メソッド を使用します。

サンプルプログラム(Web Cryptography API版)

SHA1, SHA256アルゴリズムでハッシュ値を生成し、出力するプログラムです。

//Web Crypto APIを使用した場合
const { subtle } = require('crypto').webcrypto;

subtle.digest('SHA-1', 'Hello World').then(function(result) {

    const hex = Buffer.from(new Uint8Array(result)).toString("hex");
    console.log('SHA1');
    console.log(hex);
});

subtle.digest('SHA-256', 'Hello World').then(function(result) {

    const hex = Buffer.from(new Uint8Array(result)).toString("hex");
    console.log('SHA256');
    console.log(hex);
});

サンプルプログラム(Node.jsのCryptoライブラリ)

//node.js の Cryptoライブラリを使用
const {
    createHash,
} = require('node:crypto');
  
const hash1 = createHash('sha1');  
hash1.update('Hello World');

console.log('SHA1');
console.log(hash1.digest('hex'));

const hash2 = createHash('sha256');
hash2.update('Hello World');

console.log('SHA256');
console.log(hash2.digest('hex'));
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?