Reputation:
I writing app for UWP
I have code
private string Hash(string input)
{
using (SHA1Managed sha1 = new SHA1Managed())
{
var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(input));
var sb = new StringBuilder(hash.Length * 2);
foreach (byte b in hash)
{
// can be "x2" if you want lowercase
sb.Append(b.ToString("X2"));
}
return sb.ToString();
}
}
But it not works and show this error
Severity Code Description Project File Line Suppression State Error CS0246 The type or namespace name 'SHA1Managed' could not be found (are you missing a using directive or an assembly reference?) Milano C:\Users\nemes\Documents\GitHub\Milano_pizza\Milano\WoocommerceApiClient.cs 25 Active
How I can fix this?
Upvotes: 1
Views: 769
Reputation: 7552
SHA1Managed is only available for Android and iOs, for Windows UWP use:
If you want as a result a byte array:
public byte[] getSHA1MessageDigest(string originalKey)
{
IBuffer buffer = CryptographicBuffer.ConvertStringToBinary(originalKey, BinaryStringEncoding.Utf8);
HashAlgorithmProvider hashAlgorithm = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha1);
IBuffer sha1 = hashAlgorithm.HashData(buffer);
byte[] newByteArray;
CryptographicBuffer.CopyToByteArray(sha1, out newByteArray);
return newByteArray;
}
If you want as a result a string:
public string getSHA1MessageDigest(string originalKey)
{
IBuffer buffer = CryptographicBuffer.ConvertStringToBinary(originalKey, BinaryStringEncoding.Utf8);
HashAlgorithmProvider hashAlgorithm = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha1);
IBuffer sha1 = hashAlgorithm.HashData(buffer);
byte[] newByteArray;
CryptographicBuffer.CopyToByteArray(sha1, out newByteArray);
var sb = new StringBuilder(newByteArray.Length * 2);
foreach (byte b in newByteArray)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
Upvotes: 1
Reputation: 555
For UWP use HashAlgorithmProvider
public string Hash(string input)
{
IBuffer buffer = CryptographicBuffer.ConvertStringToBinary(input, BinaryStringEncoding.Utf8);
HashAlgorithmProvider hashAlgorithm = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha1);
var hashByte = hashAlgorithm.HashData(buffer).ToArray();
var sb = new StringBuilder(hashByte.Length * 2);
foreach (byte b in hashByte)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
Remember to add
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
Upvotes: 4