基於C# 的RSA 前端JS加密後端進行解密。

來源:互聯網
上載者:User

標籤:system   back   data   expect   add   new   substr   ...   you   

前端代碼

引用 js : 

http://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;

 解密

 /// <summary>        /// 與前端互動的解密        /// </summary>        /// <param name="DecryptString"></param>        /// <param name="privateKey"></param>        /// <returns></returns>        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;        }

  產生金鑰組

/// <summary>        /// 建立金鑰組        /// </summary>        /// <returns></returns>        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# 的RSA 前端JS加密後端進行解密。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.