asp.net 前端JS加密,后端c#解密

前台代码:


<!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;

    }

}

亚马逊测评 www.yisuping.com

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,519评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,842评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,544评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,742评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,646评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,027评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,513评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,169评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,324评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,268评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,299评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,996评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,591评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,667评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,911评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,288评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,871评论 2 341