当前位置: 移动技术网 > IT编程>开发语言>.net > WebApi实现通讯加密

WebApi实现通讯加密

2017年12月08日  | 移动技术网IT编程  | 我要评论

李茂林,酒店摄像头正对床铺,造梦西游3黑龟在哪

一. 场景介绍:

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

二. 探究:

1.需求分析

webapi服务端 有如下接口:

public class apitestcontroller : apicontroller
{
 // get api/<controller>/5
 public object get(int id)
 {
  return "value" + id;
 }
}

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

messageprocessinghandler

三. 实践:

现在我们将来 先实现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

编写版本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

编写版本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

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

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 encryptstring)
  {
   return convert.tobase64string(encoding.utf8.getbytes(encryptstring));
  }
  public static string decryptbase64(this string encryptstring)
  {
   return encoding.utf8.getstring(convert.frombase64string(encryptstring));
  }
  public static string decodeurl(this string cryptstring)
  {
   return system.web.httputility.urldecode(cryptstring);
  }
  public static string encodeurl(this string cryptstring)
  {
   return system.web.httputility.urlencode(cryptstring);
  }
 }

encrypextends

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

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

header例:

  api_version: 1.0

  api_version: 1.1

/// <summary>
 /// api消息请求处理
 /// </summary>
 public class joymessagehandler : messageprocessinghandler
 {
  /// <summary>
  /// 接收到request时 处理
  /// </summary>
  /// <param name="request"></param>
  /// <param name="cancellationtoken"></param>
  /// <returns></returns>
  protected override httprequestmessage processrequest(httprequestmessage request, cancellationtoken cancellationtoken)
  {
   if (request.content.ismimemultipartcontent())
    return request;
   // 获取请求头中 api_version版本号
   var ver = system.web.httpcontext.current.request.headers.getvalues("api_version")?.firstordefault();
   // 根据api_version版本号获取加密对象, 如果为null 则不需要加密
   var encrypt = messageencryptioncreator.getinstance(ver);
   if (encrypt != null)
   {
    // 读取请求body中的数据
    string basecontent = request.content.readasstringasync().result;
    // 获取加密的信息
    // 兼容 body: 加密数据 和 body: code=加密数据
    basecontent = basecontent.match("(code=)*(?<code>[\\s]+)", 2);
    // url解码数据
    basecontent = basecontent.decodeurl();
    // 用加密对象解密数据
    basecontent = encrypt.decode(basecontent);
    string basequery = string.empty;
    if (!request.requesturi.query.isnullorempty())
    {
     // 同 body
     // 读取请求 url query数据
     basequery = request.requesturi.query.substring(1);
     basequery = basequery.match("(code=)*(?<code>[\\s]+)", 2);
     basequery = basequery.decodeurl();
     basequery = encrypt.decode(basequery);
    }
    // 将解密后的 url 重置url请求
    request.requesturi = new uri($"{request.requesturi.absoluteuri.split('?')[0]}?{basequery}");
    // 将解密后的body数据 重置
    request.content = new stringcontent(basecontent);
   }
   return request;
  }
  /// <summary>
  /// 处理将要向客户端response时
  /// </summary>
  /// <param name="response"></param>
  /// <param name="cancellationtoken"></param>
  /// <returns></returns>
  protected override httpresponsemessage processresponse(httpresponsemessage response, cancellationtoken cancellationtoken)
  {
   //var ismediatype = response.content.headers.contenttype.mediatype.equals(mediatypename, stringcomparison.ordinalignorecase);
   var ver = system.web.httpcontext.current.request.headers.getvalues("api_version")?.firstordefault();
   var encrypt = messageencryptioncreator.getinstance(ver);
   if (encrypt != null)
   {
    if (response.statuscode == httpstatuscode.ok)
    {
     var result = response.content.readasstringasync().result;
     // 返回消息 进行加密
     var encoderesult = encrypt.encode(result);
     response.content = new stringcontent(encoderesult);
    }
   }
   return response;
  }
 }

joymessagehandler

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

public static class webapiconfig
 {
  public static void register(httpconfiguration config)
  {
   // web api 配置和服务
   // 将 web api 配置为仅使用不记名令牌身份验证。
   config.suppressdefaulthostauthentication();
   config.filters.add(new hostauthenticationfilter(oauthdefaults.authenticationtype));
   // web api 路由
   config.maphttpattributeroutes();
   config.routes.maphttproute(
    name: "defaultapi",
    routetemplate: "api/{controller}/{id}",
    defaults: new { id = routeparameter.optional }
   );
   // 添加自定义消息处理
   config.messagehandlers.add(new joymessagehandler());
  }
 }

webapiconfig

编写单元测试:

[testmethod()]
  public void gettest()
  {
   var id = 10;
   var resultsuccess = $"\"value{id}\"";
   //不加密
   trace.writeline($"without encryption.");
   var url = $"api/apitest?id={id}";
   trace.writeline($"get url : {url}");
   var response = http.getasync(url).result;
   var result = response.content.readasstringasync().result;
   assert.areequal(result, resultsuccess);
   trace.writeline($"result : {result}");
   //使用 方案1加密
   trace.writeline($"encryption case one.");
   url = $"api/apitest?code=" + $"id={id}".encryptbase64().encodeurl();
   trace.writeline($"get url : {url}");
   http.defaultrequestheaders.clear();
   http.defaultrequestheaders.add("api_version", "1.0");
   response = http.getasync(url).result;
   result = response.content.readasstringasync().result;
   trace.writeline($"result : {result}");
   result = result.decryptbase64();
   trace.writeline($"decryptbase64 : {result}");
   assert.areequal(result, resultsuccess);
   //使用 方案2 加密通讯
   trace.writeline($"encryption case one.");
   url = $"api/apitest?code=" + $"id={id}".encryptdes(messageencryptionversion1_1.key).encodeurl();
   trace.writeline($"get url : {url}");
   http.defaultrequestheaders.clear();
   http.defaultrequestheaders.add("api_version", "1.1");
   response = http.getasync(url).result;
   result = response.content.readasstringasync().result;
   trace.writeline($"result : {result}");
   result = result.decryptdes(messageencryptionversion1_1.key);
   trace.writeline($"decryptbase64 : {result}");
   assert.areequal(result, resultsuccess);
  }

apitestcontrollertests

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

四.思想延伸

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

本demo开源地址:

oschina

https://git.oschina.net/jonneydong/webapi_encryption

github

https://github.com/jonneydong/webapi_encryption

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持移动技术网!

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网