C#vs Java HmacSHA1然后是base64 [英] C# vs Java HmacSHA1 and then base64

查看:283
本文介绍了C#vs Java HmacSHA1然后是base64的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个java代码示例,用于使用HMAC-SHA1算法(RFC 2104)计算摘要,然后使用Base64编码(RFC 2045)进行编码。

I have a java code example to make a digest computed using the HMAC-SHA1 algorithm (RFC 2104.), then encoded using Base64 encoding (RFC 2045).

这里是java代码

public static String buildDigest(String key, String idString) throws SignatureException {


 try {
    String algorithm = "HmacSHA1";
    Charset charset = Charset.forName("utf-8");
    SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), algorithm);
    Mac mac = Mac.getInstance(algorithm);
    mac.init(signingKey);
    return new String(Base64.encodeBase64(mac.doFinal(idString.getBytes(charset))), charset);
  } catch (Exception e) {
    throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
  }
}

我在Stack Overflow中找到了答案,所以这里是C#代码

I found answers here in Stack Overflow so here is the C# code

   private string EncodeHMAC(string input, byte[] key)
    {
        HMACSHA1 myhmacsha1 = new HMACSHA1(key);
        byte[] byteArray = Encoding.UTF8.GetBytes(input);
       // MemoryStream stream = new MemoryStream(byteArray);
        var hashValue = myhmacsha1.ComputeHash(byteArray);
        return hashValue.Aggregate("", (s, e) => s + String.Format("{0:x2}", e), s => s);
    }

    private string EncodeTo64(string toEncode)
    {
        byte[] toEncodeAsBytes = System.Text.UTF8Encoding.UTF8.GetBytes(toEncode);

        string returnValue = System.Convert.ToBase64String(toEncodeAsBytes);

        return returnValue;
    }

我没有在我正在关注的教程

推荐答案

试试这个:

// This method will return the base 64 encoded string using the given input and key.
private string EncodeHMAC(string input, byte[] key)
{
    HMACSHA1 hmac = new HMACSHA1(key);
    byte[] stringBytes = Encoding.UTF8.GetBytes(input);
    byte[] hashedValue = hmac.ComputeHash(stringBytes);
    return Convert.ToBase64String(hashedValue);
}

我认为您不会将散列值转换为基数64串正确。

I don't think you're converting the hashed value to a base 64 string correctly.

这篇关于C#vs Java HmacSHA1然后是base64的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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