使用jsencrypt.js實現前端加密女器,C#后端解密

在分享源碼之前诀蓉,先準備一些東西:
1、下載一個js加密幫助文件癣漆,下載地址:https://passport.cnblogs.com/scripts/jsencrypt.min.js维咸,在項目中以JavaScript.js保存,以方便引用:<script type="text/javascript" src="JavaScript.js"></script>惠爽,當然了癌蓖,也可以直接引用網頁的,即:<script type="text/javascript" src="https://passport.cnblogs.com/scripts/jsencrypt.min.js"></script>
2疆股、生成一對RSA密鑰對费坊,可以在這個網址生成:http://web.chacuo.net/netrsakeypair倒槐,也可以下載一個工具來生成旬痹。
3、創(chuàng)建一個JsEncryptHelper.cs讨越,包含后臺的加密和解決功能两残,要把第2步生成的密鑰對放置在此文件中,之前本來想在前臺js中有參調用加密函數來加密不成功把跨,就是我樓上提出的問題人弓。后面就采用JavaScript.js夠進行加密了,為了展示效果着逐,把加密的結果保存在文本框中崔赌,如果在實際項目中可以把密文保存在一個隱藏的文本框中。后面會把這個類JsEncryptHelper.cs的代碼一并分享耸别。

一健芭、前臺代碼:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
   <script type="text/javascript" src="JavaScript.js"></script>
    <script language="javascript">       
        function pwd()
        {
            var encrypt = new JSEncrypt();
            encrypt.setPublicKey("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCC0hrRIjb3noDWNtbDpANbjt5Iwu2NFeDwU16Ec87ToqeoIm2KI+cOs81JP9aTDk/jkAlU97mN8wZkEMDr5utAZtMVht7GLX33Wx9XjqxUsDfsGkqNL8dXJklWDu9Zh80Ui2Ug+340d5dZtKtd+nv09QZqGjdnSp9PTfFDBY133QIDAQAB");
           var str = document.getElementById("tmpPWD").value;
            var encryptData = encrypt.encrypt(str);//加密后的字符串
            console.log(encryptData);
            document.getElementById("miwen").value = encryptData;
        }
 
</script>
</head>
<body>
    <form id="form1" runat="server" onsubmit="return pwd();">
    <div>       
        輸入密碼:<asp:TextBox ID="tmpPWD" runat="server"></asp:TextBox>
        <br />       
        密碼加密密文:<asp:TextBox ID="miwen" runat="server" TextMode="MultiLine"></asp:TextBox>
        <br />
        密文解密:<asp:TextBox ID="mingwen" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="解密" OnClick="Button1_Click" />
     
    </div>
    </form>
</body>
</html>

二、后臺解密按鈕代碼 :

protected void Button1_Click(object sender, EventArgs e)
   {
       JsEncryptHelper newRSA = new JsEncryptHelper();
       mingwen.Text = newRSA.Decrypt(miwen.Text);
 
   }

三秀姐、JsEncryptHelper.cs代碼:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
 
/// <summary>
/// JsEncryptHelper 的摘要說明
/// </summary>
/// <summary>
/// AJax提交參數加密幫助類
/// </summary>
public class JsEncryptHelper
{
    private const string defaultprivateKey = @"MIICXAIBAAKBgQCC0hrRIjb3noDWNtbDpANbjt5Iwu2NFeDwU16Ec87ToqeoIm2K
I+cOs81JP9aTDk/jkAlU97mN8wZkEMDr5utAZtMVht7GLX33Wx9XjqxUsDfsGkqN
L8dXJklWDu9Zh80Ui2Ug+340d5dZtKtd+nv09QZqGjdnSp9PTfFDBY133QIDAQAB
AoGAJBNTOITaP6LCyKVKyEdnHaKNAz0DS+V9UwjKhyAgfcAxwm3sDdd6FQCEW0TI
JA7Np7rFYrGwcR1UOoKxkNxB10ACl6JX4rE7xKS6NLZumdwxON/KgDb+2SQtWEXD
gBySZ7Znv/FhEp1RmoBDjZ05E99kILWO3ToorUM0Eq2GHQkCQQCnUMXgZa4HS0tu
INzysgB37d7ene9+CIARyJphs079qao2UWCgXqen43Ob6GJUgulz7We+4JOZFld0
TfEi1E5rAkEAyClQAVzafLO3gXgqH7tbRbPPx788+4opxT9QBo2Trzl6/3FlcC1P
IZeqbQ/Oc2wT7jmidFnpyTEnM2p7Yq3U1wJBAILTWaX4W3dAnJ5j+9+Y51zfFiEj
hRwbMWi2XmB+gAlAHOOUBeXfnWBdLQx/TEOgiUIoI7LQjxhoq8E5II+HSjkCQDlK
SdH6B7dFoTJ3eGcYsykiLEiZ3hSJGSeR1Y/qmei/ZQsUI9qVvV56EJeivI6g0puO
94ah7Z5eaT/4LFS0OIUCQDgLn586pGgeidLhQsIe/AR3y9YOCAygTFLxzmeBXOKt
M90q4516KWlTtK2u99442mNi7hNmjryBVwk62foWo8w=";
 
    private const string defaultpublicKey = @"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCC0hrRIjb3noDWNtbDpANbjt5I
wu2NFeDwU16Ec87ToqeoIm2KI+cOs81JP9aTDk/jkAlU97mN8wZkEMDr5utAZtMV
ht7GLX33Wx9XjqxUsDfsGkqNL8dXJklWDu9Zh80Ui2Ug+340d5dZtKtd+nv09QZq
GjdnSp9PTfFDBY133QIDAQAB";
 
    private RSACryptoServiceProvider _privateKeyRsaProvider;
    private RSACryptoServiceProvider _publicKeyRsaProvider;
 
    public JsEncryptHelper(string privateKey = "", string publicKey = "")
    {
 
        if (string.IsNullOrEmpty(privateKey))
        {
            privateKey = defaultprivateKey;
        }
        if (string.IsNullOrEmpty(publicKey))
        {
            publicKey = defaultpublicKey;
        }
 
        if (!string.IsNullOrEmpty(privateKey))
        {
            _privateKeyRsaProvider = CreateRsaProviderFromPrivateKey(privateKey);
        }
 
        if (!string.IsNullOrEmpty(publicKey))
        {
            _publicKeyRsaProvider = CreateRsaProviderFromPublicKey(publicKey);
        }
    }
 
    public string Decrypt(string cipherText)
    {
        if (_privateKeyRsaProvider == null)
        {
            throw new Exception("_privateKeyRsaProvider is null");
        }
 
        if (string.IsNullOrEmpty(cipherText))
        {
            return "";
        }       
 
 
        return Encoding.UTF8.GetString(_privateKeyRsaProvider.Decrypt(Convert.FromBase64String(cipherText), false));
    }
 
    public string Encrypt(string text)
    {
        if (_publicKeyRsaProvider == null)
        {
            throw new Exception("_publicKeyRsaProvider is null");
        }
        return Convert.ToBase64String(_publicKeyRsaProvider.Encrypt(Encoding.UTF8.GetBytes(text), false));
    }
 
 
    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;
    }
 
    private RSACryptoServiceProvider CreateRsaProviderFromPublicKey(string publicKeyString)
    {
        // encoded OID sequence for  PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1"
        byte[] SeqOID = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
        byte[] x509key;
        byte[] seq = new byte[15];
        int x509size;
 
        x509key = Convert.FromBase64String(publicKeyString);
        x509size = x509key.Length;
 
        // ---------  Set up stream to read the asn.1 encoded SubjectPublicKeyInfo blob  ------
        using (MemoryStream mem = new MemoryStream(x509key))
        {
            using (BinaryReader binr = new BinaryReader(mem))  //wrap Memory Stream with BinaryReader for easy reading
            {
                byte bt = 0;
                ushort twobytes = 0;
 
                twobytes = binr.ReadUInt16();
                if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
                    binr.ReadByte();    //advance 1 byte
                else if (twobytes == 0x8230)
                    binr.ReadInt16();   //advance 2 bytes
                else
                    return null;
 
                seq = binr.ReadBytes(15);       //read the Sequence OID
                if (!CompareBytearrays(seq, SeqOID))    //make sure Sequence for OID is correct
                    return null;
 
                twobytes = binr.ReadUInt16();
                if (twobytes == 0x8103) //data read as little endian order (actual data order for Bit String is 03 81)
                    binr.ReadByte();    //advance 1 byte
                else if (twobytes == 0x8203)
                    binr.ReadInt16();   //advance 2 bytes
                else
                    return null;
 
                bt = binr.ReadByte();
                if (bt != 0x00)     //expect null byte next
                    return null;
 
                twobytes = binr.ReadUInt16();
                if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
                    binr.ReadByte();    //advance 1 byte
                else if (twobytes == 0x8230)
                    binr.ReadInt16();   //advance 2 bytes
                else
                    return null;
 
                twobytes = binr.ReadUInt16();
                byte lowbyte = 0x00;
                byte highbyte = 0x00;
 
                if (twobytes == 0x8102) //data read as little endian order (actual data order for Integer is 02 81)
                    lowbyte = binr.ReadByte();  // read next bytes which is bytes in modulus
                else if (twobytes == 0x8202)
                {
                    highbyte = binr.ReadByte(); //advance 2 bytes
                    lowbyte = binr.ReadByte();
                }
                else
                    return null;
                byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };   //reverse byte order since asn.1 key uses big endian order
                int modsize = BitConverter.ToInt32(modint, 0);
 
                int firstbyte = binr.PeekChar();
                if (firstbyte == 0x00)
                {   //if first byte (highest order) of modulus is zero, don't include it
                    binr.ReadByte();    //skip this null byte
                    modsize -= 1;   //reduce modulus buffer size by 1
                }
 
                byte[] modulus = binr.ReadBytes(modsize);   //read the modulus bytes
 
                if (binr.ReadByte() != 0x02)            //expect an Integer for the exponent data
                    return null;
                int expbytes = (int)binr.ReadByte();        // should only need one byte for actual exponent data (for all useful values)
                byte[] exponent = binr.ReadBytes(expbytes);
 
                // ------- create RSACryptoServiceProvider instance and initialize with public key -----
                RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
                RSAParameters RSAKeyInfo = new RSAParameters();
                RSAKeyInfo.Modulus = modulus;
                RSAKeyInfo.Exponent = exponent;
                RSA.ImportParameters(RSAKeyInfo);
 
                return RSA;
            }
 
        }
    }
 
    private bool CompareBytearrays(byte[] a, byte[] b)
    {
        if (a.Length != b.Length)
            return false;
        int i = 0;
        foreach (byte c in a)
        {
            if (c != b[i])
                return false;
            i++;
        }
        return true;
    }
}
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末慈迈,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子省有,更是在濱河造成了極大的恐慌痒留,老刑警劉巖,帶你破解...
    沈念sama閱讀 210,978評論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件蠢沿,死亡現場離奇詭異伸头,居然都是意外死亡,警方通過查閱死者的電腦和手機舷蟀,發(fā)現死者居然都...
    沈念sama閱讀 89,954評論 2 384
  • 文/潘曉璐 我一進店門恤磷,熙熙樓的掌柜王于貴愁眉苦臉地迎上來弧轧,“玉大人,你說我怎么就攤上這事碗殷【铮” “怎么了?”我有些...
    開封第一講書人閱讀 156,623評論 0 345
  • 文/不壞的土叔 我叫張陵锌妻,是天一觀的道長代乃。 經常有香客問我炭菌,道長颈渊,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,324評論 1 282
  • 正文 為了忘掉前任寓娩,我火速辦了婚禮吭历,結果婚禮上堕仔,老公的妹妹穿的比我還像新娘。我一直安慰自己晌区,他們只是感情好摩骨,可當我...
    茶點故事閱讀 65,390評論 5 384
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著朗若,像睡著了一般恼五。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上哭懈,一...
    開封第一講書人閱讀 49,741評論 1 289
  • 那天灾馒,我揣著相機與錄音,去河邊找鬼遣总。 笑死睬罗,一個胖子當著我的面吹牛,可吹牛的內容都是我干的旭斥。 我是一名探鬼主播容达,決...
    沈念sama閱讀 38,892評論 3 405
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼琉预!你這毒婦竟也來了董饰?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 37,655評論 0 266
  • 序言:老撾萬榮一對情侶失蹤圆米,失蹤者是張志新(化名)和其女友劉穎卒暂,沒想到半個月后,有當地人在樹林里發(fā)現了一具尸體娄帖,經...
    沈念sama閱讀 44,104評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡也祠,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 36,451評論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現自己被綠了近速。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片诈嘿。...
    茶點故事閱讀 38,569評論 1 340
  • 序言:一個原本活蹦亂跳的男人離奇死亡堪旧,死狀恐怖,靈堂內的尸體忽然破棺而出奖亚,到底是詐尸還是另有隱情淳梦,我是刑警寧澤,帶...
    沈念sama閱讀 34,254評論 4 328
  • 正文 年R本政府宣布昔字,位于F島的核電站爆袍,受9級特大地震影響,放射性物質發(fā)生泄漏作郭。R本人自食惡果不足惜陨囊,卻給世界環(huán)境...
    茶點故事閱讀 39,834評論 3 312
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望夹攒。 院中可真熱鬧蜘醋,春花似錦、人聲如沸咏尝。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,725評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽状土。三九已至无蜂,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間蒙谓,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,950評論 1 264
  • 我被黑心中介騙來泰國打工训桶, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留累驮,地道東北人。 一個月前我還...
    沈念sama閱讀 46,260評論 2 360
  • 正文 我出身青樓舵揭,卻偏偏與公主長得像谤专,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子午绳,可洞房花燭夜當晚...
    茶點故事閱讀 43,446評論 2 348

推薦閱讀更多精彩內容