[removed] Equivalent of PHP's hash_hmac() with RAW BINARY output?

前端 未结 5 1610
轮回少年
轮回少年 2021-02-05 13:12

I am connecting to the Amazon Product Advertising API, and to sign my request I need to base64-encode the raw binary output of an HMAC-SHA256 hash.

In t

相关标签:
5条回答
  • 2021-02-05 13:40

    php code

    echo base64_encode(hash_hmac('SHA1', 'shanghai', '0', true).'beijing');
    

    php output

    xvBv49PpaYvXAIfy3iOSDWNQj89iZWlqaW5n
    

    node code

    var crypto = require('crypto');
    var buf1 = crypto.createHmac("sha1", "0").update("shanghai").digest();
    var buf2 = Buffer.from('beijing');
    console.log(Buffer.concat([buf1, buf2]).toString('base64'));    
    

    node output

    xvBv49PpaYvXAIfy3iOSDWNQj89iZWlqaW5n
    
    0 讨论(0)
  • 2021-02-05 13:44

    This is explained in their documentation. Try this:

    var hash = CryptoJS.HmacSHA256("Message", "Secret Passphrase");
    
    var base64 = hash.toString(CryptoJS.enc.Base64);
    

    You need to include http://crypto-js.googlecode.com/svn/tags/3.0.2/build/components/enc-base64-min.js for this. If you didn't include this, CryptoJS.enc.Base64 will be undefined and fallback to the default.

    Working demo: http://jsfiddle.net/ak5Qm/

    0 讨论(0)
  • 2021-02-05 13:45

    PHP:

    base64_encode(hash_hmac('sha256', $value, $key, true));
    

    Nodejs equivalent:

    const crypto = require('crypto');
    let token = crypto.createHmac("sha256", key).update(value).digest().toString('base64');
    
    0 讨论(0)
  • 2021-02-05 13:57

    This worked for me :

    var CryptoJS = require("crypto-js");
    const raw_signature = hmacSHA1(baseString, signingKey);
    const signature = raw_signature.toString(CryptoJS.enc.Base64);
    

    It's giving the exact same result as, in PHP, :

    $rawSignature = hash_hmac("sha1", $baseString, $signingKey, true);
    $signature    = base64_encode($rawSignature);
    
    0 讨论(0)
  • 2021-02-05 13:58

    You can also use this npm package to do the same in Javascript.

    var jsSHA = require('jssha');
    
    hmac_sha1(string, key){
        let shaObj = new jsSHA("SHA-1", "TEXT");
        shaObj.setHMACKey(key, "TEXT");
        shaObj.update(string);
        let hmac = shaObj.getHMAC("B64");
        return hmac;
    };
    
    0 讨论(0)
提交回复
热议问题