RSA 加密

发布时间 2023-07-19 17:37:04作者: WantRemake
//通用RSA加密,可兼容.Net 6.0以下
string CommonRSAEncrypt(string publicKeyBase64, string plaintext)
{
    try
    {
        byte[] publicKeyBytes = Convert.FromBase64String(publicKeyBase64);
        AsymmetricKeyParameter publicKeyParam = PublicKeyFactory.CreateKey(publicKeyBytes);
        IBufferedCipher rsa = CipherUtilities.GetCipher("RSA");
        rsa.Init(true, publicKeyParam);
        byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext);
        byte[] ciphertextBytes = rsa.DoFinal(plaintextBytes);
        string encryptedText = Convert.ToBase64String(ciphertextBytes);

        return encryptedText;
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
    }

    return null;
}

//RSA 加密,.Net6.0版本可用
string RSAEncrypt(string publicKey, string password)
{
    try
    {
        byte[] decoded = Convert.FromBase64String(publicKey);
        RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
        provider.ImportSubjectPublicKeyInfo(decoded, out int bytesRead);
        // RSA加密
        byte[] bytesToEncrypt = Encoding.UTF8.GetBytes(password);
        byte[] ciphertext = provider.Encrypt(bytesToEncrypt, false);
        //**此处Base64编码,开发者可以使用自己的库**
        string outStr = Convert.ToBase64String(ciphertext);
        //outStr 是加密密文
        return outStr;
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
    }
    return null;
}

//通用RSA解密,可兼容.Net 6.0以下
string CommonRSADecrypt(string privateKeyBase64, string ciphertext)
{
    try
    {
        byte[] privateKeyBytes = Convert.FromBase64String(privateKeyBase64);
        AsymmetricKeyParameter privateKeyParam = PrivateKeyFactory.CreateKey(privateKeyBytes);
        IBufferedCipher rsa = CipherUtilities.GetCipher("RSA");
        rsa.Init(false, privateKeyParam);
        byte[] ciphertextBytes = Convert.FromBase64String(ciphertext);
        byte[] decryptedBytes = rsa.DoFinal(ciphertextBytes);
        string decryptedText = Encoding.UTF8.GetString(decryptedBytes);

        return decryptedText;
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
    }

    return null;
}