c#和java - hmacsha256 hash Redux之间的区别

时间:2017-12-28 14:53:46

标签: java c# encryption sha256 hmac

在前一个post中测试java和c#hmacsha256实现输出之间差异的代码时,我注意到输出略有不同,即当我运行java代码时输出是

ivEyFpkagEoghGnTw_LmfhDOsiNbcnEON50mFGzW9_w=

但是在C#代码中我得到了

ivEyFpkagEoghGnTw/LmfhDOsiNbcnEON50mFGzW9/w=

是否有人看过这个,即java示例中有_但c#示例中有/

Java代码

import java.util.*;
import javax.crypto.*;
import javax.crypto.spec.*;

public class Test {
    public static void main (String[] args) throws Exception {
        String secretAccessKey = "mykey";
        String data = "my data";
        byte[] secretKey = secretAccessKey.getBytes();
        SecretKeySpec signingKey = new SecretKeySpec(secretKey, "HmacSHA256");
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(signingKey);
        byte[] bytes = data.getBytes();
        byte[] rawHmac = mac.doFinal(bytes);
        System.out.println(Base64.getUrlEncoder().encodeToString(rawHmac));
    }
}

C#代码

using System;
using System.Security.Cryptography;
using System.Text;

class Test
{
    static void Main()
    {
        String secretAccessKey = "mykey";
        String data = "my data";
        byte[] secretKey = Encoding.UTF8.GetBytes(secretAccessKey);
        HMACSHA256 hmac = new HMACSHA256(secretKey);
        hmac.Initialize();
        byte[] bytes = Encoding.UTF8.GetBytes(data);
        byte[] rawHmac = hmac.ComputeHash(bytes);
        Console.WriteLine(Convert.ToBase64String(rawHmac));
    }
}

1 个答案:

答案 0 :(得分:0)

这似乎是Base64编码器的设计选择,其中一个选择使用_字符,其中一个选择使用/字符(C#也使用{{1 }}而不是+字符。如果您需要跨语言使用该字符串,可以使用-(C#中的myString.replace(oldChar, newChar))来替换不匹配字符。

如果您希望C#Base64字符串看起来像Java的Base64字符串,您可以使用myString.Replace(oldChar, newChar),但这是您必须安装的Nuget包。这使用Microsoft.IdentityModel.Tokens.Base64UrlEncoder-代替_+