How to get CryptoJS.HmacSHA256 digest view in JS

I need to create a string representation CryptoJS.HmacSHA256in digest (byte representation).

I need this because I have to duplicate the python code that generates such a digest in javascript:

print hmac.new("secret", "test", hashlib.sha256).digest()

') kb  > y+      : oΚ  H    '

The goal is to duplicate the behavior of the code above in javascript.

Could you suggest me how to do this?

+4
source share
2 answers

If you need raw bytes, then CryptoJS doesn't seem to provide code for this. It is mentioned that this is due to the lack of compatibility with the browser for Uint8Arrayfriends.

, 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. , hexadecimals base 64. , , Artjom.

+3

JavaScript. , . Hex- hmac python, CryptoJS.

CryptoJS:

CryptoJS.HmacSHA256("test", "secret").toString(CryptoJS.enc.Hex)

Python:

hmac.new("secret", "test", hashlib.sha256).hexdigest()

.

0329a06b62cd16b33eb6792be8c60b158d89a2ee3a876fce9a881ebb488c0914
+17

All Articles