当前位置:首页 > 操作系统 > MacOs

Java相当于使用SHA1的Fantom HMAC

我在用Java执行以下操作时遇到麻烦.以下是我正在使用的工具的文档中的Fantom代码.

<code>// compute salted hmac
hmac := Buf().print("$username:$userSalt").hmac("SHA-1", password.toBuf).toBase64

// now compute login digest using nonce
digest := "${hmac}:${nonce}".toBuf.toDigest("SHA-1").toBase64

// our example variables
username: "jack"
password: "pass"
userSalt: "6s6Q5Rn0xZP0LPf89bNdv+65EmMUrTsey2fIhim/wKU="
nonce:    "3da210bdb1163d0d41d3c516314cbd6e"
hmac:     "IjJOApgvDoVDk9J6NiyWdktItl0="
digest:   "t/nzXF3n0zzH4JhXtihT8FC1N3s="
</code>

我一直在通过Google搜索各种示例,但没有一个示例会产生应归还文档声明的结果.

拥有Fantom知识的人可以验证文档中的示例是否正确吗?

至于Java方面,这是我最近的尝试

<code>    public static String hmacSha1(String value, String key) {
    try {
        // Get an hmac_sha1 key from the raw key bytes
        byte[] keyBytes = key.getBytes("UTF-8");           
        SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");

        // Get an hmac_sha1 Mac instance and initialize with the signing key
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signingKey);

        // Compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(value.getBytes("UTF-8"));

        // Convert raw bytes to Hex
        byte[] hexBytes = new Hex().encode(rawHmac);

        //  Covert array of Hex bytes to a String
        return new String(hexBytes, "UTF-8");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
</code>

但是,当我使用以下参数调用方法时

<code>jack:6s6Q5Rn0xZP0LPf89bNdv+65EmMUrTsey2fIhim/wKU=
pass
</code>

我懂了

<code>22324e02982f0e854393d27a362c96764b48b65d
</code>

解决方法:

不确定文档来自何处-但它们可能是过时的-或错误的.我实际上将运行Fantom代码以用作您的参考,以确保您正在测试正确的东西;)

您可以看一下sys :: Buf.hmac的Java源代码:MemBuf.java

我还建议分离出3个转换.确保您的原始字节数组在Fantom和Java中都匹配,然后验证摘要匹配,最后是Base64编码.可以更轻松地验证代码中的每个阶段.


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!

相关教程推荐

其他课程推荐