Unity -C# RSA加密解密 公钥加密私钥解密,私钥加密公钥解密

Unity -C# RSA加密解密 公钥加密私钥解密,私钥加密公钥解密

最近接了个包,用unity做的,但是客户有安全考虑,需要用到rsa加密解密,作为一个直接从unity入行的程序员,神TM知道RSA是什么,只能一点点百度,一点点查,然后就发现了一堆坑…

C#基础加密解密

查过资料以后发现,C#本身只支持公钥加密,私钥解密
还好,那就开始做,然后密钥形式支持pem和xml都可,说是这样说,但是我的工程里,对接的是php的大佬,然后pem这个没搞定,但是xml就搞定了。。这我就放着了,由于php给我的是pem,我只好一不小心找到一个工具:
这个是个通用工具,具体情况还需要具体分析
引用这位大佬的文章,有兴趣的可以看看代码
https://www.cnblogs.com/jaamy/p/6118814.html
xml 与 pem互转的工具.

由于我用的是1024的,所以分段加密117,解密128 ,2048的自己改
有了这两个基础,公钥加密私钥解密就可以了

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Security.Cryptography;
using System;
using System.Text;
using System.Linq;

namespace XGPass
{
    public class RSAInstance : MonoBehaviour
    {
        private static readonly string privateKeyXml = "";
        private static readonly string publicKeyXml = "";


        /// <summary>
        /// 生成一对公钥和私钥,xml
        /// </summary>
        /// <returns></returns>
        public KeyValuePair<string, string> GetKeyPairXML()
        {
            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
            string public_Key = RSA.ToXmlString(false);
            string private_Key = RSA.ToXmlString(true);
            return new KeyValuePair<string, string>(public_Key, private_Key);
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="info">待解密信息</param>
        /// <returns>解密信息</returns>
        public static string DecryptXml(string info)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(privateKeyXml);

            byte[] byteData = Convert.FromBase64String(info);
            string result = "";

            for (int i = 0, j = byteData.Length / 128 + (byteData.Length % 128 == 0 ? 0 : 1); i < j; i++)
            {
                //Debug.Log(i);
                byte[] getData = byteData.Skip(i * 128).Take(128).ToArray();
                string itStr = Encoding.UTF8.GetString(rsa.Decrypt(getData, false));
                result += itStr;
            }
            return result;
        }

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="info">待加密信息</param>
        /// <returns>已加密信息</returns>
        public static string EncryptXml(string info)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(publicKeyXml);

            byte[] byteData = Encoding.UTF8.GetBytes(info);
            byte[] result = new byte[] { };

            for (int i = 0, j = byteData.Length / 117 + (byteData.Length % 117 == 0 ? 0 : 1); i < j; i++)
            {
                byte[] getData = byteData.Skip(i * 117).Take(117).ToArray();
                byte[] ResultData = rsa.Encrypt(getData,false);
                result = result.Concat(ResultData).ToArray();
            }
            return Convert.ToBase64String(result);
        }
    }
}

C# 私钥加密公钥解密

之前只需要我加密信息发过去,然后传回来的信息没有加密,我可以直接进行处理,那么问题来了,突然对传回的信息也要加密,那本地只有公钥,C#这个坑就大了,我只好查资料,翻文档,到处找,Biginteger这个说的比较多,我就去试,试来试去,行吧,原理大概看懂了,就是不顶用。。。然后又查,之前也查到了BouncyCastle这个dll的写法,但是还是没成功,好吧,我菜。睡了一觉,心情不是很好的继续寻找,最终这位大佬解救了我:
https://blog.csdn.net/hezhixiang/article/details/103635877
大家可以先看看大佬的文章
我的与大佬的区别是就加了个分段
这个需要这个dll:BouncyCastle.Crypto.dll
我是复制了大佬的代码,然后通过VS快捷下载了,unity里用的话,还需创建一个Plugins的文件夹,将dll放入这个文件夹

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

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 XGPass
{
    public class RSAForJava
    {
        static readonly string publicKeyString = "";
        static readonly string privateKeyString = "";


        /// <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 static AsymmetricKeyParameter GetPublicKeyParameter(string s)
        {
            s = s.Replace("\r", "").Replace("\n", "").Replace(" ", "");
            byte[] publicInfoByte = Convert.FromBase64String(s);
            AsymmetricKeyParameter pubKey = PublicKeyFactory.CreateKey(publicInfoByte);
            return pubKey;
        }
        private static AsymmetricKeyParameter GetPrivateKeyParameter(string s)
        {
            s = s.Replace("\r", "").Replace("\n", "").Replace(" ", "");
            byte[] privateInfoByte = Convert.FromBase64String(s);
            AsymmetricKeyParameter priKey = PrivateKeyFactory.CreateKey(privateInfoByte);
            return priKey;
        }

        public static string EncryptByPrivateKey(string s)
        {
            //非对称加密算法,加解密用  
            IAsymmetricBlockCipher engine = new Pkcs1Encoding(new RsaEngine());


            //加密  

            //try
            //{
            engine.Init(true, GetPrivateKeyParameter(privateKeyString));
            byte[] byteData = Encoding.UTF8.GetBytes(s);

            byte[] result = new byte[] { };

            for (int i = 0, j = byteData.Length / 117 + (byteData.Length % 117 == 0 ? 0 : 1); i < j; i++)
            {
                byte[] getData = byteData.Skip(i * 117).Take(117).ToArray();
                byte[] ResultData = engine.ProcessBlock(getData, 0, getData.Length);
                result = result.Concat(ResultData).ToArray();
            }

            //var ResultData = engine.ProcessBlock(byteData, 0, byteData.Length);
            return Convert.ToBase64String(result);

            //}
            //catch (Exception ex)
            //{
            //    return ex.Message;

            //}
        }
        public static string DecryptByPublicKey(string s)
        {
            s = s.Replace("\r", "").Replace("\n", "").Replace(" ", "");
            //非对称加密算法,加解密用  
            IAsymmetricBlockCipher engine = new Pkcs1Encoding(new RsaEngine());


            //解密  

            //try
            //{
            engine.Init(false, GetPublicKeyParameter(publicKeyString));
            byte[] byteData = Convert.FromBase64String(s);

            string all = "";

            for (int i = 0, j = byteData.Length / 128 + (byteData.Length % 128 == 0 ? 0 : 1); i < j; i++)
            {
                byte[] getData = byteData.Skip(i * 128).Take(128).ToArray();
                byte[] ResultData = engine.ProcessBlock(getData, 0, getData.Length);
                all += Encoding.UTF8.GetString(ResultData);
            }

            //var ResultData = engine.ProcessBlock(byteData, 0, byteData.Length);
            return all;

            //}
            //catch (Exception ex)
            //{
            //    return ex.Message;

            //}
        }
    }
}

OK,就这了!!

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值