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

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

    • C#基础加密解密
    • C# 私钥加密公钥解密

最近接了个包,用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 = "";


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

        /// 
        /// 解密
        /// 
        /// 待解密信息
        /// 解密信息
        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;
        }

        /// 
        /// 加密
        /// 
        /// 待加密信息
        /// 已加密信息
        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 = "";


        /// 
        /// KEY 结构体
        /// 
        public struct RSAKEY
        {
            /// 
            /// 公钥
            /// 
            public string PublicKey
            {
                get;
                set;
            }
            /// 
            /// 私钥
            /// 
            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,就这了!!

你可能感兴趣的:(unity开发,c#,加密解密,unity)