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

来源:https://www.cnblogs.com/liguokun/archive/2020/05/19/12916136.html
-Advertisement-
Play Games

近來有一個報名網站原來是內網訪問的,近期要放到外網訪問,但要求密碼不能明文傳輸。在網上參考了幾個帖子並整理出來: asp.net 前端JS RSA加密,後端c#解密 在分享源碼之前,先準備一些東西:1、下載一個js加密幫助文件,下載地址:https://passport.cnblogs.com/sc ...


近來有一個報名網站原來是內網訪問的,近期要放到外網訪問,但要求密碼不能明文傳輸。在網上參考了幾個帖子並整理出來:

asp.net 前端JS RSA加密,後端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、創建一個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;
    }
}

 

大概參考了以下幾個博客:

 

https://www.cnblogs.com/alunchen/p/5758585.html

https://www.cnblogs.com/zhangwenbo0713/p/10494945.html 

https://blog.csdn.net/k21325/article/details/54409381

感謝以上幾個博主,也感謝沒有列舉出來的參考博客。

如果有哪位朋友參考了本博客後還有疑問的,可以發郵件一併討論:[email protected]


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • SunnyUI.Net, 基於 C# .Net WinForm 開源控制項庫、工具類庫、擴展類庫、多頁面開發框架 Blog: https://www.cnblogs.com/yhuse Gitee: https://gitee.com/yhuse/SunnyUI GitHub: https://git ...
  • SunnyUI.Net, 基於 C# .Net WinForm 開源控制項庫、工具類庫、擴展類庫、多頁面開發框架,2020-05-19創建目錄 ...
  • 一.分別在Windows/Mac/Centos上安裝Docker Windows上下載地址:https://docs.docker.com/docker-for-windows/install/(window上安裝的常見問題和解決方案請參考下方步驟六) Mac上下載地址:https://hub.do ...
  • 隨著信息技術對人們工作生活的影響越來越大,人們對於應用程式的依賴性也越來越大,越來越多的人使用應用程式來解決自己工作和生活中的問題,這也導致應用程式的開發需求越來越大,傳統的應用程式開發方法已經沒有辦法滿足市場的需求,現在很多的人使用低代碼開發平臺來完成應用程式的開發工作,用低代碼開發平臺開發應用程 ...
  • ketcup git地址:https://github.com/simple-gr/ketchup consul 安裝 1.docker pull consul 2.docker run --name=consul --restart=always -d -p 8500:8500 consul 3. ...
  • 上一篇文章(https://www.cnblogs.com/meowv/p/12909558.html)完善了項目中的代碼,接入了Swagger。本篇主要使用Entity Framework Core完成對資料庫的訪問,以及使用Code First的方式進行數據遷移,自動創建表結構。 數據訪問 在 ...
  • 最近在做發票的批量開票處理,發現航信的開票軟體V2.3.10.200301 竟然連個介面都沒有…咨詢航信竟然是幾萬塊一個,是一個license而且每年收取服務費,也太貴了…這是稅務的介面竟然它收費!!!好吧,研究一下繞道處理。自己生成註冊碼…哈哈搞定。 ...
  • 時間格式我使用的一直都是 yyyy-MM-dd HH:mm:ss,然後某天,我改成了 yyyy/MM/dd HH:mm:ss,然後神奇的問題就來了。 ...
一周排行
    -Advertisement-
    Play Games
  • GoF之工廠模式 @目錄GoF之工廠模式每博一文案1. 簡單說明“23種設計模式”1.2 介紹工廠模式的三種形態1.3 簡單工廠模式(靜態工廠模式)1.3.1 簡單工廠模式的優缺點:1.4 工廠方法模式1.4.1 工廠方法模式的優缺點:1.5 抽象工廠模式1.6 抽象工廠模式的優缺點:2. 總結:3 ...
  • 新改進提供的Taurus Rpc 功能,可以簡化微服務間的調用,同時可以不用再手動輸出模塊名稱,或調用路徑,包括負載均衡,這一切,由框架實現並提供了。新的Taurus Rpc 功能,將使得服務間的調用,更加輕鬆、簡約、高效。 ...
  • 本章將和大家分享ES的數據同步方案和ES集群相關知識。廢話不多說,下麵我們直接進入主題。 一、ES數據同步 1、數據同步問題 Elasticsearch中的酒店數據來自於mysql資料庫,因此mysql數據發生改變時,Elasticsearch也必須跟著改變,這個就是Elasticsearch與my ...
  • 引言 在我們之前的文章中介紹過使用Bogus生成模擬測試數據,今天來講解一下功能更加強大自動生成測試數據的工具的庫"AutoFixture"。 什麼是AutoFixture? AutoFixture 是一個針對 .NET 的開源庫,旨在最大程度地減少單元測試中的“安排(Arrange)”階段,以提高 ...
  • 經過前面幾個部分學習,相信學過的同學已經能夠掌握 .NET Emit 這種中間語言,並能使得它來編寫一些應用,以提高程式的性能。隨著 IL 指令篇的結束,本系列也已經接近尾聲,在這接近結束的最後,會提供幾個可供直接使用的示例,以供大伙分析或使用在項目中。 ...
  • 當從不同來源導入Excel數據時,可能存在重覆的記錄。為了確保數據的準確性,通常需要刪除這些重覆的行。手動查找並刪除可能會非常耗費時間,而通過編程腳本則可以實現在短時間內處理大量數據。本文將提供一個使用C# 快速查找並刪除Excel重覆項的免費解決方案。 以下是實現步驟: 1. 首先安裝免費.NET ...
  • C++ 異常處理 C++ 異常處理機制允許程式在運行時處理錯誤或意外情況。它提供了捕獲和處理錯誤的一種結構化方式,使程式更加健壯和可靠。 異常處理的基本概念: 異常: 程式在運行時發生的錯誤或意外情況。 拋出異常: 使用 throw 關鍵字將異常傳遞給調用堆棧。 捕獲異常: 使用 try-catch ...
  • 優秀且經驗豐富的Java開發人員的特征之一是對API的廣泛瞭解,包括JDK和第三方庫。 我花了很多時間來學習API,尤其是在閱讀了Effective Java 3rd Edition之後 ,Joshua Bloch建議在Java 3rd Edition中使用現有的API進行開發,而不是為常見的東西編 ...
  • 框架 · 使用laravel框架,原因:tp的框架路由和orm沒有laravel好用 · 使用強制路由,方便介面多時,分多版本,分文件夾等操作 介面 · 介面開發註意欄位類型,欄位是int,查詢成功失敗都要返回int(對接java等強類型語言方便) · 查詢介面用GET、其他用POST 代碼 · 所 ...
  • 正文 下午找企業的人去鎮上做貸後。 車上聽同事跟那個司機對罵,火星子都快出來了。司機跟那同事更熟一些,連我在內一共就三個人,同事那一手指桑罵槐給我都聽愣了。司機也是老社會人了,馬上聽出來了,為那個無辜的企業經辦人辯護,實際上是為自己辯護。 “這個事情你不能怪企業。”“但他們總不能讓銀行的人全權負責, ...