問題描述
我必須在摘要中生成 CryptoJS.HmacSHA256
的字符串表示(字節表示).
I have to generate string representation of CryptoJS.HmacSHA256
in digest (bytes representation).
我需要它,因為我必須復制在 javascript 中生成此類摘要的 python 代碼:
I need it because i have to duplicate python code which generate such digest in javascript:
print hmac.new("secret", "test", hashlib.sha256).digest()
')?kb??>?y+??????:?oΚ??H? '
目標是在 javascript 中復制上述代碼的行為.
The goal is to duplicate behaviour of code above in javascript.
你能建議我怎么做嗎?
推薦答案
如果您需要原始字節,那么 CryptoJS 似乎沒有為它提供代碼.提到這是因為Uint8Array
和朋友缺乏跨瀏覽器兼容性.
If you need raw bytes then CryptoJS does not seem to supply code for it. It is mentioned that this is because of lack of cross browser compatibility for Uint8Array
and friends.
但是,經過搜索,我確實找到了一些由 Vincenzo Ciancia 創建的轉換代碼:
However, after searching, I did find some conversion code created by Vincenzo Ciancia:
CryptoJS.enc.u8array = {
/**
* Converts a word array to a Uint8Array.
*
* @param {WordArray} wordArray The word array.
*
* @return {Uint8Array} The Uint8Array.
*
* @static
*
* @example
*
* var u8arr = CryptoJS.enc.u8array.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var u8 = new Uint8Array(sigBytes);
for (var i = 0; i < sigBytes; i++) {
var byte = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
u8[i]=byte;
}
return u8;
},
/**
* Converts a Uint8Array to a word array.
*
* @param {string} u8Str The Uint8Array.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.u8array.parse(u8arr);
*/
parse: function (u8arr) {
// Shortcut
var len = u8arr.length;
// Convert
var words = [];
for (var i = 0; i < len; i++) {
words[i >>> 2] |= (u8arr[i] & 0xff) << (24 - (i % 4) * 8);
}
return CryptoJS.lib.WordArray.create(words, len);
}
};
當然請注意,字節不會直接轉換為字符;你不能使用文本比較來比較 ') kb > y+ : oΚ H '
由 python 生成.為此,您確實需要一個編碼器,例如十六進制或 base 64.在這種情況下,請查看 來自Artjom 代替.
Note of course that bytes don't translate directly to characters; you cannot use a text compare to compare against ')?kb??>?y+??????:?oΚ??H? '
generated by python. For that you do need an encoder such as hexadecimals or base 64. In that case please look at the answer from Artjom instead.
這篇關于如何在 JS 中獲取 CryptoJS.HmacSHA256 的摘要表示的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!