c# 生成的数字签名的代码
以下是使用C#生成数字签名的示例代码:
using System;
using System.Security.Cryptography;
using System.Text;
public class DigitalSignature
{
public static void Main()
{
//创建RSA密钥对
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
try
{
//获取私钥和公钥
string privateKey = rsa.ToXmlString(true);
string publicKey = rsa.ToXmlString(false);
//使用私钥对数据进行签名
byte[] data = Encoding.UTF8.GetBytes("Hello World");
byte[] signature = SignData(data, privateKey);
//验证签名是否正确
bool isVerified = VerifyData(data, signature, publicKey);
Console.WriteLine("数字签名验证结果: " + isVerified);
}
catch (CryptographicException e)
{
Console.WriteLine(e.Message);
}
}
}
//使用私钥对数据进行签名
public static byte[] SignData(byte[] data, string privateKey)
{
byte[] signature;
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
rsa.FromXmlString(privateKey);
signature = rsa.SignData(data, new SHA512CryptoServiceProvider());
}
return signature;
}
//验证签名是否正确
public static bool VerifyData(byte[] data, byte[] signature, string publicKey)
{
bool isVerified;
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
rsa.FromXmlString(publicKey);
isVerified = rsa.VerifyData(data, new SHA512CryptoServiceProvider(), signature);
}
return isVerified;
}
}
这段代码使用RSA算法对字符串"Hello World"进行数字签名,并验证签名是否正确。其中,私钥和公钥都采用XML格式进行存储和传输
原文地址: http://www.cveoy.top/t/topic/frGD 著作权归作者所有。请勿转载和采集!