I am trying to generate hash value in my Android app (API 23). I followed this link- https://developer.android.com/reference/javax/crypto/Mac.html and below code should work as per it.
Mac hmacSha256 = Mac.getInstance("HmacSHA1");
But this gives compile time error-
java.security.NoSuchAlgorithmException
I searched and tried few solutions from across other Stackoverflow posts but they didn't work.
Tried this- MessageDigest digest = MessageDigest.getInstance("SHA-256");
got same error.
My overall intention is to convert the below C# code in Java so I can use it in my Android app-
string GenerateAuthToken(string verb, string resourceType, string resourceId, string date, string key, string keyType, string tokenVersion)
{
var hmacSha256 = new System.Security.Cryptography.HMACSHA256 { Key = Convert.FromBase64String(key) };
verb = verb ?? "";
resourceType = resourceType ?? "";
resourceId = resourceId ?? "";
string payLoad = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}
{1}
{2}
{3}
{4}
",
verb.ToLowerInvariant(),
resourceType.ToLowerInvariant(),
resourceId,
date.ToLowerInvariant(),
""
);
byte[] hashPayLoad = hmacSha256.ComputeHash(System.Text.Encoding.UTF8.GetBytes(payLoad));
string signature = Convert.ToBase64String(hashPayLoad);
return System.Web.HttpUtility.UrlEncode(String.Format(System.Globalization.CultureInfo.InvariantCulture, "type={0}&ver={1}&sig={2}",
keyType,
tokenVersion,
signature));
}
So I am just going and converting each line manually step by step and stuck at this point. Any ideas I can make this work?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…