I have the following code in C# which generates a hash value from a Base64 encoded string.
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));
This works perfectly fine and I wanted to convert it to Java code for my Android app. I checked references from these sources-
C# vs Java HmacSHA1 and then base64
c# and java - difference between hmacsha256 hash
and wrote below code in 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);
The authToken
value generated in Java does not match with C#. Also the byte array generated from Base64 decoding differs.
I am not sure if this is the correct approach. Can someone please take a look? All I need is to convert the above working C# code to Java for my Android app.