csharp 使用pem密钥的本地文件RSA加密解密信息,以及SHA256的签名与验签代码
时间: 2023-05-13 12:04:43 浏览: 163
C#使用PEM文件RSA加密和解密
4星 · 用户满意度95%
以下是使用 C# 语言使用 PEM 密钥的本地文件 RSA 加密解密信息,以及 SHA256 的签名与验签代码:
加密:
```
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public static string Encrypt(string publicKeyPath, string plainText)
{
var rsa = new RSACryptoServiceProvider();
var publicKey = File.ReadAllText(publicKeyPath);
rsa.FromXmlString(publicKey);
var plainBytes = Encoding.UTF8.GetBytes(plainText);
var encryptedBytes = rsa.Encrypt(plainBytes, false);
return Convert.ToBase64String(encryptedBytes);
}
```
解密:
```
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public static string Decrypt(string privateKeyPath, string encryptedText)
{
var rsa = new RSACryptoServiceProvider();
var privateKey = File.ReadAllText(privateKeyPath);
rsa.FromXmlString(privateKey);
var encryptedBytes = Convert.FromBase64String(encryptedText);
var plainBytes = rsa.Decrypt(encryptedBytes, false);
return Encoding.UTF8.GetString(plainBytes);
}
```
签名:
```
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public static string Sign(string privateKeyPath, string plainText)
{
var rsa = new RSACryptoServiceProvider();
var privateKey = File.ReadAllText(privateKeyPath);
rsa.FromXmlString(privateKey);
var plainBytes = Encoding.UTF8.GetBytes(plainText);
var signatureBytes = rsa.SignData(plainBytes, new SHA256CryptoServiceProvider());
return Convert.ToBase64String(signatureBytes);
}
```
验签:
```
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public static bool Verify(string publicKeyPath, string plainText, string signatureText)
{
var rsa = new RSACryptoServiceProvider();
var publicKey = File.ReadAllText(publicKeyPath);
rsa.FromXmlString(publicKey);
var plainBytes = Encoding.UTF8.GetBytes(plainText);
var signatureBytes = Convert.FromBase64String(signatureText);
return rsa.VerifyData(plainBytes, new SHA256CryptoServiceProvider(), signatureBytes);
}
```
注意:以上代码仅供参考,实际使用时需要根据具体情况进行修改和调整。
阅读全文