gpt4 book ai didi

c# - SHA256 在哈希中返回无效字符

转载 作者:行者123 更新时间:2023-11-30 23:14:29 30 4
gpt4 key购买 nike

我试图在我的 C# 代码中,在 Unity 中使用 SHA256 获取字符串的哈希值。我做了以下事情:

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??

? 是否代表无效字符?如果是,他们为什么会出现?我是不是忘记了什么?

最佳答案

代替

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();
}

获取哈希的字符串表示形式。

参见 HashAlgorithm.ComputeHash .

关于c# - SHA256 在哈希中返回无效字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43042428/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com