RSA利用公钥解密,私钥加密(一般是公钥加密,私钥解密),以及AES加解密算法,,

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;
using System.Security.Cryptography;
using System.IO;

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("-----BEGIN PUBLIC KEY-----", "");
            s = s.Replace("-----END PUBLIC KEY-----", "");
            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;

            //}
        }


        /// <summary>
        /// RSA公钥解密
        /// </summary>
        /// <param name="s"></param>
        /// <param name="publicKeyString"></param>
        /// <returns></returns>
        public static string DecryptByPublicKey(string s, string publicKeyString)
        {
            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;

            //}
        }



        /// <summary>
        /// AES解密使用
        /// </summary>
        /// <param name="str"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string AesDecrypt(string str, string key)
        {
            if (string.IsNullOrEmpty(str)) return null;
            byte[] toEncryptArray = HexToByteArray(str);

            RijndaelManaged rm = new RijndaelManaged
            {
                Key = Encoding.UTF8.GetBytes(key),
                Mode = CipherMode.ECB,
                Padding = PaddingMode.PKCS7
            };

            ICryptoTransform cTransform = rm.CreateDecryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            return Encoding.UTF8.GetString(resultArray);
        }

        private static byte[] HexToByteArray(string hex)
        {
            int len = hex.Length / 2;
            byte[] result = new byte[len];
            for (int i = 0; i < len; i++)
            {
                result[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
            }
            return result;
        }


        /// <summary>
        ///  AES加密使用
        /// </summary>
        /// <param name="str"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string AesEncrypt(string str, string key)
        {
            if (string.IsNullOrEmpty(str)) return null;
            byte[] toEncryptArray = Encoding.UTF8.GetBytes(str);

            RijndaelManaged rm = new RijndaelManaged
            {
                Key = Encoding.UTF8.GetBytes(key),
                Mode = CipherMode.ECB,
                Padding = PaddingMode.PKCS7
            };

            ICryptoTransform cTransform = rm.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            return ByteArrayToHex(resultArray);
        }

        private static string ByteArrayToHex(byte[] bytes)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < bytes.Length; i++)
            {
                sb.Append(bytes[i].ToString("X2"));
            }
            return sb.ToString();
        }

    }
}

下面是引用实例,

using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
using System.Security.Cryptography;
using XGPass;

public class ICT_Data : MonoBehaviour
{
    public string App_ID;

    public string Ticket;

    public string SecretKey;

    public string token;

    [Header("ip地址")]
    public string ipaddress;

    [Header("token的接口")]
    public string GetTken;

    [Header("步骤请求接口")]
    public string RequstStep;

    [Header("任务请求接口")]
    public string RequstTask;

    [Header("密钥获取接口")]
    public string Secret;

    [Header("获取任务信息")]
    public string GetCourseTaskList;

    [Header("获取任务下的步骤信息")]
    public string GetCourseStepList;

    [Header("RSA加密AES密钥解密后")]
    public string AESSecretKeY;  //加密钥匙

    [Header("AES业务逻辑加解密密匙")]
    public string AESKey;


相关推荐

最近更新

  1. TCP协议是安全的吗?

    2024-06-18 10:58:01       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-18 10:58:01       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-18 10:58:01       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-18 10:58:01       18 阅读

热门阅读

  1. 面试计算机网络八股文十问十答第十期

    2024-06-18 10:58:01       9 阅读
  2. 腾讯云点播ugc upload | lack signature 问题处理

    2024-06-18 10:58:01       8 阅读
  3. Redis 五种基本数据类型及场景

    2024-06-18 10:58:01       8 阅读
  4. 在Elasticsearch中添加字段

    2024-06-18 10:58:01       7 阅读
  5. Spring框架对BeanUtils.copyProperties的优化

    2024-06-18 10:58:01       7 阅读
  6. MySQL触发器基本结构

    2024-06-18 10:58:01       9 阅读
  7. Ubuntu系列-fzf最新版安装

    2024-06-18 10:58:01       9 阅读
  8. CSS外部样式

    2024-06-18 10:58:01       7 阅读
  9. Mysql中的函数

    2024-06-18 10:58:01       8 阅读
  10. Node.js 入门:

    2024-06-18 10:58:01       10 阅读
  11. Node.js 教程

    2024-06-18 10:58:01       7 阅读
  12. Nginx负载均衡之动态更新upstream

    2024-06-18 10:58:01       10 阅读