C#编程之基于C# 的RSA 前端JS加密后端进行解密
小标 2018-11-14 来源 : 阅读 4976 评论 0

摘要:本文主要向大家介绍了C#编程之基于C# 的RSA 前端JS加密后端进行解密,通过具体的内容向大家展示,希望对大家学习C#编程有所帮助。

本文主要向大家介绍了C#编程之基于C# 的RSA 前端JS加密后端进行解密,通过具体的内容向大家展示,希望对大家学习C#编程有所帮助。

前端代码
引用 js : 
//passport.cnblogs.com/scripts/jsencrypt.min.js通过接口从服务端获取随机一对密钥串,主键为Token

 function GetRSAKey(params, callback) {
        Service.post({
            url: "/BaseService.svc/GetRSAKey",
            params: {
            },
            success: function (response) {
                var encrypt = new JSEncrypt();
                encrypt.setPublicKey(response.PublicKey);
                params = JSON.stringify(params);
                var Encryptdata = encrypt.encrypt(params);
                //+号的处理:因为数据在网络上传输时,非字母数字字符都将被替换成百分号(%)后跟两位十六进制数,
                //而base64编码在传输到后端的时候,+会变成空格,因此先替换掉。后端再替换回来
                Encryptdata = encodeURI(Encryptdata).replace(/\+/g, ‘%2B‘);
                if (callback) {
                    callback(Encryptdata, response.Token);
                }
            }
        });
    }


  将加密后的信息,和加密KEY的主键传回登录接口

GetRSAKey(params, function (Encryptdata, token) {
            Service.post({
                url: "/UserAccountService.svc/SafeInDoor",
                params: {
                    Encryptdata: Encryptdata,
                    Token: token,
                },
                success: function (response) {
                    if (response.Token) {
                       
                    } else {
                        ZENG.msgbox.show(response.StatusText, 5, 2000);
                    }
                },
                error: function (response) {
                },
                mask: function () {
                    $("#J_LoginSub").mask("正在登录,请稍候...");
                },
                unmask: function () {
                    $("#J_LoginSub").unmask();
                }
            });
        })

    }

获取解密Key,对加密信息进行解密

 引用 
using System.Security.Cryptography;using Cn.Ubingo.Security.RSA.Key;
 解密

 /// 


        /// 与前端交互的解密
        /// 


        /// 


        /// 


        /// 


        public string HtmlDecrypt(string DecryptString,string privateKey){
            string result="";
            try
            {
                RSACryptoServiceProvider rsaCryptoServiceProvider = CreateRsaProviderFromPrivateKey(privateKey);
                //把+号,再替换回来
                byte[] res = rsaCryptoServiceProvider.Decrypt(Convert.FromBase64String(DecryptString.Replace("%2B","+")), false);
                result= Encoding.UTF8.GetString(res);
            }
            catch (Exception exception)
            {
                FileLog.AddLog("RSACryptoDecryptRSA解密异常",exception.Message);

            }
            return result;
        }
      


  

 private RSACryptoServiceProvider CreateRsaProviderFromPrivateKey(string privateKey)
        {
            var privateKeyBits = System.Convert.FromBase64String(privateKey);

            var RSA = new RSACryptoServiceProvider();
            var RSAparams = new RSAParameters();

            using (BinaryReader binr = new BinaryReader(new MemoryStream(privateKeyBits)))
            {
                byte bt = 0;
                ushort twobytes = 0;
                twobytes = binr.ReadUInt16();
                if (twobytes == 0x8130)
                    binr.ReadByte();
                else if (twobytes == 0x8230)
                    binr.ReadInt16();
                else
                    throw new Exception("Unexpected value read binr.ReadUInt16()");

                twobytes = binr.ReadUInt16();
                if (twobytes != 0x0102)
                    throw new Exception("Unexpected version");

                bt = binr.ReadByte();
                if (bt != 0x00)
                    throw new Exception("Unexpected value read binr.ReadByte()");

                RSAparams.Modulus = binr.ReadBytes(GetIntegerSize(binr));
                RSAparams.Exponent = binr.ReadBytes(GetIntegerSize(binr));
                RSAparams.D = binr.ReadBytes(GetIntegerSize(binr));
                RSAparams.P = binr.ReadBytes(GetIntegerSize(binr));
                RSAparams.Q = binr.ReadBytes(GetIntegerSize(binr));
                RSAparams.DP = binr.ReadBytes(GetIntegerSize(binr));
                RSAparams.DQ = binr.ReadBytes(GetIntegerSize(binr));
                RSAparams.InverseQ = binr.ReadBytes(GetIntegerSize(binr));
            }

            RSA.ImportParameters(RSAparams);
            return RSA;
        }

        private int GetIntegerSize(BinaryReader binr)
        {
            byte bt = 0;
            byte lowbyte = 0x00;
            byte highbyte = 0x00;
            int count = 0;
            bt = binr.ReadByte();
            if (bt != 0x02)
                return 0;
            bt = binr.ReadByte();

            if (bt == 0x81)
                count = binr.ReadByte();
            else
                if (bt == 0x82)
                {
                    highbyte = binr.ReadByte();
                    lowbyte = binr.ReadByte();
                    byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };
                    count = BitConverter.ToInt32(modint, 0);
                }
                else
                {
                    count = bt;
                }

            while (binr.ReadByte() == 0x00)
            {
                count -= 1;
            }
            binr.BaseStream.Seek(-1, SeekOrigin.Current);
            return count;
        }


  生成密钥对

/// 


        /// 创建密钥对
        /// 


        /// 


        public RSAKey NewRsaKey()
        {
            //RSAKey RSAKey = new RSAKey();
            Chilkat.Rsa rsa = new Chilkat.Rsa();

            bool success = rsa.UnlockComponent("Anything for 30-day trial");
            if (success != true) {
                Console.WriteLine(rsa.LastErrorText);
                return null;
            }

            //  Generate a 2048-bit key.  Chilkat RSA supports
            //  key sizes ranging from 512 bits to 8192 bits.
            success = rsa.GenerateKey(1024);
            if (success != true)
            {
                Console.WriteLine(rsa.LastErrorText);
                return null;
            }

            //  Get the public and private key parts:
            Chilkat.PublicKey pubKey = rsa.ExportPublicKeyObj();
            Chilkat.PrivateKey privKey = rsa.ExportPrivateKeyObj();

            //  Get the public key as a PKCS8 PEM string
            //string pubKeyPem = pubKey.GetOpenSslPem();
            //Console.WriteLine(pubKeyPem);

            //  Get the public key in PKCS8 format, in a Base64 encoded string.
            string PublicKey = pubKey.GetPkcs8ENC("base64");
            //Console.WriteLine(pubKeyPkcs8Base64);

            //  Get the public key in PKCS1 format, in a Base64 encoded string.
            //string PublicKey = pubKey.GetPkcs1ENC("base64");
            //Console.WriteLine(pubKeyPkcs1Base64);

            //  Get the private key in a PKCS8 PEM string.
            //string privKeyPem = privKey.GetPkcs8Pem();
            //Console.WriteLine(privKeyPem);

            //  Get the private key in a PKCS8 encrypted PEM string.
            //string privKeyEncPem = privKey.GetPkcs8EncryptedPem("myPassword");
            //Console.WriteLine(privKeyEncPem);

            //  Get the private key in PKCS1 Base64 format
            string PrivateKey = privKey.GetPkcs1ENC("base64");
            //Console.WriteLine(privKeyPkcs1Base64);

            //  Get the private key in PKCS8 Base64 format
            //string privKeyPkcs8Base64 = privKey.GetPkcs8ENC("base64");
            //Console.WriteLine(privKeyPkcs8Base64);

            RSAKey RSAKey = new RSAKey();
            RSAKey.PrivateKey = PrivateKey;
            RSAKey.PublicKey = PublicKey;
            RSAKey.token = Guid.NewGuid();
            return RSAKey;
            //  Save to PKCS1 / PKCS8 / PEM files...

            //  Save the public key to PKCS8 binary DER
            //  Note: Chilkat is confusingly using the substring "OpenSsl" in the method name.
            //  A better choice would‘ve been "SavePkcs8DerFile". When you see "OpenSsl" referring to
            //  a key format in a Chilkat method name, assume "PKCS8".
            //success = pubKey.SaveOpenSslDerFile("pubKey_pkcs8.der");

            //  Save the public key to PKCS1 binary DER
            //success = pubKey.SaveRsaDerFile("pubKey_pkcs1.der");

            //  Save the private key to unencrypted binary PKCS1 DER.
            //  Note: PKCS1 is never found in an encrypted format.
            //success = privKey.SaveRsaDerFile("privKey_pkcs1.der");

            //  Save the private key to unencrypted binary PKCS8
            //success = privKey.SavePkcs8File("privKey_pkcs8.der");

            //  Save the private key to encrypted binary PKCS8
           // success = privKey.SavePkcs8EncryptedFile("myPassword", "privKey_enc_pkcs8.der");

            //  Save the private key to unencrypted PKCS8 PEM
            //success = privKey.SavePkcs8PemFile("privKey.pem");

            //  Save the private key to encrypted PKCS8 PEM
            //success = privKey.SavePkcs8EncryptedPemFile("myPassword", "privKey_enc.pem");
        }

本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标编程语言C#.NET频道!

本文由 @小标 发布于职坐标。未经许可,禁止转载。
喜欢 | 1 不喜欢 | 0
看完这篇文章有何感觉?已经有1人表态,100%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    

©2015 www.zhizuobiao.com All Rights Reserved

208小时内训课程