一. 场景介绍:如题如何有效的,最少量的现有代码侵入从而实现客户端与服务器之间的数据交换加密呢?
二. 探究: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加密
1 /// <summary> 2 /// 加密解密接口 3 /// </summary> 4 public interface imessageencryption 5 { 6 /// <summary> 7 /// 加密 8 /// </summary> 9 /// <param name="content"></param>10 /// <returns></returns>11 string encode(string content);12 /// <summary>13 /// 解密14 /// </summary>15 /// <param name="content"></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.1 des加密解密
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_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 name="encryptstring">待加密的字符串</param>12 /// <param name="encryptkey">加密密钥,要求为8位</param>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 name="decryptstring">待解密的字符串</param>37 /// <param name="decryptkey">解密密钥,要求为8位,和加密密钥相同</param>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 name="request"></param>11 /// <param name="cancellationtoken"></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 name="response"></param>57 /// <param name="cancellationtoken"></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 }
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实现通讯加密的详细内容。