visual studio - SHA1Managed UWP (C#)
本文关键字:UWP SHA1Managed studio visual | 更新日期: 2023-09-27 18:02:02
我正在为UWP编写应用程序
我有代码
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();
}
}
但是它不工作并且显示这个错误
项目文件行抑制状态找不到类型或命名空间名称"SHA1Managed"(您是否缺少using指令或程序集引用?)米兰C:'Users'nemes'Documents'GitHub'Milano_pizza'米兰' woocommerceapiclients .cs 25 Active
我该如何解决这个问题?
对于UWP使用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();
}
记得加上
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
SHA1Managed仅适用于Android和iOs,适用于Windows UWP:
如果你想要一个字节数组:
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;
}
如果你想要一个字符串作为结果:
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();
}