搜尋
首頁後端開發C#.Net教程WebApi實現通訊加密

WebApi實現通訊加密

Mar 12, 2017 pm 04:17 PM

一. 場景介紹:

如題如何有效的,最少量的現有程式碼侵入從而實現客戶端與服務器之間的資料交換加密呢?

 

二.探究:

1.需求分析

webapi服務端有如下介面:

 


#
public class ApiTestController : ApiController
{    // GET api/<controller>/5
    public object Get(int id)
    {        return "value" + id;
    }
}</controller>

ApiTestController

#無加密請求

 GET /api/apitest?id=10

#返回結果

 response "value10"

#我們想要達到的效果為:

Get /api/apitest?aWQ9MTA=

response InZhbHVlMTAi  (解密所得"value10")

 或更多其它方式加密

 2.功能分析

 要想對現有程式碼不做任何修改, 我們都知道所有api controller 初始化在router確定之後, 因此我們應在router之前將GET參數和POST的參數進行加密才行.

 看下圖webapi 生命週期:

 

 我們看到在路由routing 之前有DelegationgHander 層進行訊息處理.

因為我們要對每個請求進行參數解密處理,並且又將回傳訊息進行加密處理, 因此我們瞄準 MessageProcessingHandler

 


#
    //
    // 摘要:    //     A base type for handlers which only do some small processing of request and/or    //     response messages.
    public abstract class MessageProcessingHandler : DelegatingHandler
    {        //
        // 摘要:        //     Creates an instance of a System.Net.Http.MessageProcessingHandler class.
        protected MessageProcessingHandler();        //
        // 摘要:        //     Creates an instance of a System.Net.Http.MessageProcessingHandler class with        //     a specific inner handler.        //
        // 参数:        //   innerHandler:        //     The inner handler which is responsible for processing the HTTP response messages.
        protected MessageProcessingHandler(HttpMessageHandler innerHandler);        //
        // 摘要:        //     Performs processing on each request sent to the server.        //
        // 参数:        //   request:        //     The HTTP request message to process.        //
        //   cancellationToken:        //     A cancellation token that can be used by other objects or threads to receive        //     notice of cancellation.        //
        // 返回结果:        //     Returns System.Net.Http.HttpRequestMessage.The HTTP request message that was        //     processed.
        protected abstract HttpRequestMessage ProcessRequest(HttpRequestMessage request, CancellationToken cancellationToken);        //
        // 摘要:        //     Perform processing on each response from the server.        //
        // 参数:        //   response:        //     The HTTP response message to process.        //
        //   cancellationToken:        //     A cancellation token that can be used by other objects or threads to receive        //     notice of cancellation.        //
        // 返回结果:        //     Returns System.Net.Http.HttpResponseMessage.The HTTP response message that was        //     processed.
        protected abstract HttpResponseMessage ProcessResponse(HttpResponseMessage response, CancellationToken cancellationToken);        //
        // 摘要:        //     Sends an HTTP request to the inner handler to send to the server as an asynchronous        //     operation.        //
        // 参数:        //   request:        //     The HTTP request message to send to the server.        //
        //   cancellationToken:        //     A cancellation token that can be used by other objects or threads to receive        //     notice of cancellation.        //
        // 返回结果:        //     Returns System.Threading.Tasks.Task`1.The task object representing the asynchronous        //     operation.        //
        // 异常:        //   T:System.ArgumentNullException:        //     The request was null.
        protected internal sealed override Task<httpresponsemessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken);
    }</httpresponsemessage>

MessageProcessingHandler

 

三.實踐:

現在我們將來先實現2個版本的通訊加密解密功能,設定為版本1.0 base64加密, 版本1.1 Des加密

 

 1     /// <summary> 2     /// 加密解密接口 3     /// </summary> 4     public interface IMessageEnCryption 5     { 6         /// <summary> 7         /// 加密 8         /// </summary> 9         /// <param>10         /// <returns></returns>11         string Encode(string content);12         /// <summary>13         /// 解密14         /// </summary>15         /// <param>16         /// <returns></returns>17         string Decode(string content);18     }

IMessageEnCryption

#編寫版本1.0 base64加密解密

 1     /// <summary> 2     /// 加解密 只做 base64 3     /// </summary> 4     public class MessageEncryptionVersion1_0 : IMessageEnCryption 5     { 6         public string Decode(string content) 7         { 8             return content?.DecryptBase64(); 9         }10 11         public string Encode(string content)12         {13             return content.EncryptBase64();14         }15     }

MessageEncryptionVersion1_0

#
 1     /// <summary> 2     /// 数据加解密 des 3     /// </summary> 4     public class MessageEncryptionVersion1_1 : IMessageEnCryption 5     { 6         public static readonly string KEY = "fHil/4]0"; 7         public string Decode(string content) 8         { 9             return content.DecryptDES(KEY);10         }11 12         public string Encode(string content)13         {14             return content.EncryptDES(KEY);15         }16     }

MessageEncryptionVersion1_0

#寫版本1.1 des加密解密

 1     public static class EncrypExtends 2     { 3  4         //默认密钥向量 5         private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; 6         internal static string Key = "*@&$(@#H"; 7  8         //// <summary> 9         /// DES加密字符串10         /// </summary>11         /// <param>待加密的字符串12         /// <param>加密密钥,要求为8位13         /// <returns>加密成功返回加密后的字符串,失败返回源串</returns>14         public static string EncryptDES(this string encryptString, string encryptKey)15         {16             try17             {18                 byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));19                 byte[] rgbIV = Keys;20                 byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);21                 DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();22                 MemoryStream mStream = new MemoryStream();23                 CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);24                 cStream.Write(inputByteArray, 0, inputByteArray.Length);25                 cStream.FlushFinalBlock();26                 return Convert.ToBase64String(mStream.ToArray());27             }28             catch29             {30                 return encryptString;31             }32         }33         //// <summary>34         /// DES解密字符串35         /// </summary>36         /// <param>待解密的字符串37         /// <param>解密密钥,要求为8位,和加密密钥相同38         /// <returns>解密成功返回解密后的字符串,失败返源串</returns>39         public static string DecryptDES(this string decryptString, string key)40         {41             try42             {43                 byte[] rgbKey = Encoding.UTF8.GetBytes(key.Substring(0, 8));44                 byte[] rgbIV = Keys;45                 byte[] inputByteArray = Convert.FromBase64String(decryptString);46                 DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();47                 MemoryStream mStream = new MemoryStream();48                 CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);49                 cStream.Write(inputByteArray, 0, inputByteArray.Length);50                 cStream.FlushFinalBlock();51                 return Encoding.UTF8.GetString(mStream.ToArray());52             }53             catch54             {55                 return decryptString;56             }57         }58         public static string EncryptBase64(this string encryptString)59         {60             return Convert.ToBase64String(Encoding.UTF8.GetBytes(encryptString));61         }62         public static string DecryptBase64(this string encryptString)63         {64             return Encoding.UTF8.GetString(Convert.FromBase64String(encryptString));65         }66         public static string DecodeUrl(this string cryptString)67         {68             return System.Web.HttpUtility.UrlDecode(cryptString);69         }70         public static string EncodeUrl(this string cryptString)71         {72             return System.Web.HttpUtility.UrlEncode(cryptString);73         }74     }

#MessageEncryptionVersion1_1 ######### #######附上加密解密的基本的一個封裝類別###


 1     public static class EncrypExtends 2     { 3  4         //默认密钥向量 5         private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; 6         internal static string Key = "*@&$(@#H"; 7  8         //// <summary> 9         /// DES加密字符串10         /// </summary>11         /// <param>待加密的字符串12         /// <param>加密密钥,要求为8位13         /// <returns>加密成功返回加密后的字符串,失败返回源串</returns>14         public static string EncryptDES(this string encryptString, string encryptKey)15         {16             try17             {18                 byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));19                 byte[] rgbIV = Keys;20                 byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);21                 DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();22                 MemoryStream mStream = new MemoryStream();23                 CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);24                 cStream.Write(inputByteArray, 0, inputByteArray.Length);25                 cStream.FlushFinalBlock();26                 return Convert.ToBase64String(mStream.ToArray());27             }28             catch29             {30                 return encryptString;31             }32         }33         //// <summary>34         /// DES解密字符串35         /// </summary>36         /// <param>待解密的字符串37         /// <param>解密密钥,要求为8位,和加密密钥相同38         /// <returns>解密成功返回解密后的字符串,失败返源串</returns>39         public static string DecryptDES(this string decryptString, string key)40         {41             try42             {43                 byte[] rgbKey = Encoding.UTF8.GetBytes(key.Substring(0, 8));44                 byte[] rgbIV = Keys;45                 byte[] inputByteArray = Convert.FromBase64String(decryptString);46                 DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();47                 MemoryStream mStream = new MemoryStream();48                 CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);49                 cStream.Write(inputByteArray, 0, inputByteArray.Length);50                 cStream.FlushFinalBlock();51                 return Encoding.UTF8.GetString(mStream.ToArray());52             }53             catch54             {55                 return decryptString;56             }57         }58         public static string EncryptBase64(this string encryptString)59         {60             return Convert.ToBase64String(Encoding.UTF8.GetBytes(encryptString));61         }62         public static string DecryptBase64(this string encryptString)63         {64             return Encoding.UTF8.GetString(Convert.FromBase64String(encryptString));65         }66         public static string DecodeUrl(this string cryptString)67         {68             return System.Web.HttpUtility.UrlDecode(cryptString);69         }70         public static string EncodeUrl(this string cryptString)71         {72             return System.Web.HttpUtility.UrlEncode(cryptString);73         }74     }

EncrypExtends

OK! 到此我们前题工作已经完成了80%,开始进行HTTP请求的 消息进和出的加密解密功能的实现.

我们暂时将加密的版本信息定义为 HTTP header头中 以 api_version 的value 来判别分别是用何种方式加密解密

header例:

  api_version: 1.0

  api_version: 1.1

 


 1     /// <summary> 2     ///  API消息请求处理 3     /// </summary> 4     public class JoyMessageHandler : MessageProcessingHandler 5     { 6  7         /// <summary> 8         /// 接收到request时 处理 9         /// </summary>10         /// <param>11         /// <param>12         /// <returns></returns>13         protected override HttpRequestMessage ProcessRequest(HttpRequestMessage request, CancellationToken cancellationToken)14         {15             if (request.Content.IsMimeMultipartContent())16                 return request;17             // 获取请求头中 api_version版本号18             var ver = System.Web.HttpContext.Current.Request.Headers.GetValues("api_version")?.FirstOrDefault();19             // 根据api_version版本号获取加密对象, 如果为null 则不需要加密20             var encrypt = MessageEncryptionCreator.GetInstance(ver);21 22             if (encrypt != null)23             {24                 // 读取请求body中的数据25                 string baseContent = request.Content.ReadAsStringAsync().Result;26                 // 获取加密的信息27                 // 兼容 body: 加密数据  和 body: code=加密数据28                 baseContent = baseContent.Match("(code=)*(?<code>[\\S]+)", 2);29                 // URL解码数据30                 baseContent = baseContent.DecodeUrl();31                 // 用加密对象解密数据32                 baseContent = encrypt.Decode(baseContent);33 34                 string baseQuery = string.Empty;35                 if (!request.RequestUri.Query.IsNullOrEmpty())36                 {37                     // 同 body38                     // 读取请求 url query数据39                     baseQuery = request.RequestUri.Query.Substring(1);40                     baseQuery = baseQuery.Match("(code=)*(?<code>[\\S]+)", 2);41                     baseQuery = baseQuery.DecodeUrl();42                     baseQuery = encrypt.Decode(baseQuery);43                 }44                 // 将解密后的 URL 重置URL请求45                 request.RequestUri = new Uri($"{request.RequestUri.AbsoluteUri.Split('?')[0]}?{baseQuery}");46                 // 将解密后的BODY数据 重置47                 request.Content = new StringContent(baseContent);48             }49 50             return request;51         }52 53         /// <summary>54         /// 处理将要向客户端response时55         /// </summary>56         /// <param>57         /// <param>58         /// <returns></returns>59         protected override HttpResponseMessage ProcessResponse(HttpResponseMessage response, CancellationToken cancellationToken)60         {61             //var isMediaType = response.Content.Headers.ContentType.MediaType.Equals(mediaTypeName, StringComparison.OrdinalIgnoreCase);62             var ver = System.Web.HttpContext.Current.Request.Headers.GetValues("api_version")?.FirstOrDefault();63             var encrypt = MessageEncryptionCreator.GetInstance(ver);64             if (encrypt != null)65             {66                 if (response.StatusCode == HttpStatusCode.OK)67                 {68                     var result = response.Content.ReadAsStringAsync().Result;69                     // 返回消息 进行加密70                     var encodeResult = encrypt.Encode(result);71                     response.Content = new StringContent(encodeResult);72                 }73             }74 75             return response;76         }77 78     }</code></code>

JoyMessageHandler

 

最后在 webapiconfig 中将我们的消息处理添加到容器中

 


 1     public static class WebApiConfig 2     { 3         public static void Register(HttpConfiguration config) 4         { 5             // Web API 配置和服务 6             // 将 Web API 配置为仅使用不记名令牌身份验证。 7             config.SuppressDefaultHostAuthentication(); 8             config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); 9 10             // Web API 路由11             config.MapHttpAttributeRoutes();12 13             config.Routes.MapHttpRoute(14                 name: "DefaultApi",15                 routeTemplate: "api/{controller}/{id}",16                 defaults: new { id = RouteParameter.Optional }17             );18 19             // 添加自定义消息处理20             config.MessageHandlers.Add(new JoyMessageHandler());21 22         }23     }

WebApiConfig

 

编写单元测试:


 1  [TestMethod()] 2         public void GetTest() 3         { 4             var id = 10; 5             var resultSuccess = $"\"value{id}\""; 6             //不加密 7             Trace.WriteLine($"without encryption."); 8             var url = $"api/ApiTest?id={id}"; 9             Trace.WriteLine($"get url : {url}");10             var response = http.GetAsync(url).Result;11             var result = response.Content.ReadAsStringAsync().Result;12             Assert.AreEqual(result, resultSuccess);13             Trace.WriteLine($"result : {result}");14 15             //使用 方案1加密16             Trace.WriteLine($"encryption case one.");17 18             url = $"api/ApiTest?code=" + $"id={id}".EncryptBase64().EncodeUrl();19 20             Trace.WriteLine($"get url : {url}");21 22             http.DefaultRequestHeaders.Clear();23             http.DefaultRequestHeaders.Add("api_version", "1.0");24             response = http.GetAsync(url).Result;25 26             result = response.Content.ReadAsStringAsync().Result;27 28             Trace.WriteLine($"result : {result}");29 30             result = result.DecryptBase64();31 32             Trace.WriteLine($"DecryptBase64 : {result}");33 34             Assert.AreEqual(result, resultSuccess);35 36             //使用 方案2 加密通讯37             Trace.WriteLine($"encryption case one.");38             39             url = $"api/ApiTest?code=" + $"id={id}".EncryptDES(MessageEncryptionVersion1_1.KEY).EncodeUrl();40 41             Trace.WriteLine($"get url : {url}");42 43             http.DefaultRequestHeaders.Clear();44             http.DefaultRequestHeaders.Add("api_version", "1.1");45             response = http.GetAsync(url).Result;46 47             result = response.Content.ReadAsStringAsync().Result;48 49             Trace.WriteLine($"result : {result}");50 51             result = result.DecryptDES(MessageEncryptionVersion1_1.KEY);52 53             Trace.WriteLine($"DecryptBase64 : {result}");54 55             Assert.AreEqual(result, resultSuccess);56         }

ApiTestControllerTests

 至此为止功能实现完毕..

 四.思想延伸

要想更加安全的方案,可以将给每位用户生成不同的 private key , 利用AES加密解密

 

以上是WebApi實現通訊加密的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
c#.net的持續相關性:查看當前用法c#.net的持續相關性:查看當前用法Apr 16, 2025 am 12:07 AM

C#.NET依然重要,因為它提供了強大的工具和庫,支持多種應用開發。 1)C#結合.NET框架,使開發高效便捷。 2)C#的類型安全和垃圾回收機制增強了其優勢。 3).NET提供跨平台運行環境和豐富的API,提升了開發靈活性。

從網絡到桌面:C#.NET的多功能性從網絡到桌面:C#.NET的多功能性Apr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C#.NET與未來:適應新技術C#.NET與未來:適應新技術Apr 14, 2025 am 12:06 AM

C#和.NET通過不斷的更新和優化,適應了新興技術的需求。 1)C#9.0和.NET5引入了記錄類型和性能優化。 2).NETCore增強了雲原生和容器化支持。 3)ASP.NETCore與現代Web技術集成。 4)ML.NET支持機器學習和人工智能。 5)異步編程和最佳實踐提升了性能。

c#.net適合您嗎?評估其適用性c#.net適合您嗎?評估其適用性Apr 13, 2025 am 12:03 AM

c#.netissutableforenterprise-levelapplications withemofrosoftecosystemdueToItsStrongTyping,richlibraries,androbustperraries,androbustperformance.however,itmaynotbeidealfoross-platement forment forment forment forvepentment offependment dovelopment toveloperment toveloperment whenrawspeedsportor whenrawspeedseedpolitical politionalitable,

.NET中的C#代碼:探索編程過程.NET中的C#代碼:探索編程過程Apr 12, 2025 am 12:02 AM

C#在.NET中的編程過程包括以下步驟:1)編寫C#代碼,2)編譯為中間語言(IL),3)由.NET運行時(CLR)執行。 C#在.NET中的優勢在於其現代化語法、強大的類型系統和與.NET框架的緊密集成,適用於從桌面應用到Web服務的各種開發場景。

C#.NET:探索核心概念和編程基礎知識C#.NET:探索核心概念和編程基礎知識Apr 10, 2025 am 09:32 AM

C#是一種現代、面向對象的編程語言,由微軟開發並作為.NET框架的一部分。 1.C#支持面向對象編程(OOP),包括封裝、繼承和多態。 2.C#中的異步編程通過async和await關鍵字實現,提高應用的響應性。 3.使用LINQ可以簡潔地處理數據集合。 4.常見錯誤包括空引用異常和索引超出範圍異常,調試技巧包括使用調試器和異常處理。 5.性能優化包括使用StringBuilder和避免不必要的裝箱和拆箱。

測試C#.NET應用程序:單元,集成和端到端測試測試C#.NET應用程序:單元,集成和端到端測試Apr 09, 2025 am 12:04 AM

C#.NET應用的測試策略包括單元測試、集成測試和端到端測試。 1.單元測試確保代碼的最小單元獨立工作,使用MSTest、NUnit或xUnit框架。 2.集成測試驗證多個單元組合的功能,常用模擬數據和外部服務。 3.端到端測試模擬用戶完整操作流程,通常使用Selenium進行自動化測試。

高級C#.NET教程:ACE您的下一次高級開發人員面試高級C#.NET教程:ACE您的下一次高級開發人員面試Apr 08, 2025 am 12:06 AM

C#高級開發者面試需要掌握異步編程、LINQ、.NET框架內部工作原理等核心知識。 1.異步編程通過async和await簡化操作,提升應用響應性。 2.LINQ以SQL風格操作數據,需注意性能。 3..NET框架的CLR管理內存,垃圾回收需謹慎使用。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
4 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
4 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
4 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.聊天命令以及如何使用它們
4 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),