Получить строку строки SHA-256
У меня есть немного string
и я хочу хэшировать его с помощью хэш-функции SHA-256, используя C#. Я хочу что-то вроде этого:
string hashString = sha256_hash("samplestring");
Есть ли что-то встроенное в рамки для этого?
5 ответов
Решение
Реализация может быть такой
public static String sha256_hash(String value) {
StringBuilder Sb = new StringBuilder();
using (SHA256 hash = SHA256Managed.Create()) {
Encoding enc = Encoding.UTF8;
Byte[] result = hash.ComputeHash(enc.GetBytes(value));
foreach (Byte b in result)
Sb.Append(b.ToString("x2"));
}
return Sb.ToString();
}
Редактировать: реализацияLinq более краткая, но, вероятно, менее читабельная:
public static String sha256_hash(String value) {
using (SHA256 hash = SHA256Managed.Create()) {
return String.Concat(hash
.ComputeHash(Encoding.UTF8.GetBytes(value))
.Select(item => item.ToString("x2")));
}
}
Редактировать 2:.NET Core
public static String sha256_hash(string value)
{
StringBuilder Sb = new StringBuilder();
using (var hash = SHA256.Create())
{
Encoding enc = Encoding.UTF8;
Byte[] result = hash.ComputeHash(enc.GetBytes(value));
foreach (Byte b in result)
Sb.Append(b.ToString("x2"));
}
return Sb.ToString();
}
Это гораздо более приятный / аккуратный способ в ядре .net:
public static string sha256_hash( string value )
{
using var hash = SHA256.Create();
var byteArray = hash.ComputeHash( Encoding.UTF8.GetBytes( value ) );
return Convert.ToHexString( byteArray ).ToLower();
}
Просто:
string sha256(string s) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(s)));
Я искал встроенное решение и смог скомпилировать нижеприведенный ответ Дмитрия:
public static String sha256_hash(string value)
{
return (System.Security.Cryptography.SHA256.Create()
.ComputeHash(Encoding.UTF8.GetBytes(value))
.Select(item => item.ToString("x2")));
}
Я попробовал все вышеперечисленные методы, и ни один из них мне не помог. Я сделал вот этот, который работает безупречно:
public static string Encrypt(string input)
{
using (SHA256 sha256 = SHA256.Create())
{
// Convert the input string to a byte array
byte[] inputBytes = Encoding.UTF8.GetBytes(input);
// Compute the hash value of the input bytes
byte[] hashBytes = sha256.ComputeHash(inputBytes);
// Convert the hash bytes to a hexadecimal string
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hashBytes.Length; i++)
{
sb.Append(hashBytes[i].ToString("x2"));
}
return sb.ToString();
}
}
Обязательно используйте System.Security.Cryptography в начале вашего кода.
using System.Security.Cryptography