从Python到JavaScript的翻译:HMAC-SHA256

时间:2016-08-05 10:46:13

标签: javascript python sha256 hmac cryptojs

我想将以下Python代码转换为JavaScript:

signature_string = self.format("{apip_id}{identity_id}{method}{uri}{content_hash}{timestamp}{nonce}") # pyhton unicode string in UTF-8 format
signature_bytes = signature_string.encode('utf-8') # previous string is converted in a python bytes string
apip_key_bytes = base64.b64decode(self.apip_key.encode('utf-8')) # pyhton unicode string is converted in a python bytes string and then in ??
hasher = hmac.new(apip_key_bytes, signature_bytes, hashlib.sha256) # hash is calculated
hash_bytes = hasher.digest() # hash coded in a python bytes string
return base64.b64encode(hash_bytes).decode('utf-8') # the hash in bytes is converted to a base64 string

我尝试使用crypto.JS并开发了以下代码,但我不认为我得到了正确的结果,这是我在上面代码的JavaScript转换

function stringToAsciiByteArray(str) {
    var bytes = [];
    for (var i = 0; i < str.length; ++i) {
        var charCode = str.charCodeAt(i);
        if (charCode > 0xFF) // char > 1 byte since charCodeAt returns the    UTF-16 value
        {
        throw new Error('Character ' + String.fromCharCode(charCode) + '  can\'t be represented by a US-ASCII byte.');
        }
       bytes.push(charCode);
    }
    return bytes;
}

var signature_bytes = stringToAsciiByteArray(signature_string);
var apip_key_bytes = stringToAsciiByteArray(apip_key);

CryptoJS.enc.u8array = {
    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;
    },
    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);
    }
};

var wordArray1 = CryptoJS.enc.u8array.parse(signature_bytes);
var wordArray2 = CryptoJS.enc.u8array.parse(apip_key_bytes);
var hash_bytes = CryptoJS.HmacSHA256(wordArray1, wordArray2);
return window.btoa(hash_bytes);

我在这个程序后得到的哈希码我不认为它是正确的,它不起作用,我做错了吗?

0 个答案:

没有答案