![](/img/trans.png)
[英]Convert md5 hash code of javascript to Python return different result
[英]Encoding Hash in javascript gives different result compared to python
我正在嘗試將 javascript 程序轉換為 python,但我得到不同的結果,在創建哈希后它們是相同的,但在對結果進行編碼后,它們與 python 程序相差甚遠,因為它比 javascript 版本長得多。
Javascript 結果: 'DqnyGCG5qW5DPceKe1p7fFyFxqdXrqZhQiN2Ukp-2h0'
Python 結果: 'NGQ4MWNiYWY3NzgyZmIyZjE3YWEzNWQyNGE1Mjg4M2M2ZmI1MmQxNGE4MDFmNDMxM2FkZWRlOTE1NjVhZGU0YQ'
Javascript
var hash = CryptoJS.HmacSHA256(token.join("."), secret);
// Same hash on both
var base64Hash = CryptoJS.enc.Base64.stringify(hash);
document.write(urlConvertBase64(base64Hash));
// Results are different now
function urlConvertBase64(input) {
var output = input.replace(/=+$/, '');
output = output.replace(/\+/g, '-');
output = output.replace(/\//g, '_');
return output;
}
Python
signatureHash = hmac.new(secret.encode(), tokenHB, hashlib.sha256).hexdigest()
// Same hash on both
signature = base64.urlsafe_b64encode(signatureHash.encode())
signature = signature.rstrip('='.encode())
// Results are different now
print(signature)
您在 Node.js 和 Python 之間編碼了兩種不同的東西。 在 Node.js 中,您直接使用原始(字節值)散列,而在 Python 中,您使用相同散列的十六進制編碼值。 根據您想要的輸出,您需要在 Node.js 中對十六進制輸出進行字符串化,或者在 Python 中對原始哈希進行 base64 編碼。
將復制兩個版本的輸出的 Node.js 代碼(示例中省略了您的urlConvertBase64
實現,但已使用):
const CryptoJS = require('crypto-js');
var token = 'the token';
var data_to_hash = 'thesecret\x00\x00\x02';
var hashed = CryptoJS.HmacSHA256(data_to_hash, token);
var hexdigest = hashed.toString(CryptoJS.enc.Hex);
var raw_base64 = urlConvertBase64(CryptoJS.enc.Base64.stringify(hashed));
var hex_base64 = urlConvertBase64(Buffer.from(hexdigest).toString('base64'));
console.log(`raw + base64: ${raw_base64}`);
console.log(`hex + base64: ${hex_base64}`);
將復制上述內容的 Python 代碼:
import hashlib
import hmac
from base64 import urlsafe_b64encode
token = b'the token'
data_to_hash = b'thesecret\x00\x00\x02'
hashed = hmac.new(token, data_to_hash, hashlib.sha256)
hexdigest = hashed.hexdigest().encode()
raw_base64 = urlsafe_b64encode(hashed.digest()).decode().rstrip('=')
hex_base64 = urlsafe_b64encode(hexdigest).decode().rstrip('=')
print(f'raw + base64: {raw_base64}')
print(f'hex + base64: {hex_base64}')
兩個版本都產生以下輸出:
raw + base64: R1oLspOvlQ6X_rzaudD8dk8Kqo-nu9pgij-f_-4tnxo hex + base64: NDc1YTBiYjI5M2FmOTUwZTk3ZmViY2RhYjlkMGZjNzY0ZjBhYWE4ZmE3YmJkYTYwOGEzZjlmZmZlZTJkOWYxYQ
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.