C# SHA256+BASE64
C# SHA256+BASE64
資料來源: https://dotblogs.com.tw/mrsunboss/2013/04/07/99955#SHA256
片段程式碼:
SHA256 sha256 = new SHA256CryptoServiceProvider();//建立一個SHA256
byte[] source = Encoding.Default.GetBytes(input.Text);//將字串轉為Byte[]
byte[] crypto = sha256.ComputeHash(source);//進行SHA256加密
string result = Convert.ToBase64String(crypto);//把加密後的字串從Byte[]轉為字串
Response.Write(“SHA256加密: ” + result);//輸出結果
完整範例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace CS_SHA256
{
class Program
{
static void Pause()
{
Console.Write("Press any key to continue...");
Console.ReadKey(true);
}
public static string ToHexString(byte[] bytes)//16進制陣列轉字串
{
string hexString = string.Empty;
if (bytes != null)
{
StringBuilder str = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
str.Append(bytes[i].ToString("X2"));
}
hexString = str.ToString();
}
return hexString;
}
static void Main(string[] args)
{
SHA256 sha256 = new SHA256CryptoServiceProvider();//建立一個SHA256
byte[] source = Encoding.Default.GetBytes("");//將字串轉為Byte[]
byte[] crypto = sha256.ComputeHash(source);//進行SHA256加密 ~ https://emn178.github.io/online-tools/sha256.html e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
Console.WriteLine("SHA256加密:" + ToHexString(crypto));
string result = Convert.ToBase64String(crypto);//把加密後的字串從Byte[]轉為字串
Console.WriteLine("SHA256+Base64 加密:" + result);//輸出結果
Pause();
}
}
}