带有密钥的Java HmacSHA256 [英] Java HmacSHA256 with key

查看:1408
本文介绍了带有密钥的Java HmacSHA256的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已尝试使用stackoverflow中的几个链接来获取HmacSHA256的密钥以使用java,但我总是得到

i have tried several links from stackoverflow to get HmacSHA256 with key to work with java, but i always get

 func check(body: String) -> String {
    let hash = body.hmac(HMACAlgorithm.sha256, key: Router.sigKey)
    print("SIG: " + Router.sigKey)
    print("result of hash. \(hash)")
    return hash
}

此函数返回哈希使用给定String的键。
关键是:0393e944ee8108bb66fc9fa4f99f9c862481e9e0519e18232ba61b0767eee8c6

This function returns hash with key from given String. Key was: 0393e944ee8108bb66fc9fa4f99f9c862481e9e0519e18232ba61b0767eee8c6

字符串是:示例

结果是:27effb76c97022497e25d3a5d7e823462f212a82d9ebba35f179071568b0c335

Result is: 27effb76c97022497e25d3a5d7e823462f212a82d9ebba35f179071568b0c335

当我使用这个网站检查我的SHA256是否使用相同的密钥,它返回相同的答案,所以我知道我在swift中的代码是好的。但是当我尝试在java中执行此操作时,这里是源代码。

When i use this website to check if my SHA256 is good with the same key, it returns same answer, so i know my code in swift is good. But when i try to do it in java, here is the source code.

public static String HMAC_SHA(){
    try {
        String secret = "0393e944ee8108bb66fc9fa4f99f9c862481e9e0519e18232ba61b0767eee8c6";
        String message = "example";
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
        sha256_HMAC.init(secret_key);
        String hash = android.util.Base64.encodeToString(sha256_HMAC.doFinal(message.getBytes()), Base64.URL_SAFE);
        return new String(Hex.encodeHex(hash.getBytes()));
    }
    catch (Exception e){
        e.printStackTrace();
    }
    return null;
}

它返回:4a2d5f3764736c77496b6c2d4a644f6c312d676a526938684b6f4c5a36376f3138586b4846576977777a553d0a

It returns this: 4a2d5f3764736c77496b6c2d4a644f6c312d676a526938684b6f4c5a36376f3138586b4846576977777a553d0a

这与快速输出甚至不相似。如何从上面的swift代码中使用java获得相同的结果,它会很有帮助!

Which is not even similar to the swift output. How can i achieve the same result with java from the swift code above, it would be helpful a lot!

推荐答案

    String key = "0393e944ee8108bb66fc9fa4f99f9c862481e9e0519e18232ba61b0767eee8c6";
    Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
    sha256_HMAC.init(new SecretKeySpec(key.getBytes(), "HmacSHA256"));
    byte[] result = sha256_HMAC.doFinal("example".getBytes());
    System.out.println (DatatypeConverter.printHexBinary(result));
    // ONLY CONVERT TO HEX (= SWIFT) NOT FIRST TO BASE64

按要求提供结果

 27EFFB76C97022497E25D3A5D7E823462F212A82D9EBBA35F179071568B0C335

这篇关于带有密钥的Java HmacSHA256的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆