C#RSA加解密

场景:

为了支持与JAVA端进行通信数据的加解密,C#编写的客户端使用BouncyCastle进行rsa非对称加密。

 

BouncyCastle安装:直接在Visual 2019 项目->管理Nuget程序包,搜索安装。

上源码:

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text.RegularExpressions;
using System.Runtime;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Web;
using System.Diagnostics;

using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Crypto.Encodings;

namespace FileApplication
{    
    class Program
	{                
        /// <summary>
        /// KEY 结构体
        /// </summary>
        public struct RSAKEY
        {
            /// <summary>
            /// 公钥
            /// </summary>
            public string PublicKey { get; set; }
            /// <summary>
            /// 私钥
            /// </summary>
            public string PrivateKey { get; set; }
        }
        public RSAKEY GetKey()
        {
            //RSA密钥对的构造器  
            RsaKeyPairGenerator keyGenerator = new RsaKeyPairGenerator();
            //RSA密钥构造器的参数  
            RsaKeyGenerationParameters param = new RsaKeyGenerationParameters(
                Org.BouncyCastle.Math.BigInteger.ValueOf(3),
                new Org.BouncyCastle.Security.SecureRandom(),
                1024,   //密钥长度  
                25);
            //用参数初始化密钥构造器  
            keyGenerator.Init(param);
            //产生密钥对  
            AsymmetricCipherKeyPair keyPair = keyGenerator.GenerateKeyPair();
            //获取公钥和密钥  
            AsymmetricKeyParameter publicKey = keyPair.Public;
            AsymmetricKeyParameter privateKey = keyPair.Private;

            SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);
            PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);

            Asn1Object asn1ObjectPublic = subjectPublicKeyInfo.ToAsn1Object();

            byte[] publicInfoByte = asn1ObjectPublic.GetEncoded("UTF-8");
            Asn1Object asn1ObjectPrivate = privateKeyInfo.ToAsn1Object();
            byte[] privateInfoByte = asn1ObjectPrivate.GetEncoded("UTF-8");

            RSAKEY item = new RSAKEY()
            {
                PublicKey = Convert.ToBase64String(publicInfoByte),
                PrivateKey = Convert.ToBase64String(privateInfoByte)
            };
            return item;
        }
        /*获取公钥数据*/
        private AsymmetricKeyParameter GetPublicKeyParameter(string s)
        {
            s = s.Replace("\r", "").Replace("\n", "").Replace(" ", "");
            byte[] publicInfoByte = Convert.FromBase64String(s);
            Asn1Object pubKeyObj = Asn1Object.FromByteArray(publicInfoByte);//这里也可以从流中读取,从本地导入   
            AsymmetricKeyParameter pubKey = PublicKeyFactory.CreateKey(publicInfoByte);
            return pubKey;
        }
        /*获取私钥数据*/
        private AsymmetricKeyParameter GetPrivateKeyParameter(string s)
        {
            s = s.Replace("\r", "").Replace("\n", "").Replace(" ", "");
            byte[] privateInfoByte = Convert.FromBase64String(s);
            // Asn1Object priKeyObj = Asn1Object.FromByteArray(privateInfoByte);//这里也可以从流中读取,从本地导入   
            // PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);
            AsymmetricKeyParameter priKey = PrivateKeyFactory.CreateKey(privateInfoByte);
            return priKey;
        }
        /*私钥加密*/
        public string EncryptByPrivateKey(string s, string key)
        {
            //非对称加密算法,加解密用  
            IAsymmetricBlockCipher engine = new Pkcs1Encoding(new RsaEngine());
            //加密  
            try
            {
                engine.Init(true, GetPrivateKeyParameter(key));
                byte[] byteData = System.Text.Encoding.UTF8.GetBytes(s);
                var ResultData = engine.ProcessBlock(byteData, 0, byteData.Length);
                return Convert.ToBase64String(ResultData);
                //Console.WriteLine("密文(base64编码):" + Convert.ToBase64String(testData) + Environment.NewLine);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        /*私钥解密*/
        public string DecryptByPrivateKey(string s, string key)
        {
            //非对称加密算法,加解密用  
            IAsymmetricBlockCipher engine = new Pkcs1Encoding(new RsaEngine());
            //解密
            try
            {
                engine.Init(false, GetPrivateKeyParameter(key));
                byte[] byteData = Convert.FromBase64String(s);
                var ResultData = engine.ProcessBlock(byteData, 0, byteData.Length);
                return System.Text.Encoding.UTF8.GetString(ResultData);

                //Console.WriteLine("密文(base64编码):" + Convert.ToBase64String(testData) + Environment.NewLine);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        /*公钥加密*/
        public string EncryptByPublicKey(string s, string key)
        {            
            //非对称加密算法,加解密用  
            IAsymmetricBlockCipher engine = new Pkcs1Encoding(new RsaEngine());
            //加密  
            try
            {
                engine.Init(true, GetPublicKeyParameter(key));
                byte[] byteData = System.Text.Encoding.UTF8.GetBytes(s);
                var ResultData = engine.ProcessBlock(byteData, 0, byteData.Length);
                return Convert.ToBase64String(ResultData);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        /*公钥解密*/
        public string DecryptByPublicKey(string s, string key)
        {
            s = s.Replace("\r", "").Replace("\n", "").Replace(" ", "");
            //非对称加密算法,加解密用  
            IAsymmetricBlockCipher engine = new Pkcs1Encoding(new RsaEngine());
            //解密  
            try
            {
                engine.Init(false, GetPublicKeyParameter(key));
                byte[] byteData = Convert.FromBase64String(s);
                var ResultData = engine.ProcessBlock(byteData, 0, byteData.Length);
                return System.Text.Encoding.UTF8.GetString(ResultData);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        static void Main(string[] args)
		{
            Program pr = new Program();

            /*私钥解密*/
            //string s = "KRbcmSksh303L7InqtyDSndJTxx/20e3tHIRsVB6H/kbZzsKwgKSx7B8LeoVkK1kexnJ5ABzEUUwMeNnxq1eR60kaVDRmAwGxhLZOZIB6prp/aicZZJhSmGNx7qeSAP2mT79e4HYKBWsOi9rm0/WtuoP1BlJXXMb2zPWlkwDYosabsU/+lp7mpH9uujtd+2PL+Trqt4IcCH7ooP3jzC2W0KtjRTGa8nxaIsLRTAr7p4tzEjB/pj6ECy7V0PQYH7kQxnnlMc8tTfahYJbdiElVh2kx3qWAlwjbdml5DNZG2We2ScXAjEhyFOlRytDHydzLonuUqVVs7xPHTAzQ+9pgQ==";
            //string key = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAIQgnpsSRKSfY2phifDVJt/YAHJOokywePq868hhOMmjYK3wk2wQx5hTaALvugULzWCI0DG58u+1Mq4O62JBg2lrpO4LhpkT6YPFt4ylfO7ZKjd28bW/fxX052b4jjn+XzzOyjEH8Ei3LDcO5D7mCNorAFCcJoTbDgY7vWsoq0FHAgMBAAECgYBgz1HHB5yaDlsWcD9U4ajpLGgvWORcUpViCpisKmgkffvxlqs97BGCz+IO/L2MwvgJelUpijixYE+w7yeSx7PTtB7av8iP9AidB1CDFhOjgTox+5VRxpPFXI1IKFyFYGB3OJxr9RSJ3KRdUx1KSkwE+odeVgZBQA/Kc4DAdVNL4QJBAM3L4/hnfS5lZNZqBR13IeUnk6Hz1Nu7Hww3yzd6T2EtizrTGZk78ufGZnN4bFiLCB9BCW4vDSXhsPSobrPOhrcCQQCkXA4LBZAq1x3y6h8NXmGPzQiM9xx6MvNBXLLjZuSck5fSi4U57u+x53hruYtRsIN8xchpYUe/D/fg3uVRjgnxAkAF30F7/wf1YPNFovTOaG3RKhXuUxTJyEcUhCsKRDUroq8MWKWsV6eQsXqO5OrChAURTzvDpxgK8qun735pJwV1AkAdjjQ0RS7UlVRcXz9wPv2aR0t3VeR4EPtvUIUWoWUQxvWxNceiUFYoDrC35mioKu6qHELauFSXhf6UIGDqVnlxAkBk/BGnEBjmX7EYFqbJJDirbTtUG/nOpNJxfOTms6+O5CkAblfEh0JHPWn3TTFBSpZaMt/6jESilsmlnlsZ8zL4"; 
            //string result = pr.DecryptByPrivateKey(s, key);

            /*公钥加密*/
            string s = "helloworld";
            string key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCEIJ6bEkSkn2NqYYnw1Sbf2AByTqJMsHj6vOvIYTjJo2Ct8JNsEMeYU2gC77oFC81giNAxufLvtTKuDutiQYNpa6TuC4aZE+mDxbeMpXzu2So3dvG1v38V9Odm+I45/l88zsoxB/BItyw3DuQ+5gjaKwBQnCaE2w4GO71rKKtBRwIDAQAB";
            string result = pr.EncryptByPublicKey(s, key);
            Console.WriteLine(result);
        }
	}
}

参考:https://www.cnblogs.com/lhxsoft/p/10801158.html

由于RSA加密有长度限制,一般是根据密钥长度来确定,比如1024位密钥,那最长加密长度就是1024/8-11=127字节数据。

于是,在此基础上,进行循环加解密,即可解决加密长度限制的问题。

 

上源码:

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text.RegularExpressions;
using System.Runtime;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Web;
using System.Diagnostics;

using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Pkcs;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Crypto.Encodings;

namespace FileApplication
{    
    class Program
	{                
        /// <summary>
        /// KEY 结构体
        /// </summary>
        public struct RSAKEY
        {
            /// <summary>
            /// 公钥
            /// </summary>
            public string PublicKey { get; set; }
            /// <summary>
            /// 私钥
            /// </summary>
            public string PrivateKey { get; set; }
        }
        public RSAKEY GetKey()
        {
            //RSA密钥对的构造器  
            RsaKeyPairGenerator keyGenerator = new RsaKeyPairGenerator();
            //RSA密钥构造器的参数  
            RsaKeyGenerationParameters param = new RsaKeyGenerationParameters(
                Org.BouncyCastle.Math.BigInteger.ValueOf(3),
                new Org.BouncyCastle.Security.SecureRandom(),
                1024,   //密钥长度  
                25);
            //用参数初始化密钥构造器  
            keyGenerator.Init(param);
            //产生密钥对  
            AsymmetricCipherKeyPair keyPair = keyGenerator.GenerateKeyPair();
            //获取公钥和密钥  
            AsymmetricKeyParameter publicKey = keyPair.Public;
            AsymmetricKeyParameter privateKey = keyPair.Private;

            SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(publicKey);
            PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);

            Asn1Object asn1ObjectPublic = subjectPublicKeyInfo.ToAsn1Object();

            byte[] publicInfoByte = asn1ObjectPublic.GetEncoded("UTF-8");
            Asn1Object asn1ObjectPrivate = privateKeyInfo.ToAsn1Object();
            byte[] privateInfoByte = asn1ObjectPrivate.GetEncoded("UTF-8");

            RSAKEY item = new RSAKEY()
            {
                PublicKey = Convert.ToBase64String(publicInfoByte),
                PrivateKey = Convert.ToBase64String(privateInfoByte)
            };
            return item;
        }
        /*获取公钥数据*/
        private AsymmetricKeyParameter GetPublicKeyParameter(string s)
        {
            s = s.Replace("\r", "").Replace("\n", "").Replace(" ", "");
            byte[] publicInfoByte = Convert.FromBase64String(s);
            Asn1Object pubKeyObj = Asn1Object.FromByteArray(publicInfoByte);//这里也可以从流中读取,从本地导入   
            AsymmetricKeyParameter pubKey = PublicKeyFactory.CreateKey(publicInfoByte);
            return pubKey;
        }
        /*获取私钥数据*/
        private AsymmetricKeyParameter GetPrivateKeyParameter(string s)
        {
            s = s.Replace("\r", "").Replace("\n", "").Replace(" ", "");
            byte[] privateInfoByte = Convert.FromBase64String(s);
            // Asn1Object priKeyObj = Asn1Object.FromByteArray(privateInfoByte);//这里也可以从流中读取,从本地导入   
            // PrivateKeyInfo privateKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(privateKey);
            AsymmetricKeyParameter priKey = PrivateKeyFactory.CreateKey(privateInfoByte);
            return priKey;
        }        
        
        /*私钥解密,支持分段解密*/
        public string DecryptByPrivateKey(string in_plain, string key)
        {
            //非对称加密算法,加解密用  
            IAsymmetricBlockCipher engine = new Pkcs1Encoding(new RsaEngine());
            //加密  
            try
            {                
                int CryLen = 1024;  /*密钥长度为1024位*/
                int bufferSize = CryLen / 8 ;   /*每段密文的长度*/

                /*存放base64解码后的字节数据*/
                byte[] encryptData = Convert.FromBase64String(in_plain);                
                byte[] dencryContent = null;
                if (encryptData == null || encryptData.Length <= 0)
                {
                    Console.WriteLine("Error");
                    throw new NotSupportedException();
                }

                /*存放分段初始字节数据*/
                byte[] buffer = new byte[bufferSize];              
                using (MemoryStream input = new MemoryStream(encryptData))
                    using (MemoryStream output = new MemoryStream())
                {
                    while (true)
                    {
                        int readLine = input.Read(buffer, 0, bufferSize);
                        if (readLine <= 0)
                        {
                            break;
                        }
                        byte[] temp = new byte[readLine];
                        Array.Copy(buffer, 0, temp, 0, readLine);
                        byte[] decrypt = rsa_private_decrypt(engine, temp, key);                                               
                        output.Write(decrypt, 0, decrypt.Length);
                        
                    }
                    dencryContent = output.ToArray();                  
                }               
                return Encoding.UTF8.GetString(dencryContent);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        /*私钥解密,最小长度解密*/
        public byte[] rsa_private_decrypt(IAsymmetricBlockCipher engine,
            byte[] str, string key)
        {           
            //解密
            try
            {
                /*BouncyCastle 解密初始化*/
                engine.Init(false, GetPrivateKeyParameter(key));
                byte[] ResultData = engine.ProcessBlock(str, 0, str.Length);               
                return ResultData;                
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        /*公钥加密,支持分段加密*/
        public string EncryptByPublicKey(string in_plain, string key)
        {            
            //非对称加密算法,加解密用  
            IAsymmetricBlockCipher engine = new Pkcs1Encoding(new RsaEngine());
            //加密  
            try
            {                                          
                int CryLen = 1024;  /*密钥长度为1024位*/
                int bufferSize = CryLen / 8 - 11;   /*通过加密长度获取明文的最大加密长度*/
                int cipherLen = CryLen / 8;    /*通过加密长度获取密文的长度*/

                /*存放加密后的数据*/
                byte[] encryContent = null;
                /*初始字节数据*/
                byte[] originalData = Encoding.UTF8.GetBytes(in_plain);
                /*存放分段初始字节数据*/
                byte[] buffer = new byte[bufferSize];

                using (MemoryStream input = new MemoryStream(originalData))
                using (MemoryStream ouput = new MemoryStream())
                {
                    while (true)
                    {
                        /*每次读bufferSize字节的数据存放到buffer中*/
                        int readLine = input.Read(buffer, 0, bufferSize);
                        if (readLine <= 0)
                        {
                            break;
                        }
                        byte[] temp = new byte[readLine];
                        /*复制buffer中的数据到temp中*/
                        Array.Copy(buffer, 0, temp, 0, readLine);
                        //byte[] encrypt = rsa.Encrypt(temp, false);
                        /*加密数据,返回加密后的字节数据*/
                        byte[] encrypt = rsa_public_encrypt(engine, temp, key);
                        ouput.Write(encrypt, 0, encrypt.Length);
                    }
                    encryContent = ouput.ToArray();
                }
                return Convert.ToBase64String(encryContent);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        /*公钥最小长度加密*/
        public byte[] rsa_public_encrypt(IAsymmetricBlockCipher engine,
            byte[] str, string key)
        {
            try
            {
                engine.Init(true, GetPublicKeyParameter(key));                
                byte[] ResultData = engine.ProcessBlock(str, 0, str.Length);
                return ResultData;               
            }
            catch (Exception ex)
            {
                return null;
            }
        }                
        static void Main(string[] args)
		{
            Program pr = new Program();

            /*公钥加密*/
            //string s = "xiadeliang111xiadeliang111xiadeliang111xiadeliang111xiadeliang111xiadeliang111xiadeliang111xiadeliang111xiadeliang111xiadeliang111xiadeliang111xiadeliang111";
            //string s = "xiadeliang";
            //string key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCEIJ6bEkSkn2NqYYnw1Sbf2AByTqJMsHj6vOvIYTjJo2Ct8JNsEMeYU2gC77oFC81giNAxufLvtTKuDutiQYNpa6TuC4aZE+mDxbeMpXzu2So3dvG1v38V9Odm+I45/l88zsoxB/BItyw3DuQ+5gjaKwBQnCaE2w4GO71rKKtBRwIDAQAB";
            //string result = pr.EncryptByPublicKey(s, key);

            /*私钥解密*/
            string s = "BBVpxSMkIf2ZCWp/AKaJxR2S6nw9+3RA1RdRiSSKRgaQdY+hsDyIAVvUSaTapxbVrlPleQ9QOFOLqvS5nO5FMVlCXcuv3IRoU88RVNHMWyImcXB1bDLyBFKXz/alm/ofBEmeLvPLlc52H/qwzOpzqcU95FZ6qIVaI8XFgufGeiRii9Mcj5xpKbVFCzRKzi6r3Kcb8AiVIGgGwDz9HVE7/270FaFH0/tkmi+fmdIhpRb0X/TpFwDl3gwsOmQIXOxnYxjgCweDj+OVLoq5CcwZPft8KPgMKVZXsa0MJSTqh3Fs+hS1zZsLKLRpr6lZNicgR3NEl4UMZ2C3UX/fVOFKWQ==";
            string key = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAIQgnpsSRKSfY2phifDVJt/YAHJOokywePq868hhOMmjYK3wk2wQx5hTaALvugULzWCI0DG58u+1Mq4O62JBg2lrpO4LhpkT6YPFt4ylfO7ZKjd28bW/fxX052b4jjn+XzzOyjEH8Ei3LDcO5D7mCNorAFCcJoTbDgY7vWsoq0FHAgMBAAECgYBgz1HHB5yaDlsWcD9U4ajpLGgvWORcUpViCpisKmgkffvxlqs97BGCz+IO/L2MwvgJelUpijixYE+w7yeSx7PTtB7av8iP9AidB1CDFhOjgTox+5VRxpPFXI1IKFyFYGB3OJxr9RSJ3KRdUx1KSkwE+odeVgZBQA/Kc4DAdVNL4QJBAM3L4/hnfS5lZNZqBR13IeUnk6Hz1Nu7Hww3yzd6T2EtizrTGZk78ufGZnN4bFiLCB9BCW4vDSXhsPSobrPOhrcCQQCkXA4LBZAq1x3y6h8NXmGPzQiM9xx6MvNBXLLjZuSck5fSi4U57u+x53hruYtRsIN8xchpYUe/D/fg3uVRjgnxAkAF30F7/wf1YPNFovTOaG3RKhXuUxTJyEcUhCsKRDUroq8MWKWsV6eQsXqO5OrChAURTzvDpxgK8qun735pJwV1AkAdjjQ0RS7UlVRcXz9wPv2aR0t3VeR4EPtvUIUWoWUQxvWxNceiUFYoDrC35mioKu6qHELauFSXhf6UIGDqVnlxAkBk/BGnEBjmX7EYFqbJJDirbTtUG/nOpNJxfOTms6+O5CkAblfEh0JHPWn3TTFBSpZaMt/6jESilsmlnlsZ8zL4"; 
            string result = pr.DecryptByPrivateKey(s, key);
            
            Console.WriteLine(result);
        }
	}
}

与JAVA端进行对接时,注意密钥文件的一致性,同时确定好加密算法的填充模式。

参考:

https://blog.csdn.net/lengyue2015/article/details/86582177

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值