Translation from Python to [removed] HMAC-SHA256

2019-07-18 08:27发布

问题:

I'd like to convert the following piece of Python code to 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

I tried to use crypto.JS and developed following code but I don't think I get the correct result, This is my conversion in JavaScript of the above code

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);

The hash code I get after this procedure I don't think it's correct, it doesn't work, am I doing something wrong?