Files
Ramitta-lib/Ramitta/CryptoHelper.cs
2025-11-04 11:37:27 +08:00

130 lines
3.8 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace Ramitta.lib
{
public class CryptoHelper
{
/// <summary>
/// 生成RSA密钥对
/// </summary>
/// <param name="keySize">密钥长度通常为2048、4096</param>
/// <returns>包含公钥和私钥的元组</returns>
public static (string publicKey, string privateKey) GenerateKeyPair(int keySize = 2048)
{
try
{
using (var rsa = RSA.Create(keySize))
{
string publicKey = rsa.ToXmlString(false);
string privateKey = rsa.ToXmlString(true);
return (publicKey, privateKey);
}
}
catch (Exception ex)
{
MessageBox.Show($"密钥生成失败: {ex.Message}");
return (null, null);
}
}
/// <summary>
/// 使用私钥对数据进行签名
/// </summary>
public static string? SignData(string data, string privateKey)
{
try
{
using (var rsa = RSA.Create())
{
rsa.FromXmlString(privateKey);
byte[] dataBytes = Encoding.UTF8.GetBytes(data);
byte[] signature = rsa.SignData(dataBytes, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
return Convert.ToBase64String(signature);
}
}
catch (Exception ex)
{
return null;
}
}
/// <summary>
/// 使用公钥验证签名
/// </summary>
public static bool? VerifySignature(string data, string signature, string publicKey)
{
try
{
using (var rsa = RSA.Create())
{
rsa.FromXmlString(publicKey);
byte[] dataBytes = Encoding.UTF8.GetBytes(data);
byte[] signatureBytes = Convert.FromBase64String(signature);
return rsa.VerifyData(dataBytes, signatureBytes, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
}
}
catch (Exception ex)
{
return false;
}
}
/// <summary>
/// 使用公钥加密数据
/// </summary>
public static string? Encrypt(string data, string publicKey)
{
try
{
using (var rsa = RSA.Create())
{
rsa.FromXmlString(publicKey);
byte[] dataBytes = Encoding.UTF8.GetBytes(data);
byte[] encryptedBytes = rsa.Encrypt(dataBytes, RSAEncryptionPadding.OaepSHA256);
return Convert.ToBase64String(encryptedBytes);
}
}
catch (Exception ex)
{
return null;
}
}
/// <summary>
/// 使用私钥解密数据
/// </summary>
public static string? Decrypt(string encryptedData, string privateKey)
{
try
{
using (var rsa = RSA.Create())
{
rsa.FromXmlString(privateKey);
byte[] encryptedBytes = Convert.FromBase64String(encryptedData);
byte[] decryptedBytes = rsa.Decrypt(encryptedBytes, RSAEncryptionPadding.OaepSHA256);
return Encoding.UTF8.GetString(decryptedBytes);
}
}
catch (Exception ex)
{
return null;
}
}
}
}