• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • JavaScript
  • ASP.NET
  • PHP
  • 正则表达式
  • AJAX
  • JSP
  • ASP
  • Flex
  • XML
  • 编程技巧
  • Android
  • swift
  • C#教程
  • vb
  • vb.net
  • C语言
  • Java
  • Delphi
  • 易语言
  • vc/mfc
  • 嵌入式开发
  • 游戏开发
  • ios
  • 编程问答
  • 汇编语言
  • 微信小程序
  • 数据结构
  • OpenGL
  • 架构设计
  • qt
  • 微信公众号
您的位置:首页 > 程序设计 >ASP.NET > WebApi实现通讯加密

WebApi实现通讯加密

作者:董侨 字体:[增加 减小] 来源:互联网 时间:2017-05-11

董侨通过本文主要向大家介绍了webapi 实现aop,webapi加密,webapi教程,webapi,webapi是什么等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

一. 场景介绍:

如题如何有效的,最少量的现有代码侵入从而实现客户端与服务器之间的数据交换加密呢?

二. 探究:

1.需求分析

webapi服务端 有如下接口:

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

ApiTestController
</div>

无加密请求

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);
 }

MessageProcessingHandler
</div>

三. 实践:

现在我们将来 先实现2个版本的通讯加密解密功能,定为 版本1.0 base64加密, 版本1.1 Des加密

/// <summary>
 /// 加密解密接口
 /// </summary>
 public interface IMessageEnCryption
 {
  /// <summary>
  /// 加密
  /// </summary>
  /// <param name="content"></param>
  /// <returns></returns>
  string Encode(string content);
  /// <summary>
  /// 解密
  /// </summary>
  /// <param name="content"></param>
  /// <returns></returns>
  string Decode(string content);
 }

IMessageEnCryption
</div>

编写版本1.0 base64加密解密

/// <summary>
 /// 加解密 只做 base64
 /// </summary>
 public class MessageEncryptionVersion1_0 : IMessageEnCryption
 {
  public string Decode(string content)
  {
   return content?.DecryptBase64();
  }

  public string Encode(string content)
  {
   return content.EncryptBase64();
  }
 }

MessageEncryptionVersion1_0
</div>

编写版本1.1 des加密解密

/// <summary>
 /// 数据加解密 des
 /// </summary>
 public class MessageEncryptionVersion1_1 : IMessageEnCryption
 {
  public static readonly string KEY = "fHil/4]0";
  public string Decode(string content)
  {
   return content.DecryptDES(KEY);
  }
  public string Encode(string content)
  {
   return content.EncryptDES(KEY);
  }
 }

MessageEncryptionVersion1_1
</div>

附上加密解密的基本的一个封装类

public static class EncrypExtends
 {
  //默认密钥向量
  private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
  internal static string Key = "*@&$(@#H";

  //// <summary>
  /// DES加密字符串
  /// </summary>
  /// <param name="encryptString">待加密的字符串</param>
  /// <param name="encryptKey">加密密钥,要求为8位</param>
  /// <returns>加密成功返回加密后的字符串,失败返回源串</returns>
  public static string EncryptDES(this string encryptString, string encryptKey)
  {
   try
   {
    byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
    byte[] rgbIV = Keys;
    byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
    DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
    MemoryStream mStream = new MemoryStream();
    CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
    cStream.Write(inputByteArray, 0, inputByteArray.Length);
    cStream.FlushFinalBlock();
    return Convert.ToBase64String(mStream.ToArray());
   }
   catch
   {
    return encryptString;
   }
  }
  //// <summary>
  /// DES解密字符串
  /// </summary>
  /// <param name="decryptString">待解密的字符串</param>
  /// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
  /// <returns>解密成功返回解密后的字符串,失败返源串</returns>
  public static string DecryptDES(this string decryptString, string key)
  {
   try
   {
    byte[] rgbKey = Encoding.UTF8.GetBytes(key.Substring(0, 8));
    byte[] rgbIV = Keys;
    byte[] inputByteArray = Convert.FromBase64String(decryptString);
    DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
    MemoryStream mStream = new MemoryStream();
    CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
    cStream.Write(inputByteArray, 0, inputByteArray.Length);
    cStream.FlushFinalBlock();
    return Encoding.UTF8.GetString(mStream.ToArray());
   }
   catch
   {
    return decryptString;
   }
  }
  public static string EncryptBase64(this string encryptStri



 
分享到:QQ空间新浪微博腾讯微博微信百度贴吧QQ好友复制网址打印

您可能想查找下面的文章:

  • WebApi实现通讯加密

相关文章

  • 2017-05-11ASP.NET中利用WebClient上传图片到远程服务的方法
  • 2017-05-11.Net 调用存储过程取到return的返回值
  • 2017-05-11asp.net多文件上传实例讲解
  • 2017-05-11asp.net伪静态配置备忘
  • 2017-05-11asp.net不用设置iis实现url重写 类似伪静态路由
  • 2018-08-20.NET Unity IOC框架使用实例详解
  • 2017-05-11jsp和asp.net共享session值示例代码
  • 2017-05-11.net非托管资源的回收方法
  • 2017-05-11ASP.NET中文件上传下载方法集合
  • 2018-08-20asp.net core 2.0 webapi集成signalr(实例讲解)

文章分类

  • JavaScript
  • ASP.NET
  • PHP
  • 正则表达式
  • AJAX
  • JSP
  • ASP
  • Flex
  • XML
  • 编程技巧
  • Android
  • swift
  • C#教程
  • vb
  • vb.net
  • C语言
  • Java
  • Delphi
  • 易语言
  • vc/mfc
  • 嵌入式开发
  • 游戏开发
  • ios
  • 编程问答
  • 汇编语言
  • 微信小程序
  • 数据结构
  • OpenGL
  • 架构设计
  • qt
  • 微信公众号

最近更新的内容

    • swfupload ajax无刷新上传图片实例代码
    • ASP.NET Core异常和错误处理(8)
    • .NET获取当前路径的方法汇总
    • ASP.NET笔记之文章发布管理小系统案例
    • ASP.NET显示渐变图片实现方法
    • 将Access数据库中数据导入到SQL Server中的详细方法实例
    • .net mvc页面UI之Jquery博客日历控件实现代码
    • Asp.net中Response.Charset与Response.ContentEncoding区别示例分析
    • .NET工厂方法模式讲解
    • 对ListBox的添加移除操作实例分享

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有