本帖最后由 7ian 于 2024-6-6 12:00 编辑
我自己用的简单搞个
[C#] 纯文本查看 复制代码 using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace J7ian.Algorithm
{
/// <summary>
/// 创建个RSA类
/// </summary>
public class RSA
{
//生成RSA对象
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
/// <summary>
/// 公钥(用于加密)
/// </summary>
public string publicKey = "xxx";
/// <summary>
/// 私钥(用于加解密)
/// </summary>
public string privateKey = "xxx";
/// <summary>
/// 生成新的密钥对:公钥(publicKey)+私钥(privateKey)
/// </summary>
public void CreateKey()
{
rsa = new RSACryptoServiceProvider();
//生成1024位公钥私钥
publicKey = rsa.ToXmlString(false);
privateKey = rsa.ToXmlString(true);
}
/// <summary>
/// 公钥/私钥 加密:生成base64文本数据;失败返回空文本<br/>
/// 若key可以是CreateKey是生成的privateKey/publicKey
/// </summary>
/// <param name="data"></param>
/// <param name="key">公钥/私钥</param>
/// <returns></returns>
public string Encrypt(byte[] data, string key)
{
try
{
rsa.FromXmlString(key);
byte[] re = new byte[0];
//加密
for (int i = 0; i < data.Length; i += 117)
{
byte[] cipherbytes = rsa.Encrypt(data.Skip(i).Take(117).ToArray(), false);
re = re.Concat(cipherbytes).ToArray();
}
return Convert.ToBase64String(re);
}
catch (Exception ex)
{
Console.WriteLine("RSA-Encrypt:" + ex.Message);
return "";
}
}
/// <summary>
/// 私钥解密:根据加密后生成的base64文本数据解密<br/>
/// 若prikey可以是CreateKey生成的privateKey
/// </summary>
/// <param name="base64String"></param>
/// <param name="prikey">私钥</param>
/// <returns></returns>
public byte[] Decrypt(string base64String, string prikey)
{
byte[] re = new byte[0];
try
{
rsa.FromXmlString(prikey);
//解密
byte[] data = Convert.FromBase64String(base64String);
for (int i = 0; i < data.Length; i += 128)
{
byte[] cipherbytes = rsa.Decrypt(data.Skip(i).Take(128).ToArray(), false);
re = re.Concat(cipherbytes).ToArray();
}
return re;
}
catch (Exception ex)
{
Console.WriteLine("RSA-Decrypt:" + ex.Message);
return re;
}
}
}
}
|