天天看點

【ASP.NET】RSA加密,前端加密,後端解密,有效哦!

流程:

第一步:傳回publicKey前端,用來對password等敏感字段的加密。

第二步:前端進行password敏感字段的加密。

第三步:post資料給後端。

第四步:用privateKey進行解密。

一、相關JS包和引用BIN檔案,下載下傳連結:

https://download.csdn.net/download/u012949335/20389382

二、前端如下:

<div class="from">
                    <div class="from-group">
                        <input type="text" class="inputtext width280" id="UserId" name="UserId" placeholder="請輸入使用者名" />
                    </div>
                    <div class="from-group">
                        <input type="password" class="inputtext width280" id="Password" name="Password" placeholder="請輸入密碼" />
                    </div>
                    <div class="from-group">
                        <input type="text" class="inputtext width160" id="VeriCode" name="VeriCode" placeholder="請輸入驗證碼" />
                        <img id="imgVerifi" title="單擊換一張驗證碼" class="inputimage" src="verificationcode" onclick="changecode()" />
                    </div>
                    <div class="from-group">
                        <button id="btnlogin" class="btn" onclick="loginform(); return false">登 錄</button>
                    </div>
                   <input id="pubkey" type="hidden" value='@ViewBag.pubkey' />
                </div>
           
<script type="text/javascript">
   
    function loginform() {
        var info = new Object();
        info.UserId = $("#UserId").val();
        var EncryptPwd = $("#Password").val();

        var rsa = new JSEncrypt();
        var pubkey = $("#pubkey").val();
        rsa.setPublicKey(pubkey);
        var rsa_p = rsa.encrypt(EncryptPwd);
        info.Password = rsa_p;

        info.VeriCode = $("#VeriCode").val();
        var jsonObject = JSON.stringify(info);
        $.ajax({
            type: 'post',
            url: "Login",
            dataType: "json", //傳回json格式的資料
            data: { 'json': jsonObject },
            cache: false,
            success: function (data) {
                if (data.jg == "1") {
                    
                }
                else {
                }
            },
            error: function (e) {
                var msg = responseTextTitle(e.responseText);
                $.messager.alert("提示", msg, "error");
            }
        });
    }

</script>
           

三、後端如下:

[AllowAnonymous]
        public ActionResult Login()
        {
            List<string> keys = Common.Common.CreateKeyPair();
            ViewBag.pubkey = keys[0];
            Session["publickey"] = keys[0];
            Session["privatekey"] = keys[1];
            return View();
        }
           
/// <summary>
        /// 登陸
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ActionResult Login(string json)
        {
            LoginModel model = new LoginModel();
            model = JsonUtility.Json2Info<LoginModel>(json);
            Dictionary<String, Object> jsonMap = new Dictionary<String, Object>(); 
            string rejson = string.Empty;  

            var privatekey = Session["privatekey"].ToString();
            var Password = Common.Common.Decrypt(privatekey, model.Password);
            model.Password = Password;
            model.UserId = model.UserId.Trim();
            string msg = "";
            BLL.sys_user dal = new BLL.sys_user();
            if (dal.DoLogin(model, out msg))
            {
                jsonMap.Add("jg", "1");
                rejson = JsonUtility.Info2Json(jsonMap);
                return Content(rejson);
            }
            else
            {
                jsonMap.Add("jg", "0");
                jsonMap.Add("msg", msg);
                rejson = JsonUtility.Info2Json(jsonMap);
                return Content(rejson);
            }

        }
           
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Crypto.Encodings;
using Org.BouncyCastle.Crypto.Engines;


namespace YidiKy.Common
{
    public class Common{
        
            #region 公鑰和私鑰加解密
        /// <summary>
        /// 随機擷取公鑰和私鑰的字元
        /// </summary>
        /// <param name="strength">長度</param>
        /// <returns></returns>
        public static List<string> CreateKeyPair(int strength = 1024)
        {
            RsaKeyPairGenerator r = new RsaKeyPairGenerator();
            r.Init(new KeyGenerationParameters(new SecureRandom(), strength));
            AsymmetricCipherKeyPair keys = r.GenerateKeyPair();

            TextWriter privateTextWriter = new StringWriter();
            PemWriter privatePemWriter = new PemWriter(privateTextWriter);
            privatePemWriter.WriteObject(keys.Private);
            privatePemWriter.Writer.Flush();


            TextWriter publicTextWriter = new StringWriter();
            PemWriter publicPemWriter = new PemWriter(publicTextWriter);
            publicPemWriter.WriteObject(keys.Public);
            publicPemWriter.Writer.Flush();
            List<string> revalue = new List<string>();
            revalue.Add(publicTextWriter.ToString());
            revalue.Add(privateTextWriter.ToString());
            return revalue;
        }


        /// <summary>
        /// RSA加密 将公鑰導入到RSA對象中,準備加密
        /// </summary>
        /// <param name="PublicKey">公鑰</param>
        /// <param name="encryptstring">待加密的字元串</param>
        public static string RSAEncrypt(string PublicKey, string encryptstring)
        {
            using (TextReader reader = new StringReader(PublicKey))
            {
                dynamic key = new PemReader(reader).ReadObject();
                var rsaDecrypt = new Pkcs1Encoding(new RsaEngine());

                if (key is AsymmetricKeyParameter)
                {
                    key = (AsymmetricKeyParameter)key;
                }
                else if (key is AsymmetricCipherKeyPair)
                {
                    key = ((AsymmetricCipherKeyPair)key).Private;
                }
                rsaDecrypt.Init(true, key);  //這裡加密是true;解密是false  
                byte[] DataToEncrypt = Encoding.UTF8.GetBytes(encryptstring);
                byte[] outBytes = rsaDecrypt.ProcessBlock(DataToEncrypt, 0, DataToEncrypt.Length);//加密
                string strBase64 = Convert.ToBase64String(outBytes);
                return strBase64;
            }
        }
        /// <summary>
        /// RSA加密 将私鑰導入到RSA對象中,準備解密
        /// </summary>
        /// <param name="privateKey">私鑰</param>
        /// <param name="decryptstring">待解密的字元串</param>
        /// <returns></returns>
        public static string Decrypt(string privateKey, string decryptstring)
        {
            using (TextReader reader = new StringReader(privateKey))
            {
                dynamic key = new PemReader(reader).ReadObject();
                var rsaDecrypt = new Pkcs1Encoding(new RsaEngine());
                if (key is AsymmetricKeyParameter)
                {
                    key = (AsymmetricKeyParameter)key;
                }
                else if (key is AsymmetricCipherKeyPair)
                {
                    key = ((AsymmetricCipherKeyPair)key).Private;
                }
                rsaDecrypt.Init(false, key);  //這裡加密是true;解密是false  

                byte[] entData = Convert.FromBase64String(decryptstring);
                entData = rsaDecrypt.ProcessBlock(entData, 0, entData.Length);
                return Encoding.UTF8.GetString(entData);
            }
        }

        #endregion


    }
}