SHA256

為單向加密HASH,不可逆

範例:

var crypto = require('crypto');
let msg = 'test';
var hash = crypto.createHash('sha256').update(msg).digest('base64');
console.log(hash);

原理:

#第一步:

把msg轉為二進位的數字msgBit,之後後面先放一個數字1然後pad補k個0 直到msgBit.length + 1 + k % 512 = 448

然後最後面再加上64bits的數字,內容為msg的長度(以二進位表示) ex:abc之ASCII二進位長度為24,

所以轉為64bit二進位顯示為0....11000

(以ABC為例子)

#第二步:

寫出八個initial hash value(此為固定值)

附註:1<<32在python和js行為會不同,可參考https://stackoverflow.com/questions/45024682/different-behavior-for-1-32-compare-javascript-to-python

#第三步

64個固定k值

#第四步:

使用sha256定義的六個hash function

其中符號定義如下

寫成程式為:

#完整範例

也可用Node.js的crypto模組

Reference:

https://github.com/peterolson/BigInteger.js(大數轉換無法用在parseInt,toString())

http://www.danvk.org/hex2dec.html

https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER

https://stackoverflow.com/questions/18626844/convert-a-large-integer-to-a-hex-string-in-javascript (其解答dec2hex在數字更大時還是無法解決問題,但可做為參考)

Python內建BigInteger所以如用Python則不會有問題

Last updated

Was this helpful?