C#到Java Base64和HmacSHA256加密

时间:2017-12-10 03:55:28

标签: java c# android base64 sha256

我在C#中有以下代码,它从Base64编码的字符串生成哈希值。

var hmacSha256 = new System.Security.Cryptography.HMACSHA256 { Key = Convert.FromBase64String(key) };

string verb = "post";
string resourceType = "docs";
string resourceId = "dbs/ToDoList/colls/Items";
string date = DateTime.UtcNow.ToString("R");

string payLoad = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}\n{1}\n{2}\n{3}\n{4}\n",
        verb.ToLowerInvariant(),
        resourceType.ToLowerInvariant(),
        resourceId,
        date.ToLowerInvariant(),
        ""
);

byte[] hashPayLoad = hmacSha256.ComputeHash(System.Text.Encoding.UTF8.GetBytes(payLoad));
string signature = Convert.ToBase64String(hashPayLoad);

string authToken = System.Web.HttpUtility.UrlEncode(String.Format(System.Globalization.CultureInfo.InvariantCulture, "type={0}&ver={1}&sig={2}",
    keyType,
    tokenVersion,
    signature));

这非常好用,我想将它转换为我的Android应用程序的Java代码。我检查了这些来源的参考资料 -

C# vs Java HmacSHA1 and then base64

c# and java - difference between hmacsha256 hash

并在Java中写下以下代码 -

String restServiceVersion = "2017-02-22";

String verb = "post";
String resourceType = "docs";
String resourceId = "dbs/ToDoList/colls/Items";

String dateString = org.apache.http.impl.cookie.DateUtils.formatDate(new Date(System.currentTimeMillis()));

String gmtIndex = "GMT";
int index = dateString.indexOf(gmtIndex);

String dateStringFinal = dateString.substring(0, index + 3).toLowerCase();

String payLoad = verb +"\n" + resourceType + "\n" + resourceId + "\n" + dateStringFinal + "\n\n";

System.out.println(payLoad);

String secretAccessKey = MASTER_KEY;
String data = payLoad;
byte[] secretKey = Base64.decode(secretAccessKey, Base64.DEFAULT);
SecretKeySpec signingKey = new SecretKeySpec(secretKey, "HmacSHA256");
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(signingKey);
byte[] bytes = data.getBytes("UTF-8");
byte[] rawHmac = mac.doFinal(bytes);

String authToken = "type=master&ver=1.0&sig=" + Base64.encodeToString(rawHmac, Base64.DEFAULT);

Java中生成的authToken值与C#不匹配。从Base64解码生成的字节数组也不同。

我不确定这是否是正确的做法。有人可以看看吗?我只需要将上面运行的C#代码转换为我的Android应用程序的Java。

1 个答案:

答案 0 :(得分:0)

最有可能的解释:您的BASE64字符串中嵌入了不可见的unicode字符(例如“零宽度非连接符”)。一个平台在base-64解码时剥离这些,另一个不是,导致不同的密钥。