使用URI和密钥生成HMAC SHA算法

时间:2018-06-22 10:21:06

标签: javascript node.js hmac sha

我编写了一个生成HMAC SHA哈希代码的Java程序,但是由于某种原因,我不得不在NodeJs / JavaScript中编写相同的代码。我尝试了四处搜寻,但一无所获。在此Java代码中,我将URI和Key作为参数传递,以生成哈希码,其中URI包含时间戳。 Java代码为:

    public static String calcMAC(String data, byte[] key) throws Exception {
    String result=null;
    SecretKeySpec signKey = new SecretKeySpec(key, SecurityConstants.HMAC_SHA1_ALGORITHM);
    Mac mac = Mac.getInstance(SecurityConstants.HMAC_SHA1_ALGORITHM);
    mac.init(signKey);
    byte[] rawHmac;
    try {
        rawHmac = mac.doFinal(data.getBytes("US-ASCII"));
        result = Base64.encodeBase64String(rawHmac);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result.trim();
}

public static void main(String args[]) {
    String timestamp = args[0];
    String key = "d134hjeefcgkahvg32ajkdbaff84ff180";
    String out = null;
    try {
        out = calcMAC("/req?app_id=47ca34" + timestamp + "=2018-05-22T12:02:15Z", 
                key.getBytes());
        System.out.println(URLEncoder.encode(out, "UTF-8"));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

在NodeJs / JavaScript中是否可以实现相同的目标?

注意::我必须从邮递员的预先请求脚本中调用此脚本。

1 个答案:

答案 0 :(得分:2)

加密模块应为您执行此操作,您可以将“ data”变量替换为您要散列的任何内容:

const crypto = require('crypto');

const data = 'The fault dear Brutus lies not in our stars';
const key = Buffer.from('d134hjeefcgkahvg32ajkdbaff84ff180', 'utf8');

const hash = crypto.createHmac('sha1', key).update(data).digest('base64');
const uriEncodedHash = encodeURIComponent(hash);
console.log('Hash: ' + uriEncodedHash);

将数据同时用Java和Node.js进行哈希处理可得到以下结果(URI编码):

TJJ3xj93m8bfVpGoucluMQqkB0o%3D

相同的Java代码是:

public static void main(String args[]) {
    String data = "The fault dear Brutus lies not in our stars";
    String key = "d134hjeefcgkahvg32ajkdbaff84ff180";
    String out = null;
    try {
        out = calcMAC(data, key.getBytes());
        System.out.println(URLEncoder.encode(out, "UTF-8"));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

同样,我们可以将任何东西放入所需的“数据”中。