Rsa加密解密C#(dotnet)和java互通

329 阅读6分钟

Rsa 非对称加密解密互通推荐使用三方包快捷方便

bouncycastle.org

Legion of the Bouncy Castle Inc (github.com)

工具

通过代码生成或则使用openssl生成秘钥

推荐安装openssl

OpenSSL的github地址:github.com/openssl/ope…

mac电脑安装包推荐用:

brew Homebrew — The Missing Package Manager for macOS (or Linux)

windows电脑安装包

下载地址:slproweb.com/products/Wi…

生成证书命令

生成私钥 

        openssl genrsa -out private.key 2048 

 生成一个X.509公钥证书文件 

        openssl req -new -x509 -key private.key -out publickey.cer -days 365 

 合并正式pfx文件(C# windows使用) 

        openssl pkcs12 -export -out certificate.pfx -inkey private.key -in publickey.cer 

 生成一个rsa公钥 

       openssl rsa -pubout -in private.key -out publickey.pem

使用场景

  1. 数据传输加密解密
  2. jwt生成令牌
  3. 其他接口使用

秘钥内容规范

  1. 公钥私钥都是使用base64字符串
  2. 通过公钥或私钥加密后的字符串也是base64
  3. 只有解密后的字符串明文
  4. RSA加密过程是使用接收者的公钥加密数据,然后使用接收者的私钥解密数据。这是非对称加密的基本原理

测试秘钥

私钥

String privateKey =        "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC+hQZ0KLLp4gRcm7Kg2IFv6xzWxZ4Hdi4xIbCwHNt6zptCA17PC0pO01F2j5MzeWTdooCj3c+w3s2hVjtEL72AobdWNijvzm1xkGXNuh6oBncPCggxTYK379DrhcHelvdW8RGIwY6qkDftQrEPaobSIG3YT07J9G5vWHo78jnkTcyJtP1fwbZENDzRgiBZWRD0PgeLfL3E7wm5TJ7PORNuDLF+RraLChljAYLIlpRZR71I5eH8d6lmYyaPugn0QFTM9RemEv09TSXw80KSX6zuoP/RISJFPRG5BI050LVSzeA/iNKbU7qdn3CQ4GbemJJ5YDSzwl+d2uZc6ZIOjHDTAgMBAAECggEABY9LO2uOoQ2j8/HlOhVnXZU+X7QfovcbbPqfNdx5uTE7Tadchm09a2R2TZ/t+0QRIfiiiWWpMG+oD4u9KgW8oXrWp1DoS+s5vWUp22GRkHSz18ACsjGhXW3FqoHaQP0l1acuTE/dsnOH9kgKc7k3mv0wR241DeawrFYoJwSwFM31fdQjqjx389741f47GPP2Tp4oqNzzj2QyBSYREqAosulwDaB464cwpZ6+AcjcxCGTZtwlVO7xuUBDny6PxK8bA4eTjd8//j/BHCEgoi3zVd2lANQYYkTS33b6UUfNNB3ndDhfLalLth8AXuKoJZld13O96xazCbFdeOD6JlomyQKBgQDrtbveOJfGOsPeokvi6dNl5WfigRyhyhnrohbVdON6kZMJCHJt7u/1C2HAV134TUvSlUWDdLOXvShlbcRWC3w3NWfQkFkRvID3PQyk2YfKsNQtwdse9bRxrMZh9SE1bj+E0srkHE4NgtwZ7IVinQkR7xuntocqy8mKpBDOyM27aQKBgQDO63KHthq4PYTjG7oTg5e0N2ZFTARcc98I5TQESnD+g/pdjx/n9y0xay6RLfnS/uMmJHX6ZTGtG+EFVvE5qmft2qsu7kPPU5aGZOTXPTdBGmXV8fIfo7OS9U52MXYT0Jja+R0Mz2gCt3rsYBXPA5VVMelYVuYw0b8DvvGn/RZu2wKBgB+rAfugNNwAJzKxMWriKXHGOYfX+uXNxl+/Hjw9gRaFmnCbPuyALqMIjXCPDGQA1pALWBSKSFq5okTGU5uP3Xd5aGJAEodsgRM2k41OYI0d5tPi+LKXJlAje1/L1FNeZZBN1c6B8wajrziYa29NU9uh+WA2CMD6MjC7TDrMBcAJAoGAL8N5tIn8sPrCagpEcay2oAsJuIVLnGvC2DLQRw1H9/hPGrmnC8yqyfWL0kdim6nqlStlcF9bkDIXRzxCgqUrSGRpj3PAg2MwI+W2TVj8IDMPvssSsOsA0LN/YRkZwIkuP52xbvuRbs8buOSVJCwXlIro6lNk33ALP7ob3kM1onECgYEAlYzFDeeMHjPlVj5phoV3sQmCByAN9ruWkS56Y2Nwd2ZGSE1a9/stEWml0hcp3Bm6TSMYlf5kMy1LtOMj1b519jyflZo9wbUCqJ5T37NqLMuD5Zer7PcaxhTs0podUPCjZUEi0OTrnQmcepaiMylSE1M33ld4/nJsoJvrj1ILMBU=";

公钥

String publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvoUGdCiy6eIEXJuyoNiBb+sc1sWeB3YuMSGwsBzbes6bQgNezwtKTtNRdo+TM3lk3aKAo93PsN7NoVY7RC+9gKG3VjYo785tcZBlzboeqAZ3DwoIMU2Ct+/Q64XB3pb3VvERiMGOqpA37UKxD2qG0iBt2E9OyfRub1h6O/I55E3MibT9X8G2RDQ80YIgWVkQ9D4Hi3y9xO8JuUyezzkTbgyxfka2iwoZYwGCyJaUWUe9SOXh/HepZmMmj7oJ9EBUzPUXphL9PU0l8PNCkl+s7qD/0SEiRT0RuQSNOdC1Us3gP4jSm1O6nZ9wkOBm3piSeWA0s8JfndrmXOmSDoxw0wIDAQAB";

JAVA代码

引入mvn包

<!-- https://mvnrepository.com/artifact/org.bouncycastle/bcprov-jdk16 -->
<dependency>    
    <groupId>org.bouncycastle</groupId>    
    <artifactId>bcprov-jdk16</artifactId>    
    <version>1.46</version>
</dependency>

java 帮助类

import org.bouncycastle.crypto.AsymmetricBlockCipher;
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.crypto.KeyGenerationParameters;
import org.bouncycastle.crypto.encodings.PKCS1Encoding;
import org.bouncycastle.crypto.engines.RSAEngine;
import org.bouncycastle.crypto.generators.RSAKeyPairGenerator;
import org.bouncycastle.crypto.params.AsymmetricKeyParameter;
import org.bouncycastle.crypto.params.RSAKeyGenerationParameters;
import org.bouncycastle.crypto.params.RSAKeyParameters;
import org.bouncycastle.crypto.util.PrivateKeyFactory;
import org.bouncycastle.crypto.util.PublicKeyFactory;
import org.bouncycastle.util.encoders.Base64;

import java.math.BigInteger;
import java.security.SecureRandom;
import java.nio.charset.StandardCharsets;

public class RSAUtil {
    public static String RSA_ALGORITHM = "RSA";
    public static String UTF8 = "UTF-8";

    public static class KeyStore {
        private String publicKey;
        private String privateKey;

        public String getPublicKey() {
            return publicKey;
        }

        public void setPublicKey(String publicKey) {
            this.publicKey = publicKey;
        }

        public String getPrivateKey() {
            return privateKey;
        }

        public void setPrivateKey(String privateKey) {
            this.privateKey = privateKey;
        }
    }
    /**
     * 创建公钥私钥
     */
    public static KeyStore createKeys() {
        try {

            AsymmetricCipherKeyPair keyPair = getAsymmetricCipherKeyPair();
            RSAKeyParameters publicKey = (RSAKeyParameters) keyPair.getPublic();
            RSAKeyParameters privateKey = (RSAKeyParameters) keyPair.getPrivate();

            // 将公钥和私钥编码为Base64字符串
            String publicKeyBase64 = new String(Base64.encode(publicKey.getExponent().toByteArray()), StandardCharsets.UTF_8);
            String privateKeyBase64 = new String(Base64.encode(privateKey.getExponent().toByteArray()), StandardCharsets.UTF_8);

            System.out.println("Public Key (Base64): " + publicKeyBase64);
            System.out.println("Private Key (Base64): " + privateKeyBase64);
            KeyStore keyStore = new KeyStore();
            keyStore.setPublicKey(publicKeyBase64);
            keyStore.setPrivateKey(privateKeyBase64);
            return keyStore;

        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    private static AsymmetricCipherKeyPair getAsymmetricCipherKeyPair() {
        SecureRandom secureRandom = new SecureRandom();

        // 设置公钥指数,通常选择65537
        BigInteger publicExponent = new BigInteger("65537");

        // 创建RSA密钥对生成器
        RSAKeyPairGenerator generator = new RSAKeyPairGenerator();
        KeyGenerationParameters keyGenParam = new RSAKeyGenerationParameters(
                publicExponent,
                secureRandom,
                2048,
                80
        );
        generator.init(keyGenParam);

        // 生成RSA密钥对
        AsymmetricCipherKeyPair keyPair = generator.generateKeyPair();
        return keyPair;
    }

    /*
     * 私钥加密 (需要公钥解密)
     */
    public static String encryptWithPrivateKey(String plaintext,String keyBase64) {
        try {
            keyBase64 = keyBase64.replace("\r", "").replace("\n", "").replace(" ", "");
            byte[] privateInfoByte = Base64.decode(keyBase64);
            AsymmetricKeyParameter priKey = PrivateKeyFactory.createKey(privateInfoByte);

            AsymmetricBlockCipher engine = new PKCS1Encoding(new RSAEngine());
            engine.init(true, priKey);

            byte[] plaintextKeyBytes = plaintext.getBytes(StandardCharsets.UTF_8);
            byte[] encryptedData = engine.processBlock(plaintextKeyBytes, 0, plaintextKeyBytes.length);

            String result = new String(Base64.encode(encryptedData));
            System.out.println("Encrypted: " + result);
            return result;
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    /*
    *公钥解密(需要私钥加密)
    */
    public static String decryptWithPublicKey(String ciphertext, String publicKeyBase64) {
        try {
            publicKeyBase64 = publicKeyBase64.replace("\r", "").replace("\n", "").replace(" ", "");
            byte[] publicInfoByte = Base64.decode(publicKeyBase64);
            AsymmetricKeyParameter pubKey = PublicKeyFactory.createKey(publicInfoByte);

            AsymmetricBlockCipher engine = new PKCS1Encoding(new RSAEngine());
            engine.init(false, pubKey);

            byte[] encryptedData = Base64.decode(ciphertext);
            byte[] decryptedData = engine.processBlock(encryptedData, 0, encryptedData.length);

            String result = new String(decryptedData, StandardCharsets.UTF_8);
            System.out.println("Decrypted: " + result);
            return result;
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
    /*
     *公钥加密(需要私钥解密)
     */
    public static String encryptWithPublicKey(String plaintext, String publicKeyBase64) {
        try {
            publicKeyBase64 = publicKeyBase64.replace("\r", "").replace("\n", "").replace(" ", "");
            byte[] publicInfoByte = Base64.decode(publicKeyBase64);
            AsymmetricKeyParameter pubKey = PublicKeyFactory.createKey(publicInfoByte);

            AsymmetricBlockCipher engine = new PKCS1Encoding(new RSAEngine());
            engine.init(true, pubKey);

            byte[] byteData = plaintext.getBytes(StandardCharsets.UTF_8);
            byte[] encryptedData = engine.processBlock(byteData, 0, byteData.length);

            String result = new String(Base64.encode(encryptedData));
            System.out.println("Encrypted: " + result);
            return result;
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
    /*
     *私钥解密(需要公钥加密)
     */
    public static String decryptWithPrivateKey(String ciphertext, String privateKeyBase64) {
        try {
            privateKeyBase64 = privateKeyBase64.replace("\r", "").replace("\n", "").replace(" ", "");
            byte[] privateInfoByte = Base64.decode(privateKeyBase64);
            AsymmetricKeyParameter priKey = PrivateKeyFactory.createKey(privateInfoByte);

            AsymmetricBlockCipher engine = new PKCS1Encoding(new RSAEngine());
            engine.init(false, priKey);

            byte[] encryptedData = Base64.decode(ciphertext);
            byte[] decryptedData = engine.processBlock(encryptedData, 0, encryptedData.length);

            String result = new String(decryptedData, StandardCharsets.UTF_8);
            System.out.println("Decrypted: " + result);
            return result;
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

}

C#代码

引入包

<PackageReference Include="BouncyCastle.Cryptography" Version="2.2.1" />

帮助类

using System;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Encodings;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Operators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.X509;

 
    /// <summary>
    /// KEY 
    /// </summary>
    public class RsaKey
    {
        /// <summary>
        /// 公钥
        /// </summary>
        public string PublicPemBase64String { get; set; }
        /// <summary>
        /// 私钥
        /// </summary>
        public string PrivateKeyBase64String { get; set; }
    }
    
    public static class RSAUtil
    {
        public static System.Security.Cryptography.RSA LoadCertificatePrivateKey(string keyBase64)
        {
            
            try
            {
                keyBase64 = keyBase64.Replace("\r", "").Replace("\n", "").Replace(" ", "");
                byte[] privateInfoByte = Convert.FromBase64String(keyBase64);
                AsymmetricKeyParameter  priKey = PrivateKeyFactory.CreateKey(privateInfoByte);
                // 创建 RSA 参数
                RsaPrivateCrtKeyParameters privateKeyParams = (RsaPrivateCrtKeyParameters)priKey;

                // 创建 RSA 对象
                var rsa = System.Security.Cryptography.RSA.Create();
                RSAParameters rsaParams = new RSAParameters
                {
                    Modulus = privateKeyParams.Modulus.ToByteArrayUnsigned(),
                    Exponent = privateKeyParams.PublicExponent.ToByteArrayUnsigned(),
                    D = privateKeyParams.Exponent.ToByteArrayUnsigned(),
                    P = privateKeyParams.P.ToByteArrayUnsigned(),
                    Q = privateKeyParams.Q.ToByteArrayUnsigned(),
                    DP = privateKeyParams.DP.ToByteArrayUnsigned(),
                    DQ = privateKeyParams.DQ.ToByteArrayUnsigned(),
                    InverseQ = privateKeyParams.QInv.ToByteArrayUnsigned()
                };
                rsa.ImportParameters(rsaParams);
                return rsa;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static System.Security.Cryptography.RSA LoadCertificatePublicCer(string keyBase64)
        {
            
            try
            {
                byte[] certBytes = Convert.FromBase64String(keyBase64);
                Org.BouncyCastle.X509.X509Certificate cert = new Org.BouncyCastle.X509.X509Certificate(certBytes);
                // 从 X.509 证书中提取公钥
                AsymmetricKeyParameter publicKey = cert.GetPublicKey();
                RsaKeyParameters rsaKey = (RsaKeyParameters)publicKey;

                // 创建 RSA 对象
                var rsa = System.Security.Cryptography.RSA.Create();
                RSAParameters rsaParameters = new RSAParameters
                {
                    Modulus = rsaKey.Modulus.ToByteArrayUnsigned(),
                    Exponent = rsaKey.Exponent.ToByteArrayUnsigned()
                };
                rsa.ImportParameters(rsaParameters);
                return rsa;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static System.Security.Cryptography.RSA LoadCertificatePublicPem(string keyBase64)
        {
            
            try
            {
                keyBase64 = keyBase64.Replace("\r", "").Replace("\n", "").Replace(" ", "");
                byte[] publicInfoByte = Convert.FromBase64String(keyBase64);
                Asn1Object pubKeyObj = Asn1Object.FromByteArray(publicInfoByte);//这里也可以从流中读取,从本地导入
                AsymmetricKeyParameter pubKey = PublicKeyFactory.CreateKey(publicInfoByte);
                
                RsaKeyParameters rsaKey = (RsaKeyParameters)pubKey;

                // 创建 RSA 对象
                var rsa = System.Security.Cryptography.RSA.Create();
                RSAParameters rsaParameters = new RSAParameters
                {
                    Modulus = rsaKey.Modulus.ToByteArrayUnsigned(),
                    Exponent = rsaKey.Exponent.ToByteArrayUnsigned()
                };
                rsa.ImportParameters(rsaParameters);
                return rsa;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private static Encoding Encoding_UTF8 = Encoding.UTF8;
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static (AsymmetricKeyParameter, AsymmetricKeyParameter) Generator()
        {
            //RSA密钥构造器的参数
            RsaKeyPairGenerator generator = new RsaKeyPairGenerator();
            generator.Init(new KeyGenerationParameters(new SecureRandom(), 2048));
            AsymmetricCipherKeyPair keyPair = generator.GenerateKeyPair();
            //获取公钥和密钥
            AsymmetricKeyParameter privateKey = keyPair.Private;
            AsymmetricKeyParameter publicKey = keyPair.Public;
            return (privateKey, publicKey);
        }
        
        public static RsaKey GeneratorPrivateAndPublicKeyString()
        {

            var keyPair = Generator();
            //获取公钥和密钥
            AsymmetricKeyParameter privateKey = keyPair.Item1;
            AsymmetricKeyParameter publicKey = keyPair.Item2;
            
            PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);
            Asn1Object asn1ObjectPrivate = privateKeyInfo.ToAsn1Object();
            byte[] privateInfoByte = asn1ObjectPrivate.GetEncoded("UTF-8");
            
            SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);
            Asn1Object asn1ObjectPublic = subjectPublicKeyInfo.ToAsn1Object();
            byte[] publicInfoByte = asn1ObjectPublic.GetEncoded("UTF-8");
            
            RsaKey item = new RsaKey()
            {
                PublicPemBase64String = Convert.ToBase64String(publicInfoByte).Replace("\r", "").Replace("\n", "").Replace(" ", ""),
                PrivateKeyBase64String = Convert.ToBase64String(privateInfoByte).Replace("\r", "").Replace("\n", "").Replace(" ", "")
            };
            return item;
        }
        
        public static (AsymmetricKeyParameter, System.Security.Cryptography.X509Certificates.X509Certificate2) GenerateRsaKeyPairAndCert()
        {
            
            var keyPair = Generator();
            //获取公钥和密钥
            AsymmetricKeyParameter privateKey = keyPair.Item1;
            AsymmetricKeyParameter publicKey = keyPair.Item2;
            
            // Create X.509 certificate
            var subjectDN = new X509Name("CN=beisen, O=www.italent.cn");
            var issuerDN = subjectDN; // Self-signed certificate
            var serialNumber = new BigInteger(32, new SecureRandom());
            var notBefore = DateTime.UtcNow;
            var notAfter = notBefore.AddYears(1); // 过期时间

            var certificateGenerator = new X509V3CertificateGenerator();
            certificateGenerator.SetSerialNumber(serialNumber);
            certificateGenerator.SetSubjectDN(subjectDN);
            certificateGenerator.SetIssuerDN(issuerDN);
            certificateGenerator.SetNotBefore(notBefore);
            certificateGenerator.SetNotAfter(notAfter);
            
            certificateGenerator.SetPublicKey(publicKey);
            var signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", privateKey);
            var x509Certificate = certificateGenerator.Generate(signatureFactory);

            // Convert BouncyCastle certificate to X.509 certificate
            var bcCertBytes = x509Certificate.GetEncoded();
            var x509Cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(bcCertBytes);

            return (privateKey, x509Cert);
        }
        
        public static void SaveFileByAsymmetricKeyParameter(AsymmetricKeyParameter key,string keyFilePath)
        {
             using (TextWriter textWriter = new StreamWriter(keyFilePath))
             {
                 PemWriter pemWriter = new PemWriter(textWriter);
                 pemWriter.WriteObject(key);
                 pemWriter.Writer.Flush();
             }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="privateKeyPath"></param>
        /// <returns></returns>
        public static AsymmetricKeyParameter LoadPrivateKeyFromFile(string privateKeyPath)
        {
            using (var streamReader = System.IO.File.OpenText(privateKeyPath))
            {
                PemReader pemReader = new PemReader(streamReader);
                AsymmetricCipherKeyPair keyPair = (AsymmetricCipherKeyPair)pemReader.ReadObject();
                return keyPair.Private;
            }
        }

        public static AsymmetricKeyParameter LoadPublicKeyFromPemFile(string publicKeyPath)
        {
            using (var streamReader = System.IO.File.OpenText(publicKeyPath))
            {
                PemReader pemReader = new PemReader(streamReader);
                var publicKey = (SubjectPublicKeyInfo)pemReader.ReadObject();
                return PublicKeyFactory.CreateKey(publicKey);
            }
        }
        
        public static void SaveFileByX509Certificate2(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate,string keyFilePath)
        {
            // 将 X509Certificate2 导出为 PEM 格式
            string pemString = "-----BEGIN CERTIFICATE-----\n";
            pemString += Convert.ToBase64String(certificate.Export(X509ContentType.Cert), Base64FormattingOptions.InsertLineBreaks);
            pemString += "\n-----END CERTIFICATE-----";
            File.WriteAllText(keyFilePath, pemString);
        }

        public static X509Certificate2 X509CertificateLoad(string cerFilePath,string password="")
        {
            
            Pkcs12Store pkcs = new Pkcs12StoreBuilder().Build();
            using (Stream stream = File.OpenRead(cerFilePath))
            {
                pkcs.Load(stream, password.ToCharArray());
            }
        
            var keyAlias = pkcs.Aliases.Cast<string>().SingleOrDefault(a => pkcs.IsKeyEntry(a));
        
            var key = (RsaPrivateCrtKeyParameters)pkcs.GetKey(keyAlias).Key;
            var bouncyCertificate = pkcs.GetCertificate(keyAlias).Certificate;

            var cer1 = DotNetUtilities.ToX509Certificate(bouncyCertificate);
            
            var certificate = new X509Certificate2(cer1);
            var parameters = DotNetUtilities.ToRSAParameters(key);
        
            RSACryptoServiceProvider pirRsa = new RSACryptoServiceProvider();  
            pirRsa.ImportParameters(parameters);
        
            certificate = RSACertificateExtensions.CopyWithPrivateKey(certificate, pirRsa);
        
            return certificate;
        }
        

        /// <summary>
        /// 私钥加密(公钥解密数据)
        /// </summary>
        /// <param name="plaintext">明文</param>
        /// <param name="keyBase64">私钥</param>
        /// <returns>返回Base64内容</returns>
        public static string EncryptWithPrivateKey(string plaintext, string keyBase64)
        {
            try
            {
                keyBase64 = keyBase64.Replace("\r", "").Replace("\n", "").Replace(" ", "");
                byte[] privateInfoByte = Convert.FromBase64String(keyBase64);
                AsymmetricKeyParameter priKey = PrivateKeyFactory.CreateKey(privateInfoByte);
                
                IAsymmetricBlockCipher engine = new Pkcs1Encoding(new RsaEngine());
                engine.Init(true, priKey);
                byte[] byteData = Encoding_UTF8.GetBytes(plaintext);
                var encryptedData = engine.ProcessBlock(byteData, 0, byteData.Length);
                var result = Convert.ToBase64String(encryptedData);
                Console.WriteLine($"Encrypted: {result}");
                return result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        
        /// <summary>
        /// 私钥解密数据(公钥加密数据)
        /// </summary>
        /// <param name="encryptedString">秘文</param>
        /// <param name="keyBase64">私钥</param>
        /// <returns></returns>
        public static string DecryptWithPrivateKey(string encryptedString, string keyBase64)
        {
            try
            {
                keyBase64 = keyBase64.Replace("\r", "").Replace("\n", "").Replace(" ", "");
                byte[] privateInfoByte = Convert.FromBase64String(keyBase64);
                AsymmetricKeyParameter priKey = PrivateKeyFactory.CreateKey(privateInfoByte);
                var engine = new Pkcs1Encoding(new RsaEngine());
                engine.Init(false, priKey);
                byte[] encryptedBytes = Convert.FromBase64String(encryptedString);
                byte[] decryptedBytes = engine.ProcessBlock(encryptedBytes, 0, encryptedBytes.Length);
                return Encoding.UTF8.GetString(decryptedBytes);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
       
        /// <summary>
        /// 公钥解密(私钥加密数据)
        /// </summary>
        /// <param name="encryptedString">待解密的内容</param>
        /// <param name="keyBase64">公钥</param>
        /// <returns>返回明文</returns>
        public static string DecryptWithPublicPem(string encryptedString, string keyBase64)
        {
            
            try
            {
                keyBase64 = keyBase64.Replace("\r", "").Replace("\n", "").Replace(" ", "");
                byte[] publicInfoByte = Convert.FromBase64String(keyBase64);
                Asn1Object pubKeyObj = Asn1Object.FromByteArray(publicInfoByte);//这里也可以从流中读取,从本地导入
                AsymmetricKeyParameter pubKey = PublicKeyFactory.CreateKey(publicInfoByte);
                
                IAsymmetricBlockCipher engine = new Pkcs1Encoding(new RsaEngine());
                engine.Init(false,pubKey);
                byte[] encryptedDataBytes = Convert.FromBase64String(encryptedString);
                byte[] decryptedData = engine.ProcessBlock(encryptedDataBytes, 0, encryptedDataBytes.Length);
                string plaintext = System.Text.Encoding.UTF8.GetString(decryptedData);
                return plaintext;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        
       /// <summary>
       /// 公钥加密数据(私钥解密数据)
       /// </summary>
       /// <param name="plaintext">明文</param>
       /// <param name="keyBase64"></param>
       /// <returns></returns>
        public static string EncryptWithPublicPem(string plaintext, string keyBase64)
        {
            try
            {
                keyBase64 = keyBase64.Replace("\r", "").Replace("\n", "").Replace(" ", "");
                byte[] publicInfoByte = Convert.FromBase64String(keyBase64);
                AsymmetricKeyParameter pubKey = PublicKeyFactory.CreateKey(publicInfoByte);
                
                var engine = new Pkcs1Encoding(new RsaEngine());
                engine.Init(true, pubKey);
                byte[] dataBytes = Encoding.UTF8.GetBytes(plaintext);
                byte[] encryptedBytes = engine.ProcessBlock(dataBytes, 0, dataBytes.Length);
                return Convert.ToBase64String(encryptedBytes);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        
        /// <summary>
        /// 公钥解密
        /// </summary>
        /// <param name="encryptedString">待解密的内容</param>
        /// <param name="publicCerText">公钥</param>
        /// <returns>返回明文</returns>
        public static string DecryptWithPublicCer(string encryptedString, string publicCerText)
        {
            
            try
            {
                byte[] certBytes = Convert.FromBase64String(publicCerText);
                Org.BouncyCastle.X509.X509Certificate cert = new Org.BouncyCastle.X509.X509Certificate(certBytes);
                // 从 X.509 证书中提取公钥
                AsymmetricKeyParameter publicKey = cert.GetPublicKey();
                IAsymmetricBlockCipher engine = new Pkcs1Encoding(new RsaEngine());
                engine.Init(false, publicKey);
                byte[] encryptedDataBytes = Convert.FromBase64String(encryptedString);
                byte[] decryptedData = engine.ProcessBlock(encryptedDataBytes, 0, encryptedDataBytes.Length);
                string plaintext = System.Text.Encoding.UTF8.GetString(decryptedData);
                return plaintext;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }

代码地址

github.com/wangboy91/d…