C# SHA256在散列中返回无效字符
我试图在我的C#代码中用SHA256在Unity中获取字符串的散列。我做了以下工作:C# SHA256在散列中返回无效字符,c#,unity3d,hash,C#,Unity3d,Hash,我试图在我的C#代码中用SHA256在Unity中获取字符串的散列。我做了以下工作: using UnityEngine; using System; using System.IO; using System.Security.Cryptography; using System.Text; public class URLGenerator : MonoBehaviour { void Start () { Debug.Log("myString: " + my
using UnityEngine;
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public class URLGenerator : MonoBehaviour {
void Start () {
Debug.Log("myString: " + myString);
SHA256 mySHA256 = SHA256Managed.Create();
myHashBytes = mySHA256.ComputeHash(Encoding.ASCII.GetBytes(myString));
string myHash = Encoding.ASCII.GetString(myHashBytes);
Debug.Log("myHash: " + myHash);
}
}
结果如下:
myString: 3272017110434AMbx78va23
myHash: ?)wP<??|-?)??V:?3?6"???????a??
myString:3272017110434AMbx78va23
myHash:?)wP而不是
myHashBytes = mySHA256.ComputeHash(Encoding.ASCII.GetBytes(myString));
string myHash = Encoding.ASCII.GetString(myHashBytes);
你应该
static string GetHash(SHA256 hash, string input)
{
// Convert the input string to a byte array and compute the hash.
byte[] data = hash.ComputeHash(Encoding.UTF8.GetBytes(input));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
// Return the hexadecimal string.
return sBuilder.ToString();
}
静态字符串GetHash(SHA256哈希,字符串输入)
{
//将输入字符串转换为字节数组并计算哈希。
byte[]data=hash.ComputeHash(Encoding.UTF8.GetBytes(input));
//创建新的Stringbuilder以收集字节
//并创建一个字符串。
StringBuilder sBuilder=新StringBuilder();
//循环遍历散列数据的每个字节
//并将每个字符串格式化为十六进制字符串。
for(int i=0;i
获取哈希的字符串表示形式
请参阅。尝试Encoding.GetEncoding(“1252”)
。ASCII只有7位字符,因此每个大于127的字符都不会正确显示。哈希生成一个字节数组,没有理由让这些字节值对应于ASCII字符。@Psi ASCII字符的宽度为8位。它们在@m.rogalski之前是7位宽的。恐怕您是@Psi ASCII字符,它们是8位宽的,即使您仍然只使用7位。这就是我的意思,这就是为什么有“扩展ASCII”之类的东西。