陳鍾誠

Version 1.0

雜湊法 Hashing

簡易雜湊函數

function hash(str) {
  let hash = 5381
  let i = str.length

  while(i) {
    hash = (hash * 33) ^ str.charCodeAt(--i);
  }

  /* JavaScript does bitwise operations (like XOR, above) on 32-bit signed
   * integers. Since we want the results to be always positive, convert the
   * signed int to an unsigned by doing an unsigned bitshift. */
  return hash >>> 0;
}


console.log('hash(hello)=', hash('hello').toString(16))
console.log('hash(hello!)=', hash('hello!').toString(16))

執行結果

$ node hash
hash(hello)= acfa3a7
hash(hello!)= c21a8b86

SHA256 雜湊函數

SHA256 是 Secure Hash Algorithm 2 的成員, Node.js 內建函式庫的密碼學套件 crypto 支援了很多這類算法。

範例: https://github.com/cccbook/algjs/blob/master/code/11-hashing/digest.js

const crypto = require('crypto');

const secret = 'abcdefg';
const hash = crypto.createHmac('sha256', secret)
                   .update('I love cupcakes')
                   .digest('hex')
console.log(hash)

執行結果

$ node digest
c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e
$ node digest
c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e
$ node digest
c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e

Git 版本管理

其中一版

Bitcoin 比特幣

Libra 天秤幣

加鹽

習題

  1. 請問以下的項目是『雜湊』還是『亂數』