C# RSA 加密

来源:https://www.cnblogs.com/xuannian/archive/2019/02/08/10356434.html
-Advertisement-
Play Games

class Sign_verifySign { #region prepare string to sign. //example format: a=123&b=xxx&c (with sort) private static string encrypt(T body) { var mType ... ...


class Sign_verifySign
    {
        #region prepare string to sign.
        //example format: a=123&b=xxx&c (with sort)
        private static string encrypt<T>(T body)
        {
            var mType = body.GetType();
            var props = mType.GetProperties().OrderBy(x => x.Name).ToArray();
            StringBuilder sb = new StringBuilder();
            foreach (var p in props)
            {
                if (p.Name != "sign" && p.Name != "signType" && p.GetValue(body, null) != null && p.GetValue(body, null).ToString() != "")
                {
                    sb.Append(string.Format("{0}={1}&", p.Name, p.GetValue(body, null)));
                }
            }
            var tmp = sb.ToString();
            return tmp.Substring(0, tmp.Length - 1);
        }
        #endregion

        #region sign
        public static string sign(string content, string privateKey, string input_charset)
        {
            byte[] Data = Encoding.GetEncoding(input_charset).GetBytes(content);
            RSACryptoServiceProvider rsa = DecodePemPrivateKey(privateKey);
            SHA1 sh = new SHA1CryptoServiceProvider();
            byte[] signData = rsa.SignData(Data, sh);
            //get base64string -> ASCII byte[]
            var base64ToByte = Encoding.ASCII.GetBytes(Convert.ToBase64String(signData));
            string signresult = BitConverter.ToString(base64ToByte).Replace("-", string.Empty);
            return signresult;
        }
        private static RSACryptoServiceProvider DecodePemPrivateKey(String pemstr)
        {
            byte[] pkcs8privatekey; pkcs8privatekey = Convert.FromBase64String(pemstr);
            if (pkcs8privatekey != null)
            {
                RSACryptoServiceProvider rsa = DecodePrivateKeyInfo(pkcs8privatekey);
                return rsa;
            }
            else return null;
        }
        private static RSACryptoServiceProvider DecodePrivateKeyInfo(byte[] pkcs8)
        {
            byte[] SeqOID = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
            byte[] seq = new byte[15]; MemoryStream mem = new MemoryStream(pkcs8);
            int lenstream = (int)mem.Length; BinaryReader binr = new BinaryReader(mem);    //wrap Memory Stream with BinaryReader for easy reading            
            byte bt = 0;
            ushort twobytes = 0;
            try
            {
                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;
                bt = binr.ReadByte();
                if (bt != 0x02)
                    return null;
                twobytes = binr.ReadUInt16();
                if (twobytes != 0x0001)
                    return null;
                seq = binr.ReadBytes(15);        //read the Sequence OID                
                if (!CompareBytearrays(seq, SeqOID))    //make sure Sequence for OID is correct                   
                    return null;
                bt = binr.ReadByte();
                if (bt != 0x04)    //expect an Octet string                    
                    return null;
                bt = binr.ReadByte();        //read next byte, or next 2 bytes is  0x81 or 0x82; otherwise bt is the byte count 
                if (bt == 0x81)
                    binr.ReadByte();
                else
                if (bt == 0x82)
                    binr.ReadUInt16();                //------ at this stage, the remaining sequence should be the RSA private key                 
                byte[] rsaprivkey = binr.ReadBytes((int)(lenstream - mem.Position));
                RSACryptoServiceProvider rsacsp = DecodeRSAPrivateKey(rsaprivkey);
                return rsacsp;
            }
            catch (Exception)
            {return null;
            }
            finally
            {
                binr.Close();
            }
        }
        private static 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;
        }
        private static RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey)
        {
            byte[] MODULUS, E, D, P, Q, DP, DQ, IQ;

            // ---------  Set up stream to decode the asn.1 encoded RSA private key  ------
            MemoryStream mem = new MemoryStream(privkey);
            BinaryReader binr = new BinaryReader(mem);    //wrap Memory Stream with BinaryReader for easy reading
            byte bt = 0;
            ushort twobytes = 0;
            int elems = 0;
            try
            {
                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();
                if (twobytes != 0x0102)  //version number
                    return null;
                bt = binr.ReadByte();
                if (bt != 0x00)
                    return null;


                //------  all private key components are Integer sequences ----
                elems = GetIntegerSize(binr);
                MODULUS = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                E = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                D = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                P = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                Q = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                DP = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                DQ = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                IQ = binr.ReadBytes(elems);

                // ------- create RSACryptoServiceProvider instance and initialize with public key -----
                RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
                RSAParameters RSAparams = new RSAParameters();
                RSAparams.Modulus = MODULUS;
                RSAparams.Exponent = E;
                RSAparams.D = D;
                RSAparams.P = P;
                RSAparams.Q = Q;
                RSAparams.DP = DP;
                RSAparams.DQ = DQ;
                RSAparams.InverseQ = IQ;
                RSA.ImportParameters(RSAparams);
                return RSA;
            }
            catch (Exception e)
            {
                return null;
            }
            finally { binr.Close(); }
        }
        private static int GetIntegerSize(BinaryReader binr)
        {
            byte bt = 0;
            byte lowbyte = 0x00;
            byte highbyte = 0x00;
            int count = 0;
            bt = binr.ReadByte();
            if (bt != 0x02)    //expect integer
                return 0;
            bt = binr.ReadByte();

            if (bt == 0x81)
                count = binr.ReadByte();  // data size in next byte
            else
                if (bt == 0x82)
            {
                highbyte = binr.ReadByte(); // data size in next 2 bytes
                lowbyte = binr.ReadByte();
                byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };
                count = BitConverter.ToInt32(modint, 0);
            }
            else
            {
                count = bt;     // we already have the data size
            }while (binr.ReadByte() == 0x00)
            {  //remove high order zeros in data
                count -= 1;
            }
            binr.BaseStream.Seek(-1, SeekOrigin.Current);    //last ReadByte wasn't a removed zero, so back up a byte
            return count;
        }
    
        #endregion

        #region verifySign
        //onepay verify
        public static bool verifyFromHexAscii(string sign, string publicKey, string content, string charset)
        {
            string decSign = System.Text.Encoding.UTF8.GetString(fromHexAscii(sign));
            return verify(content, decSign, publicKey, charset);
        }
        public static byte[] fromHexAscii(string s)
        {
            try
            {
                int len = s.Length;
                if ((len % 2) != 0)
                    throw new Exception("Hex ascii must be exactly two digits per byte.");

                int out_len = len / 2;
                byte[] out1 = new byte[out_len];
                int i = 0;
                StringReader sr = new StringReader(s);
                while (i < out_len)
                {
                    int val = (16 * fromHexDigit(sr.Read())) + fromHexDigit(sr.Read());
                    out1[i++] = (byte)val;
                }
                return out1;
            }
            catch (IOException e)
            {
                throw new Exception("IOException reading from StringReader?!?!");
            }
        }
        private static int fromHexDigit(int c)
        {
            if (c >= 0x30 && c < 0x3A)
                return c - 0x30;
            else if (c >= 0x41 && c < 0x47)
                return c - 0x37;
            else if (c >= 0x61 && c < 0x67)
                return c - 0x57;
            else
                throw new Exception('\'' + c + "' is not a valid hexadecimal digit.");
        }

        public static bool verify(string content, string signedString, string publicKey, string input_charset)
        {
            signedString = signedString.Replace("*", "+");
            signedString = signedString.Replace("-", "/");
            return JiJianverify(content, signedString, publicKey, input_charset);

        }
        public static bool JiJianverify(string content, string signedString, string publicKey, string input_charset)
        {
            bool result = false;
            byte[] Data = Encoding.GetEncoding(input_charset).GetBytes(content);

            byte[] data = Convert.FromBase64String(signedString);
            RSAParameters paraPub = ConvertFromPublicKey(publicKey);
            RSACryptoServiceProvider rsaPub = new RSACryptoServiceProvider();
            rsaPub.ImportParameters(paraPub);
            SHA1 sh = new SHA1CryptoServiceProvider();
            result = rsaPub.VerifyData(Data, sh, data);
            return result;
        }
        private static RSAParameters ConvertFromPublicKey(string pemFileConent)
        {

            byte[] keyData = Convert.FromBase64String(pemFileConent);
            if (keyData.Length < 162)
            {
                throw new ArgumentException("pem file content is incorrect.");
            }
            RsaKeyParameters publicKeyParam = (RsaKeyParameters)PublicKeyFactory.CreateKey(keyData);

            RSAParameters para = new RSAParameters();
            para.Modulus = publicKeyParam.Modulus.ToByteArrayUnsigned();
            para.Exponent = publicKeyParam.Exponent.ToByteArrayUnsigned();
            return para;
        }
        #endregion
    }

 


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

-Advertisement-
Play Games
更多相關文章
  • 目錄 [TOC] 1. 安裝Jupyter notebook 2. 啟動Jupyter notebook 3. 文件管理 4. 基本的操作與概念 5. 常用快捷鍵 (一)安裝Jupyter notebook 1.在控制台輸入: pip install jupyter 2.註意: 很多網上的教程推薦安 ...
  • 通過以下幾個步驟解決: 1.install-package entityFramework; 2.更新 nuget; 3.更新 visual studio; 我是通過第三個步驟解決的。 ...
  • 前端 using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Tex ...
  • [TOC] 前言 本文主要是以 C 為例介紹 .NET 中的三種指針類型(本文不包含對於函數指針的介紹): 對象引用 、 非托管指針 、 托管指針 。 學習是一個不斷深化理解的過程,藉此博客,把自己關於 .NET 中指針相關的理解和大家一起討論一下,若有表述不清楚,理解不正確之處,還請大家批評指正。 ...
  • 記錄CentOS 7.4 上安裝MySQL&MariaDB&Redis&Mongodb ...
  • 什麼是Sql註入?如何避免Sql註入? 用戶根據系統的程式構造非法的參數從而導致程式執行不是程式期望的惡意Sql語句。 使用參數化的Sql就可以避免Sql註入。 資料庫三範式是什麼? 第一範式:欄位不能有冗餘信息,所有欄位都是必不可少的。 第二範式:滿足第一範式並且表必須有主鍵。 第三範式:滿足第二 ...
  • 為了驗證採用dotnet core技術開發的物聯網設備數據採集接入服務應用是否能在高性價比的linux嵌入式平臺運行,針對dotnet core應用程式進行嵌入式linux環境的發佈部署運行驗證研究。 ...
  • 在.net 中類(class) 與結構(Struct)的異同。 Class 可以被實例化,屬於引用類型,是分配在記憶體的堆上的。類是引用傳遞的。 Struct 屬於值類型,是分配在記憶體的棧上的。結構體是複製傳遞的。 Boolean等屬於結構體。 堆和棧的區別 棧是編譯期間就分配好的記憶體空間,因此你的代 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...