using System;
using System.Security.Cryptography;
using System.Text;
public class RSAEncryptor
{
private const string DefaultPublicKey = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIywmdAMQrr/Vy5l/a/9sUzNj0moYGGbCKZ0lHVdbI9YV67sxVSzPPcQb6KFw/Xvn3bz8VGtJsHRI3JdwwP178UCAwEAAQ==";
public string RsaEncrypt(string content, string publicKey = null)
{
try
{
string keyToUse = publicKey ?? DefaultPublicKey;
byte[] encryptedData = EncryptString(content, keyToUse);
return BitConverter.ToString(encryptedData).Replace("-", "").ToLower();
}
catch (Exception ex)
{
Console.WriteLine($"加密出错: {ex.Message}");
return null;
}
}
private byte[] EncryptString(string text, string publicKey)
{
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048))
{
rsa.PersistKeyInCsp = false;
RSAParameters rsaParams = ConvertFromPublicKey(publicKey);
rsa.ImportParameters(rsaParams);
byte[] dataToEncrypt = Encoding.UTF8.GetBytes(text);
return rsa.Encrypt(dataToEncrypt, false);
}
}
private RSAParameters ConvertFromPublicKey(string publicKey)
{
byte[] keyBytes = Convert.FromBase64String(publicKey);
int offset = 0;
if (keyBytes[offset++] != 0x30)
throw new ArgumentException("无效的公钥格式");
int length = keyBytes[offset++];
if (length > 0x80)
offset += length - 0x80;
if (keyBytes[offset++] != 0x30)
throw new ArgumentException("无效的公钥格式");
int algLength = keyBytes[offset++];
offset += algLength;
if (keyBytes[offset++] != 0x03)
throw new ArgumentException("无效的公钥格式");
int bitStringLength = keyBytes[offset++];
offset++;
if (keyBytes[offset++] != 0x30)
throw new ArgumentException("无效的公钥格式");
int seqLength = keyBytes[offset++];
if (keyBytes[offset++] != 0x02)
throw new ArgumentException("无效的公钥格式");
int modLength = keyBytes[offset++];
if (keyBytes[offset] == 0x00)
{
offset++;
modLength--;
}
byte[] modulus = new byte[modLength];
Array.Copy(keyBytes, offset, modulus, 0, modLength);
offset += modLength;
if (keyBytes[offset++] != 0x02)
throw new ArgumentException("无效的公钥格式");
int expLength = keyBytes[offset++];
byte[] exponent = new byte[expLength];
Array.Copy(keyBytes, offset, exponent, 0, expLength);
return new RSAParameters
{
Modulus = modulus,
Exponent = exponent
};
}
}
class Program
{
static void Main()
{
var encryptor = new RSAEncryptor();
string original = "1448032738553055";
string encrypted = encryptor.RsaEncrypt(original);
Console.WriteLine($"原始: {original}");
Console.WriteLine($"加密: {encrypted}");
Console.WriteLine($"长度: {encrypted?.Length}");
}
}