一 HMAC-SHA256示例:
using System;
using System.Security.Cryptography;
using System.Text;
class Program
{
static void Main()
{
string key = "MySecretKey";
string message = "Hello, HMAC!";
byte[] keyBytes = Encoding.UTF8.GetBytes(key);
using (HMACSHA256 hmac = new HMACSHA256(keyBytes))
{
byte[] hashBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(message));
string hash = BitConverter.ToString(hashBytes).Replace("-", "").ToLower();
Console.WriteLine("HMAC-SHA256: " + hash);
}
}
}
二 RSA-SHA256示例:
using System;
using System.Security.Cryptography;
using System.Text;
class Program
{
static void Main()
{
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
try
{
string publicKey = rsa.ToXmlString(false);
string privateKey = rsa.ToXmlString(true);
byte[] data = Encoding.UTF8.GetBytes("Hello, RSA!");
byte[] signature = rsa.SignData(data, new SHA256CryptoServiceProvider());
Console.WriteLine("RSA-SHA256 Signature: " + Convert.ToBase64String(signature));
bool verified = rsa.VerifyData(data, new SHA256CryptoServiceProvider(), signature);
Console.WriteLine("Signature Verified: " + verified);
}
catch (CryptographicException e)
{
Console.WriteLine(e.Message);
}
}
}
}
三 SHA-256 和 RSA-SHA256 示例
using System;
using System.Security.Cryptography;
using System.Text;
class Program
{
static void Main()
{
string message = "Hello, SHA-256 and RSA-SHA256!";
byte[] hash;
using (SHA256 sha256 = SHA256.Create())
{
hash = sha256.ComputeHash(Encoding.UTF8.GetBytes(message));
}
Console.WriteLine("SHA-256 Hash: " + BitConverter.ToString(hash).Replace("-", "").ToLower());
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
try
{
string publicKey = rsa.ToXmlString(false);
string privateKey = rsa.ToXmlString(true);
byte[] signature;
using (SHA256 sha256 = SHA256.Create())
{
signature = rsa.SignData(hash, sha256);
}
Console.WriteLine("RSA-SHA256 Signature: " + Convert.ToBase64String(signature));
bool verified;
using (SHA256 sha256 = SHA256.Create())
{
verified = rsa.VerifyData(hash, sha256, signature);
}
Console.WriteLine("Signature Verified: " + verified);
}
catch (CryptographicException e)
{
Console.WriteLine(e.Message);
}
}
}
}