前言:最近一个一个很奇怪的问题,很明白的说,就是没看懂,参照下面的代码:
/// <summary>
/// 反序列化对象
/// </summary>
/// <typeparam name="T">指定对象类型</typeparam>
/// <param name="data">字节数组</param>
/// <param name="isClearData">压缩完成后,是否清除待压缩字节数组里面的内容</param>
/// <returns>指定类型的对象</returns>
public static T DeserializeByBytes<T>(byte[] data, bool isClearData = true)
{
T t = default(T);
if (data == null)
return t;
try
{
BinaryFormatter formatter = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream(data))
{
t = (T)formatter.Deserialize(ms);
}
formatter = null;
if (isClearData)
Array.Clear(data, 0, data.Length);
}
catch (Exception ex)
{
throw ex;
}
return t;
}
[Serializable]
public class parent
{
public string a;
}
[Serializable]
public class children : parent
{
public string b;
}
public static DeserializeBytes(byte[] byteData)
{
//byteData数据,其实是:{ a = "1", b = "2" } 也就是children对象得到的二进制数据流
parent a = Program.DeserializeByBytes<parent>(byteData);
children b = a as children;
Console.WriteLine(JsonConvert.SerializeObject(b));
}
猜猜结果是什么?
很奇怪?是不是,我是先反序列化成的父对象:parent对象,parent对象里没有属性b,但是我将父对象AS成子对象时,子对象children的属性b中居然有值,是不是很神奇!!!
同样的情况,我们使用JsonConvert的序列化和反序列化做一遍,结果如下:
var cc = new children { a = "1", b = "2" };
var ccStr = JsonConvert.SerializeObject(cc);
parent p = JsonConvert.DeserializeObject<parent>(ccStr);
Console.WriteLine(JsonConvert.SerializeObject(p));
children c = p as children;
Console.WriteLine(JsonConvert.SerializeObject(c));
Console.Read();
是不是很奇怪? 妹的,真是神奇了,最后询问我们的老大才知道,划重点了哈:
重点:通过二级制流序列化和反序列化的对象呢,属性值并不会丢失!!! 而通过JsonConvert进行的string类型的序列化反序列化,多余的属性值会丢失!!! 就是真么神奇!
本人觉得,应该是和机制有关,通过二进制转换的数据,多余的数据计算机会始终记录着,毕竟计算机本身就是二进制的。而通过JsonConvert的方式,它会默认去匹配属性去,没有匹配上的属性会直接丢失。
指针很简单
------引子
学计算机语言,首先推荐C语言.无论是数据结构还是算法,站在C语言的角度,会让我们理解的更加清晰透彻.
但是,指针不太"友好",让很多人抓狂,头疼.不少人选择了放弃,绕行.百度上有千千万个解决方法,而我们放弃的理
由和简单,路在脚下,向前还?是向后?
C语言之所以经久不衰,就是因为指针的存在.本篇将帮助大家突破指针这个瓶颈.
1.指针和指针变量(通常我们叙述时会把指针变量简称为指针,实际他们含义并不一样)
指针:0x7ffe38fea3e0
指针变量:char *data;(*data就是指针变量)
2.指针和函数的关系(给子函数传多个值时用到(注意:你要不知道给什么,请自觉抄写关于指针案例,10遍))
需要提前掌握:函数的设计(返回值 函数名 参数),不清楚,请问百度;
子函数能不能静态申请空间,动态呢?会出现啥情况?
子函数什么时候是指针?
函数可以返回地址码?
此时此刻,热心网友早已经为我们准备好了,我们耐心的去博客园/csdn找,绝对可以找到,讲的非常专业.
3.指针与字符串
这个也百度,当然我不是糟老头啊.对于很对新人来说,缺少的是独自探索能力,遇到问题先去文别人,不懂的地方都是,这个老师没讲,那个书本没有,对于程序员而言,我们需要自己想办法.如果一直依靠问别人,是远远不够的.
4.指针数组、二级指针、函数指针、指针函数、二维数组、void *
指针数组:是一个数组,每一项都是指针(处理多个字符串)
案例:char *str[5] = {NULL};
二级指针:
int data = 0;
int *p = NULL;
p = &data; <-------(这是二级指针)
int **q = NULL; <------(这也是二级指针)
指针数组也是(不知道,不知道百度回炉数组去)
函数指针:
回调函数是啥?
函数如何作为另一个函数的参数,有啥案例?
自己百度!
指针函数:(函数参数返回值是指针的函数)
二维数组: char[2][3]data;(有2个空间,每个空间大小为3)
void *:“不确定类型指针
https://www.cnblogs.com/yuanyongbin/p/8058755.html自己去看
当我们接触到新的知识时,反复的查找,总结练习,才能达突破某一瓶颈,抵达下一个佳境,C语言的开发速度很难跟上社会需求的速度,前人为我们已经整理好了很多宝贵的心得.但是探索精神需要稀缺,还是那句话,不会百度想办法,当你工作几年后你会感谢曾今的自己,知识、机会向来都是自己去找的.
多百度,多和同事交流,多看书,多总结,成功都是在这些废话中.
什么是研究
research
就是re -search
不同的寻找搜索
这就是研究,因为我们在探索未知区域
我们只能搜索
作者:Eleven
来源:公众号【软谋net】
【前言】
.Net Core开源&跨平台,已经肉眼可见将成为.Net平台的未来,在企业招聘需求上已经频频见到,接触到很多公司内部都已经开始尝试Core的项目了,尤其是腾讯的财付通全部是基于Core+微服务搭建的,让人倍感振奋!Eleven最近出个专题,以当下最新的Asp.Net Core 2.2 Preview3为版本,给大家来一套系统教程,希望小伙伴儿们能多多关注!
【环境搭建】
我这边使用的VisualStudio版本为2017企业版15.7.4(并不是最新版本,专业版社区版也都是可以的)。之前安装是自带的Core是1.1版本,现在需要安装最新的sdk(dotnet-sdk-2.2.100-preview3-009430-win-x64.exe),以及最新的runtime(dotnet-runtime-2.2.0-preview3-27014-02-win-x64)。相关环境配置,需要的话可以关注底部公众号后,联系助教老师获取!
【项目建立】
下面开始动手建立Asp.Net Core2.2项目了,添加项目,选择Web,然后选择 ASP.NET Core Web应用程序模板,另外那个是原来的Framework版本的。
这里选择.NET Core,然后选择最新的ASP.NET Core2.2,选择下面的MVC应用程序,点击确定即可完成创建!建立完后的项目如下,一个典型的MVC项目,但是跟Framework下的有明显差异,增加了Program和Startup,这二位将是本文的主角了!
【Program】
看到Program,应该有种很亲切的感觉,包括里面的Main方法,这就是整个程序的入口。实际上,我们建立的这个项目,本质就是个控制台程序而已,查看项目属性可以得知。但为啥这个Program能当成MVC网站呢?
秘密就是那个CreateDefaultBuilder方法,这里面是启动一个Kestrel的服务器来完成请求的监听和响应的,在以前Core版本里,这里还有很多的配置项,现在已经内置为一个Default了。然后这里简单理解下,就是初始化一个服务器,然后Run一下,我们的Web服务器就算是启动了。其中在初始化服务器的时候,使用了一个Startup类,下面来详析一番!
【Startup】
在 ASP.NET Core 中,Startup 类提供了应用程序的入口,而且在所有应用程序中都有 Startup 类。ASP.NET 会在主程序集中搜索名为 Startup 的类(在任何命名空间下)。ASP.NET 并不关心 Startup 类是不是定义为 public,如果它符合命名规范,ASP.NET 将继续加载它。如果有多个 Startup 类,也不会触发异常,ASP.NET 将基于命名空间选择其中一个(匹配项目的根命名空间优先,否则使用第一个按字母排列的命名空间中的类)。
打开Startup类,大概分三块,这个是典型的构造函数注入,完成了一个叫IConfiguration类型变量的注入,至于是怎么注入的,后文中会讲到。这个变量是用来读取配置文件的,跟以前Framework下那个System.ConfigurationManager类差不多的。
然后是ConfigureServices方法,上面的注释描述的很清楚,是交给运行时环境调用的方法,然后用来给容器注册服务的(跟刚才说到的注入一致)。在Asp.Net Core里面,IOC容器是直接内置了的,也就是这个IServiceCollection。感兴趣的小伙伴儿可以去尝试下,直接nuget就可以下载Microsoft.Extensions.DependencyInjection,跟常见的容器用法几乎一样的,后面单独开文章再讲这个。这里完成全部需要依赖注入对象的初始化。
最下面是Configure方法,也是由运行时环境调用的,用来配置HTTP请求的处理管道的。Web的本质就是对Http请求的处理,最终得到一个响应结果,而这个方法,清晰的描述了,该如何去处理请求。
【内置服务和启动】
下面我就可以启动网站了,以前在做网站开发测试的时候,习惯性的去指定一下网站的端口和默认页,但是现在项目类型是控制台项目,相关的配置现在转移到项目的Properties--->launchSettings.json文件里面,可以在这里修改生效!顺便说一下,因为建立项目的时候,勾选了SSL支持,那么这里启动的会是https的Url,而且这个sslPort好像只能是以443开头,否则可能会无法访问。
然后一个完全没有做任何修改的Asp.Net Core2.2的项目就运行起来啦!
简单说一下加密解密:
加密解密有挺多方式去实现,今天呢我做为宇宙第一帅的人就给大家来分享以下源代码!听清楚是源代码哦!!
话不多说上干货
1:MD5加密/解密
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4 using System.Web;
5 using System.Text.RegularExpressions;
6
7 namespace hic.Common
8 {
9 public class SecurityHelper
10 {
11 /// <summary>
12 /// MD5字符串加密
13 /// </summary>
14 /// <param name="source">待加密字符串</param>
15 /// <returns></returns>
16 public static string MD5(string source)
17 {
18 return MD5(source, true);
19 }
20
21 /// <summary>
22 /// MD5字符串加密
23 /// </summary>
24 /// <param name="source">待加密字符串</param>
25 /// <param name="ishalf">加密是16位还是32位,如果为true则是16位。</param>
26 /// <returns></returns>
27 public static string MD5(string source, bool ishalf)
28 {
29 string outputStr = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(source, "MD5").ToLower();
30 if (ishalf)//16位MD5加密(取32位加密的9~25字符)
31 outputStr = outputStr.Substring(8, 16);
32 return outputStr;
33 }
34
35 /// <summary>
36 /// 对字符串进行Base64编码
37 /// </summary>
38 /// <param name="source">待编码字符串</param>
39 /// <returns></returns>
40 public static string EncodeBase64(string source)
41 {
42 UnicodeEncoding code = new UnicodeEncoding();
43 byte[] bytes = code.GetBytes(source);
44 return Convert.ToBase64String(bytes);
45 }
46
47 /// <summary>
48 /// 对字符串进行Base64解码
49 /// </summary>
50 /// <param name="source">待解码字符串</param>
51 /// <returns></returns>
52 public static string DecodeBase64(string source)
53 {
54 UnicodeEncoding code = new UnicodeEncoding();
55 byte[] bytes = Convert.FromBase64String(source);
56 return code.GetString(bytes);
57 }
58
59 /// <summary>
60 /// 检查当前IP是否是受限IP
61 /// </summary>
62 /// <param name="LimitedIP">受限的IP,格式如:192.168.1.110|212.235.*.*|232.*.*.*</param>
63 /// <returns>返回true表示IP未受到限制</returns>
64 public static bool CheckIPIsLimited(string limitedIP)
65 {
66 string currentIP = GetUserIP();
67 if (limitedIP == null || limitedIP.Trim() == string.Empty)
68 return true;
69 limitedIP.Replace(".", @"\.");
70 limitedIP.Replace("*", @"[^\.]{1,3}");
71 Regex reg = new Regex(limitedIP, RegexOptions.Compiled);
72 Match match = reg.Match(currentIP);
73 return !match.Success;
74 }
75
76 /// <summary>
77 /// 得到用户IP
78 /// </summary>
79 /// <returns></returns>
80 public static string GetUserIP()
81 {
82 return HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
83 }
84 }
85 }
2:DES加密/解密类
1 using System;
2 using System.Security.Cryptography;
3 using System.Text;
4 namespace Maticsoft.Common.DEncrypt
5 {
6 /// <summary>
7 /// DES加密/解密类。
8 /// LiTianPing
9 /// </summary>
10 public class DESEncrypt
11 {
12 public DESEncrypt()
13 {
14 }
15
16 #region ========加密========
17
18 /// <summary>
19 /// 加密
20 /// </summary>
21 /// <param name="Text"></param>
22 /// <returns></returns>
23 public static string Encrypt(string Text)
24 {
25 return Encrypt(Text,"MATICSOFT");
26 }
27 /// <summary>
28 /// 加密数据
29 /// </summary>
30 /// <param name="Text"></param>
31 /// <param name="sKey"></param>
32 /// <returns></returns>
33 public static string Encrypt(string Text,string sKey)
34 {
35 DESCryptoServiceProvider des = new DESCryptoServiceProvider();
36 byte[] inputByteArray;
37 inputByteArray=Encoding.Default.GetBytes(Text);
38 des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
39 des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
40 System.IO.MemoryStream ms=new System.IO.MemoryStream();
41 CryptoStream cs=new CryptoStream(ms,des.CreateEncryptor(),CryptoStreamMode.Write);
42 cs.Write(inputByteArray,0,inputByteArray.Length);
43 cs.FlushFinalBlock();
44 StringBuilder ret=new StringBuilder();
45 foreach( byte b in ms.ToArray())
46 {
47 ret.AppendFormat("{0:X2}",b);
48 }
49 return ret.ToString();
50 }
51
52 #endregion
53
54 #region ========解密========
55
56
57 /// <summary>
58 /// 解密
59 /// </summary>
60 /// <param name="Text"></param>
61 /// <returns></returns>
62 public static string Decrypt(string Text)
63 {
64 return Decrypt(Text,"MATICSOFT");
65 }
66 /// <summary>
67 /// 解密数据
68 /// </summary>
69 /// <param name="Text"></param>
70 /// <param name="sKey"></param>
71 /// <returns></returns>
72 public static string Decrypt(string Text,string sKey)
73 {
74 DESCryptoServiceProvider des = new DESCryptoServiceProvider();
75 int len;
76 len=Text.Length/2;
77 byte[] inputByteArray = new byte[len];
78 int x,i;
79 for(x=0;x<len;x++)
80 {
81 i = Convert.ToInt32(Text.Substring(x * 2, 2), 16);
82 inputByteArray[x]=(byte)i;
83 }
84 des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
85 des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
86 System.IO.MemoryStream ms=new System.IO.MemoryStream();
87 CryptoStream cs=new CryptoStream(ms,des.CreateDecryptor(),CryptoStreamMode.Write);
88 cs.Write(inputByteArray,0,inputByteArray.Length);
89 cs.FlushFinalBlock();
90 return Encoding.Default.GetString(ms.ToArray());
91 }
92
93 #endregion
94
95
96 }
97 }
3:RSA加密解密及RSA签名和验证
1 using System;
2 using System.Text;
3 using System.Security.Cryptography;
4 namespace Maticsoft.Common.DEncrypt
5 {
6 /// <summary>
7 /// RSA加密解密及RSA签名和验证
8 /// </summary>
9 public class RSACryption
10 {
11 public RSACryption()
12 {
13 }
14
15
16 #region RSA 加密解密
17
18 #region RSA 的密钥产生
19
20 /// <summary>
21 /// RSA 的密钥产生 产生私钥 和公钥
22 /// </summary>
23 /// <param name="xmlKeys"></param>
24 /// <param name="xmlPublicKey"></param>
25 public void RSAKey(out string xmlKeys,out string xmlPublicKey)
26 {
27 System.Security.Cryptography.RSACryptoServiceProvider rsa=new RSACryptoServiceProvider();
28 xmlKeys=rsa.ToXmlString(true);
29 xmlPublicKey = rsa.ToXmlString(false);
30 }
31 #endregion
32
33 #region RSA的加密函数
34 //##############################################################################
35 //RSA 方式加密
36 //说明KEY必须是XML的行式,返回的是字符串
37 //在有一点需要说明!!该加密方式有 长度 限制的!!
38 //##############################################################################
39
40 //RSA的加密函数 string
41 public string RSAEncrypt(string xmlPublicKey,string m_strEncryptString )
42 {
43
44 byte[] PlainTextBArray;
45 byte[] CypherTextBArray;
46 string Result;
47 RSACryptoServiceProvider rsa=new RSACryptoServiceProvider();
48 rsa.FromXmlString(xmlPublicKey);
49 PlainTextBArray = (new UnicodeEncoding()).GetBytes(m_strEncryptString);
50 CypherTextBArray = rsa.Encrypt(PlainTextBArray, false);
51 Result=Convert.ToBase64String(CypherTextBArray);
52 return Result;
53
54 }
55 //RSA的加密函数 byte[]
56 public string RSAEncrypt(string xmlPublicKey,byte[] EncryptString )
57 {
58
59 byte[] CypherTextBArray;
60 string Result;
61 RSACryptoServiceProvider rsa=new RSACryptoServiceProvider();
62 rsa.FromXmlString(xmlPublicKey);
63 CypherTextBArray = rsa.Encrypt(EncryptString, false);
64 Result=Convert.ToBase64String(CypherTextBArray);
65 return Result;
66
67 }
68 #endregion
69
70 #region RSA的解密函数
71 //RSA的解密函数 string
72 public string RSADecrypt(string xmlPrivateKey, string m_strDecryptString )
73 {
74 byte[] PlainTextBArray;
75 byte[] DypherTextBArray;
76 string Result;
77 System.Security.Cryptography.RSACryptoServiceProvider rsa=new RSACryptoServiceProvider();
78 rsa.FromXmlString(xmlPrivateKey);
79 PlainTextBArray =Convert.FromBase64String(m_strDecryptString);
80 DypherTextBArray=rsa.Decrypt(PlainTextBArray, false);
81 Result=(new UnicodeEncoding()).GetString(DypherTextBArray);
82 return Result;
83
84 }
85
86 //RSA的解密函数 byte
87 public string RSADecrypt(string xmlPrivateKey, byte[] DecryptString )
88 {
89 byte[] DypherTextBArray;
90 string Result;
91 System.Security.Cryptography.RSACryptoServiceProvider rsa=new RSACryptoServiceProvider();
92 rsa.FromXmlString(xmlPrivateKey);
93 DypherTextBArray=rsa.Decrypt(DecryptString, false);
94 Result=(new UnicodeEncoding()).GetString(DypherTextBArray);
95 return Result;
96
97 }
98 #endregion
99
100 #endregion
101
102 #region RSA数字签名
103
104 #region 获取Hash描述表
105 //获取Hash描述表
106 public bool GetHash(string m_strSource, ref byte[] HashData)
107 {
108 //从字符串中取得Hash描述
109 byte[] Buffer;
110 System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");
111 Buffer = System.Text.Encoding.GetEncoding("GB2312").GetBytes(m_strSource);
112 HashData = MD5.ComputeHash(Buffer);
113
114 return true;
115 }
116
117 //获取Hash描述表
118 public bool GetHash(string m_strSource, ref string strHashData)
119 {
120
121 //从字符串中取得Hash描述
122 byte[] Buffer;
123 byte[] HashData;
124 System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");
125 Buffer = System.Text.Encoding.GetEncoding("GB2312").GetBytes(m_strSource);
126 HashData = MD5.ComputeHash(Buffer);
127
128 strHashData = Convert.ToBase64String(HashData);
129 return true;
130
131 }
132
133 //获取Hash描述表
134 public bool GetHash(System.IO.FileStream objFile, ref byte[] HashData)
135 {
136
137 //从文件中取得Hash描述
138 System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");
139 HashData = MD5.ComputeHash(objFile);
140 objFile.Close();
141
142 return true;
143
144 }
145
146 //获取Hash描述表
147 public bool GetHash(System.IO.FileStream objFile, ref string strHashData)
148 {
149
150 //从文件中取得Hash描述
151 byte[] HashData;
152 System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");
153 HashData = MD5.ComputeHash(objFile);
154 objFile.Close();
155
156 strHashData = Convert.ToBase64String(HashData);
157
158 return true;
159
160 }
161 #endregion
162
163 #region RSA签名
164 //RSA签名
165 public bool SignatureFormatter(string p_strKeyPrivate, byte[] HashbyteSignature, ref byte[] EncryptedSignatureData)
166 {
167
168 System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
169
170 RSA.FromXmlString(p_strKeyPrivate);
171 System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
172 //设置签名的算法为MD5
173 RSAFormatter.SetHashAlgorithm("MD5");
174 //执行签名
175 EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);
176
177 return true;
178
179 }
180
181 //RSA签名
182 public bool SignatureFormatter(string p_strKeyPrivate, byte[] HashbyteSignature, ref string m_strEncryptedSignatureData)
183 {
184
185 byte[] EncryptedSignatureData;
186
187 System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
188
189 RSA.FromXmlString(p_strKeyPrivate);
190 System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
191 //设置签名的算法为MD5
192 RSAFormatter.SetHashAlgorithm("MD5");
193 //执行签名
194 EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);
195
196 m_strEncryptedSignatureData = Convert.ToBase64String(EncryptedSignatureData);
197
198 return true;
199
200 }
201
202 //RSA签名
203 public bool SignatureFormatter(string p_strKeyPrivate, string m_strHashbyteSignature, ref byte[] EncryptedSignatureData)
204 {
205
206 byte[] HashbyteSignature;
207
208 HashbyteSignature = Convert.FromBase64String(m_strHashbyteSignature);
209 System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
210
211 RSA.FromXmlString(p_strKeyPrivate);
212 System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
213 //设置签名的算法为MD5
214 RSAFormatter.SetHashAlgorithm("MD5");
215 //执行签名
216 EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);
217
218 return true;
219
220 }
221
222 //RSA签名
223 public bool SignatureFormatter(string p_strKeyPrivate, string m_strHashbyteSignature, ref string m_strEncryptedSignatureData)
224 {
225
226 byte[] HashbyteSignature;
227 byte[] EncryptedSignatureData;
228
229 HashbyteSignature = Convert.FromBase64String(m_strHashbyteSignature);
230 System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
231
232 RSA.FromXmlString(p_strKeyPrivate);
233 System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
234 //设置签名的算法为MD5
235 RSAFormatter.SetHashAlgorithm("MD5");
236 //执行签名
237 EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);
238
239 m_strEncryptedSignatureData = Convert.ToBase64String(EncryptedSignatureData);
240
241 return true;
242
243 }
244 #endregion
245
246 #region RSA 签名验证
247
248 public bool SignatureDeformatter(string p_strKeyPublic, byte[] HashbyteDeformatter, byte[] DeformatterData)
249 {
250
251 System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
252
253 RSA.FromXmlString(p_strKeyPublic);
254 System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
255 //指定解密的时候HASH算法为MD5
256 RSADeformatter.SetHashAlgorithm("MD5");
257
258 if(RSADeformatter.VerifySignature(HashbyteDeformatter,DeformatterData))
259 {
260 return true;
261 }
262 else
263 {
264 return false;
265 }
266
267 }
268
269 public bool SignatureDeformatter(string p_strKeyPublic, string p_strHashbyteDeformatter, byte[] DeformatterData)
270 {
271
272 byte[] HashbyteDeformatter;
273
274 HashbyteDeformatter = Convert.FromBase64String(p_strHashbyteDeformatter);
275
276 System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
277
278 RSA.FromXmlString(p_strKeyPublic);
279 System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
280 //指定解密的时候HASH算法为MD5
281 RSADeformatter.SetHashAlgorithm("MD5");
282
283 if(RSADeformatter.VerifySignature(HashbyteDeformatter,DeformatterData))
284 {
285 return true;
286 }
287 else
288 {
289 return false;
290 }
291
292 }
293
294 public bool SignatureDeformatter(string p_strKeyPublic, byte[] HashbyteDeformatter, string p_strDeformatterData)
295 {
296
297 byte[] DeformatterData;
298
299 System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
300
301 RSA.FromXmlString(p_strKeyPublic);
302 System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
303 //指定解密的时候HASH算法为MD5
304 RSADeformatter.SetHashAlgorithm("MD5");
305
306 DeformatterData =Convert.FromBase64String(p_strDeformatterData);
307
308 if(RSADeformatter.VerifySignature(HashbyteDeformatter,DeformatterData))
309 {
310 return true;
311 }
312 else
313 {
314 return false;
315 }
316
317 }
318
319 public bool SignatureDeformatter(string p_strKeyPublic, string p_strHashbyteDeformatter, string p_strDeformatterData)
320 {
321
322 byte[] DeformatterData;
323 byte[] HashbyteDeformatter;
324
325 HashbyteDeformatter = Convert.FromBase64String(p_strHashbyteDeformatter);
326 System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
327
328 RSA.FromXmlString(p_strKeyPublic);
329 System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
330 //指定解密的时候HASH算法为MD5
331 RSADeformatter.SetHashAlgorithm("MD5");
332
333 DeformatterData =Convert.FromBase64String(p_strDeformatterData);
334
335 if(RSADeformatter.VerifySignature(HashbyteDeformatter,DeformatterData))
336 {
337 return true;
338 }
339 else
340 {
341 return false;
342 }
343
344 }
345
346
347 #endregion
348
349
350 #endregion
351
352 }
353 }
4:哈希加密/解密
1 using System;
2 using System.Text;
3 using System.Security.Cryptography;
4 namespace Maticsoft.Common.DEncrypt
5 {
6 /// <summary>
7 /// 得到随机安全码(哈希加密)。
8 /// </summary>
9 public class HashEncode
10 {
11 public HashEncode()
12 {
13 //
14 // TODO: 在此处添加构造函数逻辑
15 //
16 }
17 /// <summary>
18 /// 得到随机哈希加密字符串
19 /// </summary>
20 /// <returns></returns>
21 public static string GetSecurity()
22 {
23 string Security = HashEncoding(GetRandomValue());
24 return Security;
25 }
26 /// <summary>
27 /// 得到一个随机数值
28 /// </summary>
29 /// <returns></returns>
30 public static string GetRandomValue()
31 {
32 Random Seed = new Random();
33 string RandomVaule = Seed.Next(1, int.MaxValue).ToString();
34 return RandomVaule;
35 }
36 /// <summary>
37 /// 哈希加密一个字符串
38 /// </summary>
39 /// <param name="Security"></param>
40 /// <returns></returns>
41 public static string HashEncoding(string Security)
42 {
43 byte[] Value;
44 UnicodeEncoding Code = new UnicodeEncoding();
45 byte[] Message = Code.GetBytes(Security);
46 SHA512Managed Arithmetic = new SHA512Managed();
47 Value = Arithmetic.ComputeHash(Message);
48 Security = "";
49 foreach(byte o in Value)
50 {
51 Security += (int) o + "O";
52 }
53 return Security;
54 }
55 }
56 }
5:Encrypt
1 using System;
2 using System.Security.Cryptography;
3 using System.Text;
4 namespace Maticsoft.Common.DEncrypt
5 {
6 /// <summary>
7 /// Encrypt 的摘要说明。
8 /// LiTianPing
9 /// </summary>
10 public class DEncrypt
11 {
12 /// <summary>
13 /// 构造方法
14 /// </summary>
15 public DEncrypt()
16 {
17 }
18
19 #region 使用 缺省密钥字符串 加密/解密string
20
21 /// <summary>
22 /// 使用缺省密钥字符串加密string
23 /// </summary>
24 /// <param name="original">明文</param>
25 /// <returns>密文</returns>
26 public static string Encrypt(string original)
27 {
28 return Encrypt(original,"MATICSOFT");
29 }
30 /// <summary>
31 /// 使用缺省密钥字符串解密string
32 /// </summary>
33 /// <param name="original">密文</param>
34 /// <returns>明文</returns>
35 public static string Decrypt(string original)
36 {
37 return Decrypt(original,"MATICSOFT",System.Text.Encoding.Default);
38 }
39
40 #endregion
41
42 #region 使用 给定密钥字符串 加密/解密string
43 /// <summary>
44 /// 使用给定密钥字符串加密string
45 /// </summary>
46 /// <param name="original">原始文字</param>
47 /// <param name="key">密钥</param>
48 /// <param name="encoding">字符编码方案</param>
49 /// <returns>密文</returns>
50 public static string Encrypt(string original, string key)
51 {
52 byte[] buff = System.Text.Encoding.Default.GetBytes(original);
53 byte[] kb = System.Text.Encoding.Default.GetBytes(key);
54 return Convert.ToBase64String(Encrypt(buff,kb));
55 }
56 /// <summary>
57 /// 使用给定密钥字符串解密string
58 /// </summary>
59 /// <param name="original">密文</param>
60 /// <param name="key">密钥</param>
61 /// <returns>明文</returns>
62 public static string Decrypt(string original, string key)
63 {
64 return Decrypt(original,key,System.Text.Encoding.Default);
65 }
66
67 /// <summary>
68 /// 使用给定密钥字符串解密string,返回指定编码方式明文
69 /// </summary>
70 /// <param name="encrypted">密文</param>
71 /// <param name="key">密钥</param>
72 /// <param name="encoding">字符编码方案</param>
73 /// <returns>明文</returns>
74 public static string Decrypt(string encrypted, string key,Encoding encoding)
75 {
76 byte[] buff = Convert.FromBase64String(encrypted);
77 byte[] kb = System.Text.Encoding.Default.GetBytes(key);
78 return encoding.GetString(Decrypt(buff,kb));
79 }
80 #endregion
81
82 #region 使用 缺省密钥字符串 加密/解密/byte[]
83 /// <summary>
84 /// 使用缺省密钥字符串解密byte[]
85 /// </summary>
86 /// <param name="encrypted">密文</param>
87 /// <param name="key">密钥</param>
88 /// <returns>明文</returns>
89 public static byte[] Decrypt(byte[] encrypted)
90 {
91 byte[] key = System.Text.Encoding.Default.GetBytes("MATICSOFT");
92 return Decrypt(encrypted,key);
93 }
94 /// <summary>
95 /// 使用缺省密钥字符串加密
96 /// </summary>
97 /// <param name="original">原始数据</param>
98 /// <param name="key">密钥</param>
99 /// <returns>密文</returns>
100 public static byte[] Encrypt(byte[] original)
101 {
102 byte[] key = System.Text.Encoding.Default.GetBytes("MATICSOFT");
103 return Encrypt(original,key);
104 }
105 #endregion
106
107 #region 使用 给定密钥 加密/解密/byte[]
108
109 /// <summary>
110 /// 生成MD5摘要
111 /// </summary>
112 /// <param name="original">数据源</param>
113 /// <returns>摘要</returns>
114 public static byte[] MakeMD5(byte[] original)
115 {
116 MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
117 byte[] keyhash = hashmd5.ComputeHash(original);
118 hashmd5 = null;
119 return keyhash;
120 }
121
122
123 /// <summary>
124 /// 使用给定密钥加密
125 /// </summary>
126 /// <param name="original">明文</param>
127 /// <param name="key">密钥</param>
128 /// <returns>密文</returns>
129 public static byte[] Encrypt(byte[] original, byte[] key)
130 {
131 TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
132 des.Key = MakeMD5(key);
133 des.Mode = CipherMode.ECB;
134
135 return des.CreateEncryptor().TransformFinalBlock(original, 0, original.Length);
136 }
137
138 /// <summary>
139 /// 使用给定密钥解密数据
140 /// </summary>
141 /// <param name="encrypted">密文</param>
142 /// <param name="key">密钥</param>
143 /// <returns>明文</returns>
144 public static byte[] Decrypt(byte[] encrypted, byte[] key)
145 {
146 TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
147 des.Key = MakeMD5(key);
148 des.Mode = CipherMode.ECB;
149
150 return des.CreateDecryptor().TransformFinalBlock(encrypted, 0, encrypted.Length);
151 }
152
153 #endregion
154
155
156
157
158 }
159 }
WebApi程序可在方法参数前加[FromBody]标识,表示该参数值应该从请求的Body中获取,而不是从URL中获取。
从URL获取参数值的方式的弊端是URL有长度限制,当超过浏览器的最大URL长度时请求将被浏览器拒绝,根本不会发出去。
因此,当参数值过大时需要用[FromBody]参数进行传输。
以下是WebApi接口定义,很简单,只为说明用法:
private string SendObjectAsJsonInBody(string url, object objBody)
{
string result;
HttpClient client;
StringContent content;
client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
content = new StringContent(ParkingSqlHelper.JsonHelper.SerializeObject(objBody), Encoding.UTF8, "application/json");
result = client.PostAsync(url, content).Result.Content.ReadAsStringAsync().Result;
return result;
}
protected HttpResponseMessage GetJsonResponse(string json)
{
HttpResponseMessage result;
result = new HttpResponseMessage { Content = new StringContent(json, Encoding.GetEncoding("UTF-8"), "application/json") };
//result.Headers.Add("Access-Control-Allow-Origin", "*"); //设置HTTP头允许 返回的跨域信息给浏览器解析
return result;
}
需要注意的是: [FromBody] 参数不能是基本的数据类型(如byte、int、bool、DateTime、string等)。
以下是C#客户端请求的代码
/// <summary>
/// 通过请求体向指定URL传输数据
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="objBody">需传输的数据</param>
/// <returns></returns>
private string SendObjectAsJsonInBody(string url, object objBody)
{
string result;
HttpClient client;
StringContent content;
client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
content = new StringContent(ParkingSqlHelper.JsonHelper.SerializeObject(objBody), Encoding.UTF8, "application/json");
result = client.PostAsync(url, content).Result.Content.ReadAsStringAsync().Result;
return result;
}
以下是JQuery请求的代码
function Send(url, objBody) {
$.ajax({
url: url,
type: "post",
data: JSON.stringify(objBody),
contentType: "application/json; charset=UTF-8",
timeout: 5000,
success: function (result) {
alert("data = " + JSON.stringify(result));
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
});
};
---------------------
前言:最近一个一个很奇怪的问题,很明白的说,就是没看懂,参照下面的代码:
/// <summary>
/// 反序列化对象
/// </summary>
/// <typeparam name="T">指定对象类型</typeparam>
/// <param name="data">字节数组</param>
/// <param name="isClearData">压缩完成后,是否清除待压缩字节数组里面的内容</param>
/// <returns>指定类型的对象</returns>
public static T DeserializeByBytes<T>(byte[] data, bool isClearData = true)
{
T t = default(T);
if (data == null)
return t;
try
{
BinaryFormatter formatter = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream(data))
{
t = (T)formatter.Deserialize(ms);
}
formatter = null;
if (isClearData)
Array.Clear(data, 0, data.Length);
}
catch (Exception ex)
{
throw ex;
}
return t;
}
[Serializable]
public class parent
{
public string a;
}
[Serializable]
public class children : parent
{
public string b;
}
public static DeserializeBytes(byte[] byteData)
{
//byteData数据,其实是:{ a = "1", b = "2" } 也就是children对象得到的二进制数据流
parent a = Program.DeserializeByBytes<parent>(byteData);
children b = a as children;
Console.WriteLine(JsonConvert.SerializeObject(b));
}
猜猜结果是什么?
很奇怪?是不是,我是先反序列化成的父对象:parent对象,parent对象里没有属性b,但是我将父对象AS成子对象时,子对象children的属性b中居然有值,是不是很神奇!!!
同样的情况,我们使用JsonConvert的序列化和反序列化做一遍,结果如下:
var cc = new children { a = "1", b = "2" };
var ccStr = JsonConvert.SerializeObject(cc);
parent p = JsonConvert.DeserializeObject<parent>(ccStr);
Console.WriteLine(JsonConvert.SerializeObject(p));
children c = p as children;
Console.WriteLine(JsonConvert.SerializeObject(c));
Console.Read();
是不是很奇怪? 妹的,真是神奇了,最后询问我们的老大才知道,划重点了哈:
重点:通过二级制流序列化和反序列化的对象呢,属性值并不会丢失!!! 而通过JsonConvert进行的string类型的序列化反序列化,多余的属性值会丢失!!! 就是真么神奇!
本人觉得,应该是和机制有关,通过二进制转换的数据,多余的数据计算机会始终记录着,毕竟计算机本身就是二进制的。而通过JsonConvert的方式,它会默认去匹配属性去,没有匹配上的属性会直接丢失。
指针很简单
------引子
学计算机语言,首先推荐C语言.无论是数据结构还是算法,站在C语言的角度,会让我们理解的更加清晰透彻.
但是,指针不太"友好",让很多人抓狂,头疼.不少人选择了放弃,绕行.百度上有千千万个解决方法,而我们放弃的理
由和简单,路在脚下,向前还?是向后?
C语言之所以经久不衰,就是因为指针的存在.本篇将帮助大家突破指针这个瓶颈.
1.指针和指针变量(通常我们叙述时会把指针变量简称为指针,实际他们含义并不一样)
指针:0x7ffe38fea3e0
指针变量:char *data;(*data就是指针变量)
2.指针和函数的关系(给子函数传多个值时用到(注意:你要不知道给什么,请自觉抄写关于指针案例,10遍))
需要提前掌握:函数的设计(返回值 函数名 参数),不清楚,请问百度;
子函数能不能静态申请空间,动态呢?会出现啥情况?
子函数什么时候是指针?
函数可以返回地址码?
此时此刻,热心网友早已经为我们准备好了,我们耐心的去博客园/csdn找,绝对可以找到,讲的非常专业.
3.指针与字符串
这个也百度,当然我不是糟老头啊.对于很对新人来说,缺少的是独自探索能力,遇到问题先去文别人,不懂的地方都是,这个老师没讲,那个书本没有,对于程序员而言,我们需要自己想办法.如果一直依靠问别人,是远远不够的.
4.指针数组、二级指针、函数指针、指针函数、二维数组、void *
指针数组:是一个数组,每一项都是指针(处理多个字符串)
案例:char *str[5] = {NULL};
二级指针:
int data = 0;
int *p = NULL;
p = &data; <-------(这是二级指针)
int **q = NULL; <------(这也是二级指针)
指针数组也是(不知道,不知道百度回炉数组去)
函数指针:
回调函数是啥?
函数如何作为另一个函数的参数,有啥案例?
自己百度!
指针函数:(函数参数返回值是指针的函数)
二维数组: char[2][3]data;(有2个空间,每个空间大小为3)
void *:“不确定类型指针
https://www.cnblogs.com/yuanyongbin/p/8058755.html自己去看
当我们接触到新的知识时,反复的查找,总结练习,才能达突破某一瓶颈,抵达下一个佳境,C语言的开发速度很难跟上社会需求的速度,前人为我们已经整理好了很多宝贵的心得.但是探索精神需要稀缺,还是那句话,不会百度想办法,当你工作几年后你会感谢曾今的自己,知识、机会向来都是自己去找的.
多百度,多和同事交流,多看书,多总结,成功都是在这些废话中.
什么是研究
research
就是re -search
不同的寻找搜索
这就是研究,因为我们在探索未知区域
我们只能搜索
作者:Eleven
来源:公众号【软谋net】
【前言】
.Net Core开源&跨平台,已经肉眼可见将成为.Net平台的未来,在企业招聘需求上已经频频见到,接触到很多公司内部都已经开始尝试Core的项目了,尤其是腾讯的财付通全部是基于Core+微服务搭建的,让人倍感振奋!Eleven最近出个专题,以当下最新的Asp.Net Core 2.2 Preview3为版本,给大家来一套系统教程,希望小伙伴儿们能多多关注!
【环境搭建】
我这边使用的VisualStudio版本为2017企业版15.7.4(并不是最新版本,专业版社区版也都是可以的)。之前安装是自带的Core是1.1版本,现在需要安装最新的sdk(dotnet-sdk-2.2.100-preview3-009430-win-x64.exe),以及最新的runtime(dotnet-runtime-2.2.0-preview3-27014-02-win-x64)。相关环境配置,需要的话可以关注底部公众号后,联系助教老师获取!
【项目建立】
下面开始动手建立Asp.Net Core2.2项目了,添加项目,选择Web,然后选择 ASP.NET Core Web应用程序模板,另外那个是原来的Framework版本的。
这里选择.NET Core,然后选择最新的ASP.NET Core2.2,选择下面的MVC应用程序,点击确定即可完成创建!建立完后的项目如下,一个典型的MVC项目,但是跟Framework下的有明显差异,增加了Program和Startup,这二位将是本文的主角了!
【Program】
看到Program,应该有种很亲切的感觉,包括里面的Main方法,这就是整个程序的入口。实际上,我们建立的这个项目,本质就是个控制台程序而已,查看项目属性可以得知。但为啥这个Program能当成MVC网站呢?
秘密就是那个CreateDefaultBuilder方法,这里面是启动一个Kestrel的服务器来完成请求的监听和响应的,在以前Core版本里,这里还有很多的配置项,现在已经内置为一个Default了。然后这里简单理解下,就是初始化一个服务器,然后Run一下,我们的Web服务器就算是启动了。其中在初始化服务器的时候,使用了一个Startup类,下面来详析一番!
【Startup】
在 ASP.NET Core 中,Startup 类提供了应用程序的入口,而且在所有应用程序中都有 Startup 类。ASP.NET 会在主程序集中搜索名为 Startup 的类(在任何命名空间下)。ASP.NET 并不关心 Startup 类是不是定义为 public,如果它符合命名规范,ASP.NET 将继续加载它。如果有多个 Startup 类,也不会触发异常,ASP.NET 将基于命名空间选择其中一个(匹配项目的根命名空间优先,否则使用第一个按字母排列的命名空间中的类)。
打开Startup类,大概分三块,这个是典型的构造函数注入,完成了一个叫IConfiguration类型变量的注入,至于是怎么注入的,后文中会讲到。这个变量是用来读取配置文件的,跟以前Framework下那个System.ConfigurationManager类差不多的。
然后是ConfigureServices方法,上面的注释描述的很清楚,是交给运行时环境调用的方法,然后用来给容器注册服务的(跟刚才说到的注入一致)。在Asp.Net Core里面,IOC容器是直接内置了的,也就是这个IServiceCollection。感兴趣的小伙伴儿可以去尝试下,直接nuget就可以下载Microsoft.Extensions.DependencyInjection,跟常见的容器用法几乎一样的,后面单独开文章再讲这个。这里完成全部需要依赖注入对象的初始化。
最下面是Configure方法,也是由运行时环境调用的,用来配置HTTP请求的处理管道的。Web的本质就是对Http请求的处理,最终得到一个响应结果,而这个方法,清晰的描述了,该如何去处理请求。
【内置服务和启动】
下面我就可以启动网站了,以前在做网站开发测试的时候,习惯性的去指定一下网站的端口和默认页,但是现在项目类型是控制台项目,相关的配置现在转移到项目的Properties--->launchSettings.json文件里面,可以在这里修改生效!顺便说一下,因为建立项目的时候,勾选了SSL支持,那么这里启动的会是https的Url,而且这个sslPort好像只能是以443开头,否则可能会无法访问。
然后一个完全没有做任何修改的Asp.Net Core2.2的项目就运行起来啦!
简单说一下加密解密:
加密解密有挺多方式去实现,今天呢我做为宇宙第一帅的人就给大家来分享以下源代码!听清楚是源代码哦!!
话不多说上干货
1:MD5加密/解密
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4 using System.Web;
5 using System.Text.RegularExpressions;
6
7 namespace hic.Common
8 {
9 public class SecurityHelper
10 {
11 /// <summary>
12 /// MD5字符串加密
13 /// </summary>
14 /// <param name="source">待加密字符串</param>
15 /// <returns></returns>
16 public static string MD5(string source)
17 {
18 return MD5(source, true);
19 }
20
21 /// <summary>
22 /// MD5字符串加密
23 /// </summary>
24 /// <param name="source">待加密字符串</param>
25 /// <param name="ishalf">加密是16位还是32位,如果为true则是16位。</param>
26 /// <returns></returns>
27 public static string MD5(string source, bool ishalf)
28 {
29 string outputStr = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(source, "MD5").ToLower();
30 if (ishalf)//16位MD5加密(取32位加密的9~25字符)
31 outputStr = outputStr.Substring(8, 16);
32 return outputStr;
33 }
34
35 /// <summary>
36 /// 对字符串进行Base64编码
37 /// </summary>
38 /// <param name="source">待编码字符串</param>
39 /// <returns></returns>
40 public static string EncodeBase64(string source)
41 {
42 UnicodeEncoding code = new UnicodeEncoding();
43 byte[] bytes = code.GetBytes(source);
44 return Convert.ToBase64String(bytes);
45 }
46
47 /// <summary>
48 /// 对字符串进行Base64解码
49 /// </summary>
50 /// <param name="source">待解码字符串</param>
51 /// <returns></returns>
52 public static string DecodeBase64(string source)
53 {
54 UnicodeEncoding code = new UnicodeEncoding();
55 byte[] bytes = Convert.FromBase64String(source);
56 return code.GetString(bytes);
57 }
58
59 /// <summary>
60 /// 检查当前IP是否是受限IP
61 /// </summary>
62 /// <param name="LimitedIP">受限的IP,格式如:192.168.1.110|212.235.*.*|232.*.*.*</param>
63 /// <returns>返回true表示IP未受到限制</returns>
64 public static bool CheckIPIsLimited(string limitedIP)
65 {
66 string currentIP = GetUserIP();
67 if (limitedIP == null || limitedIP.Trim() == string.Empty)
68 return true;
69 limitedIP.Replace(".", @"\.");
70 limitedIP.Replace("*", @"[^\.]{1,3}");
71 Regex reg = new Regex(limitedIP, RegexOptions.Compiled);
72 Match match = reg.Match(currentIP);
73 return !match.Success;
74 }
75
76 /// <summary>
77 /// 得到用户IP
78 /// </summary>
79 /// <returns></returns>
80 public static string GetUserIP()
81 {
82 return HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
83 }
84 }
85 }
2:DES加密/解密类
1 using System;
2 using System.Security.Cryptography;
3 using System.Text;
4 namespace Maticsoft.Common.DEncrypt
5 {
6 /// <summary>
7 /// DES加密/解密类。
8 /// LiTianPing
9 /// </summary>
10 public class DESEncrypt
11 {
12 public DESEncrypt()
13 {
14 }
15
16 #region ========加密========
17
18 /// <summary>
19 /// 加密
20 /// </summary>
21 /// <param name="Text"></param>
22 /// <returns></returns>
23 public static string Encrypt(string Text)
24 {
25 return Encrypt(Text,"MATICSOFT");
26 }
27 /// <summary>
28 /// 加密数据
29 /// </summary>
30 /// <param name="Text"></param>
31 /// <param name="sKey"></param>
32 /// <returns></returns>
33 public static string Encrypt(string Text,string sKey)
34 {
35 DESCryptoServiceProvider des = new DESCryptoServiceProvider();
36 byte[] inputByteArray;
37 inputByteArray=Encoding.Default.GetBytes(Text);
38 des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
39 des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
40 System.IO.MemoryStream ms=new System.IO.MemoryStream();
41 CryptoStream cs=new CryptoStream(ms,des.CreateEncryptor(),CryptoStreamMode.Write);
42 cs.Write(inputByteArray,0,inputByteArray.Length);
43 cs.FlushFinalBlock();
44 StringBuilder ret=new StringBuilder();
45 foreach( byte b in ms.ToArray())
46 {
47 ret.AppendFormat("{0:X2}",b);
48 }
49 return ret.ToString();
50 }
51
52 #endregion
53
54 #region ========解密========
55
56
57 /// <summary>
58 /// 解密
59 /// </summary>
60 /// <param name="Text"></param>
61 /// <returns></returns>
62 public static string Decrypt(string Text)
63 {
64 return Decrypt(Text,"MATICSOFT");
65 }
66 /// <summary>
67 /// 解密数据
68 /// </summary>
69 /// <param name="Text"></param>
70 /// <param name="sKey"></param>
71 /// <returns></returns>
72 public static string Decrypt(string Text,string sKey)
73 {
74 DESCryptoServiceProvider des = new DESCryptoServiceProvider();
75 int len;
76 len=Text.Length/2;
77 byte[] inputByteArray = new byte[len];
78 int x,i;
79 for(x=0;x<len;x++)
80 {
81 i = Convert.ToInt32(Text.Substring(x * 2, 2), 16);
82 inputByteArray[x]=(byte)i;
83 }
84 des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
85 des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
86 System.IO.MemoryStream ms=new System.IO.MemoryStream();
87 CryptoStream cs=new CryptoStream(ms,des.CreateDecryptor(),CryptoStreamMode.Write);
88 cs.Write(inputByteArray,0,inputByteArray.Length);
89 cs.FlushFinalBlock();
90 return Encoding.Default.GetString(ms.ToArray());
91 }
92
93 #endregion
94
95
96 }
97 }
3:RSA加密解密及RSA签名和验证
1 using System;
2 using System.Text;
3 using System.Security.Cryptography;
4 namespace Maticsoft.Common.DEncrypt
5 {
6 /// <summary>
7 /// RSA加密解密及RSA签名和验证
8 /// </summary>
9 public class RSACryption
10 {
11 public RSACryption()
12 {
13 }
14
15
16 #region RSA 加密解密
17
18 #region RSA 的密钥产生
19
20 /// <summary>
21 /// RSA 的密钥产生 产生私钥 和公钥
22 /// </summary>
23 /// <param name="xmlKeys"></param>
24 /// <param name="xmlPublicKey"></param>
25 public void RSAKey(out string xmlKeys,out string xmlPublicKey)
26 {
27 System.Security.Cryptography.RSACryptoServiceProvider rsa=new RSACryptoServiceProvider();
28 xmlKeys=rsa.ToXmlString(true);
29 xmlPublicKey = rsa.ToXmlString(false);
30 }
31 #endregion
32
33 #region RSA的加密函数
34 //##############################################################################
35 //RSA 方式加密
36 //说明KEY必须是XML的行式,返回的是字符串
37 //在有一点需要说明!!该加密方式有 长度 限制的!!
38 //##############################################################################
39
40 //RSA的加密函数 string
41 public string RSAEncrypt(string xmlPublicKey,string m_strEncryptString )
42 {
43
44 byte[] PlainTextBArray;
45 byte[] CypherTextBArray;
46 string Result;
47 RSACryptoServiceProvider rsa=new RSACryptoServiceProvider();
48 rsa.FromXmlString(xmlPublicKey);
49 PlainTextBArray = (new UnicodeEncoding()).GetBytes(m_strEncryptString);
50 CypherTextBArray = rsa.Encrypt(PlainTextBArray, false);
51 Result=Convert.ToBase64String(CypherTextBArray);
52 return Result;
53
54 }
55 //RSA的加密函数 byte[]
56 public string RSAEncrypt(string xmlPublicKey,byte[] EncryptString )
57 {
58
59 byte[] CypherTextBArray;
60 string Result;
61 RSACryptoServiceProvider rsa=new RSACryptoServiceProvider();
62 rsa.FromXmlString(xmlPublicKey);
63 CypherTextBArray = rsa.Encrypt(EncryptString, false);
64 Result=Convert.ToBase64String(CypherTextBArray);
65 return Result;
66
67 }
68 #endregion
69
70 #region RSA的解密函数
71 //RSA的解密函数 string
72 public string RSADecrypt(string xmlPrivateKey, string m_strDecryptString )
73 {
74 byte[] PlainTextBArray;
75 byte[] DypherTextBArray;
76 string Result;
77 System.Security.Cryptography.RSACryptoServiceProvider rsa=new RSACryptoServiceProvider();
78 rsa.FromXmlString(xmlPrivateKey);
79 PlainTextBArray =Convert.FromBase64String(m_strDecryptString);
80 DypherTextBArray=rsa.Decrypt(PlainTextBArray, false);
81 Result=(new UnicodeEncoding()).GetString(DypherTextBArray);
82 return Result;
83
84 }
85
86 //RSA的解密函数 byte
87 public string RSADecrypt(string xmlPrivateKey, byte[] DecryptString )
88 {
89 byte[] DypherTextBArray;
90 string Result;
91 System.Security.Cryptography.RSACryptoServiceProvider rsa=new RSACryptoServiceProvider();
92 rsa.FromXmlString(xmlPrivateKey);
93 DypherTextBArray=rsa.Decrypt(DecryptString, false);
94 Result=(new UnicodeEncoding()).GetString(DypherTextBArray);
95 return Result;
96
97 }
98 #endregion
99
100 #endregion
101
102 #region RSA数字签名
103
104 #region 获取Hash描述表
105 //获取Hash描述表
106 public bool GetHash(string m_strSource, ref byte[] HashData)
107 {
108 //从字符串中取得Hash描述
109 byte[] Buffer;
110 System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");
111 Buffer = System.Text.Encoding.GetEncoding("GB2312").GetBytes(m_strSource);
112 HashData = MD5.ComputeHash(Buffer);
113
114 return true;
115 }
116
117 //获取Hash描述表
118 public bool GetHash(string m_strSource, ref string strHashData)
119 {
120
121 //从字符串中取得Hash描述
122 byte[] Buffer;
123 byte[] HashData;
124 System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");
125 Buffer = System.Text.Encoding.GetEncoding("GB2312").GetBytes(m_strSource);
126 HashData = MD5.ComputeHash(Buffer);
127
128 strHashData = Convert.ToBase64String(HashData);
129 return true;
130
131 }
132
133 //获取Hash描述表
134 public bool GetHash(System.IO.FileStream objFile, ref byte[] HashData)
135 {
136
137 //从文件中取得Hash描述
138 System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");
139 HashData = MD5.ComputeHash(objFile);
140 objFile.Close();
141
142 return true;
143
144 }
145
146 //获取Hash描述表
147 public bool GetHash(System.IO.FileStream objFile, ref string strHashData)
148 {
149
150 //从文件中取得Hash描述
151 byte[] HashData;
152 System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");
153 HashData = MD5.ComputeHash(objFile);
154 objFile.Close();
155
156 strHashData = Convert.ToBase64String(HashData);
157
158 return true;
159
160 }
161 #endregion
162
163 #region RSA签名
164 //RSA签名
165 public bool SignatureFormatter(string p_strKeyPrivate, byte[] HashbyteSignature, ref byte[] EncryptedSignatureData)
166 {
167
168 System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
169
170 RSA.FromXmlString(p_strKeyPrivate);
171 System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
172 //设置签名的算法为MD5
173 RSAFormatter.SetHashAlgorithm("MD5");
174 //执行签名
175 EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);
176
177 return true;
178
179 }
180
181 //RSA签名
182 public bool SignatureFormatter(string p_strKeyPrivate, byte[] HashbyteSignature, ref string m_strEncryptedSignatureData)
183 {
184
185 byte[] EncryptedSignatureData;
186
187 System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
188
189 RSA.FromXmlString(p_strKeyPrivate);
190 System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
191 //设置签名的算法为MD5
192 RSAFormatter.SetHashAlgorithm("MD5");
193 //执行签名
194 EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);
195
196 m_strEncryptedSignatureData = Convert.ToBase64String(EncryptedSignatureData);
197
198 return true;
199
200 }
201
202 //RSA签名
203 public bool SignatureFormatter(string p_strKeyPrivate, string m_strHashbyteSignature, ref byte[] EncryptedSignatureData)
204 {
205
206 byte[] HashbyteSignature;
207
208 HashbyteSignature = Convert.FromBase64String(m_strHashbyteSignature);
209 System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
210
211 RSA.FromXmlString(p_strKeyPrivate);
212 System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
213 //设置签名的算法为MD5
214 RSAFormatter.SetHashAlgorithm("MD5");
215 //执行签名
216 EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);
217
218 return true;
219
220 }
221
222 //RSA签名
223 public bool SignatureFormatter(string p_strKeyPrivate, string m_strHashbyteSignature, ref string m_strEncryptedSignatureData)
224 {
225
226 byte[] HashbyteSignature;
227 byte[] EncryptedSignatureData;
228
229 HashbyteSignature = Convert.FromBase64String(m_strHashbyteSignature);
230 System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
231
232 RSA.FromXmlString(p_strKeyPrivate);
233 System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
234 //设置签名的算法为MD5
235 RSAFormatter.SetHashAlgorithm("MD5");
236 //执行签名
237 EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);
238
239 m_strEncryptedSignatureData = Convert.ToBase64String(EncryptedSignatureData);
240
241 return true;
242
243 }
244 #endregion
245
246 #region RSA 签名验证
247
248 public bool SignatureDeformatter(string p_strKeyPublic, byte[] HashbyteDeformatter, byte[] DeformatterData)
249 {
250
251 System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
252
253 RSA.FromXmlString(p_strKeyPublic);
254 System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
255 //指定解密的时候HASH算法为MD5
256 RSADeformatter.SetHashAlgorithm("MD5");
257
258 if(RSADeformatter.VerifySignature(HashbyteDeformatter,DeformatterData))
259 {
260 return true;
261 }
262 else
263 {
264 return false;
265 }
266
267 }
268
269 public bool SignatureDeformatter(string p_strKeyPublic, string p_strHashbyteDeformatter, byte[] DeformatterData)
270 {
271
272 byte[] HashbyteDeformatter;
273
274 HashbyteDeformatter = Convert.FromBase64String(p_strHashbyteDeformatter);
275
276 System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
277
278 RSA.FromXmlString(p_strKeyPublic);
279 System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
280 //指定解密的时候HASH算法为MD5
281 RSADeformatter.SetHashAlgorithm("MD5");
282
283 if(RSADeformatter.VerifySignature(HashbyteDeformatter,DeformatterData))
284 {
285 return true;
286 }
287 else
288 {
289 return false;
290 }
291
292 }
293
294 public bool SignatureDeformatter(string p_strKeyPublic, byte[] HashbyteDeformatter, string p_strDeformatterData)
295 {
296
297 byte[] DeformatterData;
298
299 System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
300
301 RSA.FromXmlString(p_strKeyPublic);
302 System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
303 //指定解密的时候HASH算法为MD5
304 RSADeformatter.SetHashAlgorithm("MD5");
305
306 DeformatterData =Convert.FromBase64String(p_strDeformatterData);
307
308 if(RSADeformatter.VerifySignature(HashbyteDeformatter,DeformatterData))
309 {
310 return true;
311 }
312 else
313 {
314 return false;
315 }
316
317 }
318
319 public bool SignatureDeformatter(string p_strKeyPublic, string p_strHashbyteDeformatter, string p_strDeformatterData)
320 {
321
322 byte[] DeformatterData;
323 byte[] HashbyteDeformatter;
324
325 HashbyteDeformatter = Convert.FromBase64String(p_strHashbyteDeformatter);
326 System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
327
328 RSA.FromXmlString(p_strKeyPublic);
329 System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
330 //指定解密的时候HASH算法为MD5
331 RSADeformatter.SetHashAlgorithm("MD5");
332
333 DeformatterData =Convert.FromBase64String(p_strDeformatterData);
334
335 if(RSADeformatter.VerifySignature(HashbyteDeformatter,DeformatterData))
336 {
337 return true;
338 }
339 else
340 {
341 return false;
342 }
343
344 }
345
346
347 #endregion
348
349
350 #endregion
351
352 }
353 }
4:哈希加密/解密
1 using System;
2 using System.Text;
3 using System.Security.Cryptography;
4 namespace Maticsoft.Common.DEncrypt
5 {
6 /// <summary>
7 /// 得到随机安全码(哈希加密)。
8 /// </summary>
9 public class HashEncode
10 {
11 public HashEncode()
12 {
13 //
14 // TODO: 在此处添加构造函数逻辑
15 //
16 }
17 /// <summary>
18 /// 得到随机哈希加密字符串
19 /// </summary>
20 /// <returns></returns>
21 public static string GetSecurity()
22 {
23 string Security = HashEncoding(GetRandomValue());
24 return Security;
25 }
26 /// <summary>
27 /// 得到一个随机数值
28 /// </summary>
29 /// <returns></returns>
30 public static string GetRandomValue()
31 {
32 Random Seed = new Random();
33 string RandomVaule = Seed.Next(1, int.MaxValue).ToString();
34 return RandomVaule;
35 }
36 /// <summary>
37 /// 哈希加密一个字符串
38 /// </summary>
39 /// <param name="Security"></param>
40 /// <returns></returns>
41 public static string HashEncoding(string Security)
42 {
43 byte[] Value;
44 UnicodeEncoding Code = new UnicodeEncoding();
45 byte[] Message = Code.GetBytes(Security);
46 SHA512Managed Arithmetic = new SHA512Managed();
47 Value = Arithmetic.ComputeHash(Message);
48 Security = "";
49 foreach(byte o in Value)
50 {
51 Security += (int) o + "O";
52 }
53 return Security;
54 }
55 }
56 }
5:Encrypt
1 using System;
2 using System.Security.Cryptography;
3 using System.Text;
4 namespace Maticsoft.Common.DEncrypt
5 {
6 /// <summary>
7 /// Encrypt 的摘要说明。
8 /// LiTianPing
9 /// </summary>
10 public class DEncrypt
11 {
12 /// <summary>
13 /// 构造方法
14 /// </summary>
15 public DEncrypt()
16 {
17 }
18
19 #region 使用 缺省密钥字符串 加密/解密string
20
21 /// <summary>
22 /// 使用缺省密钥字符串加密string
23 /// </summary>
24 /// <param name="original">明文</param>
25 /// <returns>密文</returns>
26 public static string Encrypt(string original)
27 {
28 return Encrypt(original,"MATICSOFT");
29 }
30 /// <summary>
31 /// 使用缺省密钥字符串解密string
32 /// </summary>
33 /// <param name="original">密文</param>
34 /// <returns>明文</returns>
35 public static string Decrypt(string original)
36 {
37 return Decrypt(original,"MATICSOFT",System.Text.Encoding.Default);
38 }
39
40 #endregion
41
42 #region 使用 给定密钥字符串 加密/解密string
43 /// <summary>
44 /// 使用给定密钥字符串加密string
45 /// </summary>
46 /// <param name="original">原始文字</param>
47 /// <param name="key">密钥</param>
48 /// <param name="encoding">字符编码方案</param>
49 /// <returns>密文</returns>
50 public static string Encrypt(string original, string key)
51 {
52 byte[] buff = System.Text.Encoding.Default.GetBytes(original);
53 byte[] kb = System.Text.Encoding.Default.GetBytes(key);
54 return Convert.ToBase64String(Encrypt(buff,kb));
55 }
56 /// <summary>
57 /// 使用给定密钥字符串解密string
58 /// </summary>
59 /// <param name="original">密文</param>
60 /// <param name="key">密钥</param>
61 /// <returns>明文</returns>
62 public static string Decrypt(string original, string key)
63 {
64 return Decrypt(original,key,System.Text.Encoding.Default);
65 }
66
67 /// <summary>
68 /// 使用给定密钥字符串解密string,返回指定编码方式明文
69 /// </summary>
70 /// <param name="encrypted">密文</param>
71 /// <param name="key">密钥</param>
72 /// <param name="encoding">字符编码方案</param>
73 /// <returns>明文</returns>
74 public static string Decrypt(string encrypted, string key,Encoding encoding)
75 {
76 byte[] buff = Convert.FromBase64String(encrypted);
77 byte[] kb = System.Text.Encoding.Default.GetBytes(key);
78 return encoding.GetString(Decrypt(buff,kb));
79 }
80 #endregion
81
82 #region 使用 缺省密钥字符串 加密/解密/byte[]
83 /// <summary>
84 /// 使用缺省密钥字符串解密byte[]
85 /// </summary>
86 /// <param name="encrypted">密文</param>
87 /// <param name="key">密钥</param>
88 /// <returns>明文</returns>
89 public static byte[] Decrypt(byte[] encrypted)
90 {
91 byte[] key = System.Text.Encoding.Default.GetBytes("MATICSOFT");
92 return Decrypt(encrypted,key);
93 }
94 /// <summary>
95 /// 使用缺省密钥字符串加密
96 /// </summary>
97 /// <param name="original">原始数据</param>
98 /// <param name="key">密钥</param>
99 /// <returns>密文</returns>
100 public static byte[] Encrypt(byte[] original)
101 {
102 byte[] key = System.Text.Encoding.Default.GetBytes("MATICSOFT");
103 return Encrypt(original,key);
104 }
105 #endregion
106
107 #region 使用 给定密钥 加密/解密/byte[]
108
109 /// <summary>
110 /// 生成MD5摘要
111 /// </summary>
112 /// <param name="original">数据源</param>
113 /// <returns>摘要</returns>
114 public static byte[] MakeMD5(byte[] original)
115 {
116 MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
117 byte[] keyhash = hashmd5.ComputeHash(original);
118 hashmd5 = null;
119 return keyhash;
120 }
121
122
123 /// <summary>
124 /// 使用给定密钥加密
125 /// </summary>
126 /// <param name="original">明文</param>
127 /// <param name="key">密钥</param>
128 /// <returns>密文</returns>
129 public static byte[] Encrypt(byte[] original, byte[] key)
130 {
131 TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
132 des.Key = MakeMD5(key);
133 des.Mode = CipherMode.ECB;
134
135 return des.CreateEncryptor().TransformFinalBlock(original, 0, original.Length);
136 }
137
138 /// <summary>
139 /// 使用给定密钥解密数据
140 /// </summary>
141 /// <param name="encrypted">密文</param>
142 /// <param name="key">密钥</param>
143 /// <returns>明文</returns>
144 public static byte[] Decrypt(byte[] encrypted, byte[] key)
145 {
146 TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
147 des.Key = MakeMD5(key);
148 des.Mode = CipherMode.ECB;
149
150 return des.CreateDecryptor().TransformFinalBlock(encrypted, 0, encrypted.Length);
151 }
152
153 #endregion
154
155
156
157
158 }
159 }
WebApi程序可在方法参数前加[FromBody]标识,表示该参数值应该从请求的Body中获取,而不是从URL中获取。
从URL获取参数值的方式的弊端是URL有长度限制,当超过浏览器的最大URL长度时请求将被浏览器拒绝,根本不会发出去。
因此,当参数值过大时需要用[FromBody]参数进行传输。
以下是WebApi接口定义,很简单,只为说明用法:
private string SendObjectAsJsonInBody(string url, object objBody)
{
string result;
HttpClient client;
StringContent content;
client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
content = new StringContent(ParkingSqlHelper.JsonHelper.SerializeObject(objBody), Encoding.UTF8, "application/json");
result = client.PostAsync(url, content).Result.Content.ReadAsStringAsync().Result;
return result;
}
protected HttpResponseMessage GetJsonResponse(string json)
{
HttpResponseMessage result;
result = new HttpResponseMessage { Content = new StringContent(json, Encoding.GetEncoding("UTF-8"), "application/json") };
//result.Headers.Add("Access-Control-Allow-Origin", "*"); //设置HTTP头允许 返回的跨域信息给浏览器解析
return result;
}
需要注意的是: [FromBody] 参数不能是基本的数据类型(如byte、int、bool、DateTime、string等)。
以下是C#客户端请求的代码
/// <summary>
/// 通过请求体向指定URL传输数据
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="objBody">需传输的数据</param>
/// <returns></returns>
private string SendObjectAsJsonInBody(string url, object objBody)
{
string result;
HttpClient client;
StringContent content;
client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
content = new StringContent(ParkingSqlHelper.JsonHelper.SerializeObject(objBody), Encoding.UTF8, "application/json");
result = client.PostAsync(url, content).Result.Content.ReadAsStringAsync().Result;
return result;
}
以下是JQuery请求的代码
function Send(url, objBody) {
$.ajax({
url: url,
type: "post",
data: JSON.stringify(objBody),
contentType: "application/json; charset=UTF-8",
timeout: 5000,
success: function (result) {
alert("data = " + JSON.stringify(result));
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
});
};
---------------------
作者:Eleven
来源:公众号【软谋net】
【前言】
.Net Core开源&跨平台,已经肉眼可见将成为.Net平台的未来,在企业招聘需求上已经频频见到,接触到很多公司内部都已经开始尝试Core的项目了,尤其是腾讯的财付通全部是基于Core+微服务搭建的,让人倍感振奋!Eleven最近出个专题,以当下最新的Asp.Net Core 2.2 Preview3为版本,给大家来一套系统教程,希望小伙伴儿们能多多关注!
【环境搭建】
我这边使用的VisualStudio版本为2017企业版15.7.4(并不是最新版本,专业版社区版也都是可以的)。之前安装是自带的Core是1.1版本,现在需要安装最新的sdk(dotnet-sdk-2.2.100-preview3-009430-win-x64.exe),以及最新的runtime(dotnet-runtime-2.2.0-preview3-27014-02-win-x64)。相关环境配置,需要的话可以关注底部公众号后,联系助教老师获取!
【项目建立】
下面开始动手建立Asp.Net Core2.2项目了,添加项目,选择Web,然后选择 ASP.NET Core Web应用程序模板,另外那个是原来的Framework版本的。
这里选择.NET Core,然后选择最新的ASP.NET Core2.2,选择下面的MVC应用程序,点击确定即可完成创建!建立完后的项目如下,一个典型的MVC项目,但是跟Framework下的有明显差异,增加了Program和Startup,这二位将是本文的主角了!
【Program】
看到Program,应该有种很亲切的感觉,包括里面的Main方法,这就是整个程序的入口。实际上,我们建立的这个项目,本质就是个控制台程序而已,查看项目属性可以得知。但为啥这个Program能当成MVC网站呢?
秘密就是那个CreateDefaultBuilder方法,这里面是启动一个Kestrel的服务器来完成请求的监听和响应的,在以前Core版本里,这里还有很多的配置项,现在已经内置为一个Default了。然后这里简单理解下,就是初始化一个服务器,然后Run一下,我们的Web服务器就算是启动了。其中在初始化服务器的时候,使用了一个Startup类,下面来详析一番!
【Startup】
在 ASP.NET Core 中,Startup 类提供了应用程序的入口,而且在所有应用程序中都有 Startup 类。ASP.NET 会在主程序集中搜索名为 Startup 的类(在任何命名空间下)。ASP.NET 并不关心 Startup 类是不是定义为 public,如果它符合命名规范,ASP.NET 将继续加载它。如果有多个 Startup 类,也不会触发异常,ASP.NET 将基于命名空间选择其中一个(匹配项目的根命名空间优先,否则使用第一个按字母排列的命名空间中的类)。
打开Startup类,大概分三块,这个是典型的构造函数注入,完成了一个叫IConfiguration类型变量的注入,至于是怎么注入的,后文中会讲到。这个变量是用来读取配置文件的,跟以前Framework下那个System.ConfigurationManager类差不多的。
然后是ConfigureServices方法,上面的注释描述的很清楚,是交给运行时环境调用的方法,然后用来给容器注册服务的(跟刚才说到的注入一致)。在Asp.Net Core里面,IOC容器是直接内置了的,也就是这个IServiceCollection。感兴趣的小伙伴儿可以去尝试下,直接nuget就可以下载Microsoft.Extensions.DependencyInjection,跟常见的容器用法几乎一样的,后面单独开文章再讲这个。这里完成全部需要依赖注入对象的初始化。
最下面是Configure方法,也是由运行时环境调用的,用来配置HTTP请求的处理管道的。Web的本质就是对Http请求的处理,最终得到一个响应结果,而这个方法,清晰的描述了,该如何去处理请求。
【内置服务和启动】
下面我就可以启动网站了,以前在做网站开发测试的时候,习惯性的去指定一下网站的端口和默认页,但是现在项目类型是控制台项目,相关的配置现在转移到项目的Properties--->launchSettings.json文件里面,可以在这里修改生效!顺便说一下,因为建立项目的时候,勾选了SSL支持,那么这里启动的会是https的Url,而且这个sslPort好像只能是以443开头,否则可能会无法访问。
然后一个完全没有做任何修改的Asp.Net Core2.2的项目就运行起来啦!
简单说一下加密解密:
加密解密有挺多方式去实现,今天呢我做为宇宙第一帅的人就给大家来分享以下源代码!听清楚是源代码哦!!
话不多说上干货
1:MD5加密/解密
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4 using System.Web;
5 using System.Text.RegularExpressions;
6
7 namespace hic.Common
8 {
9 public class SecurityHelper
10 {
11 /// <summary>
12 /// MD5字符串加密
13 /// </summary>
14 /// <param name="source">待加密字符串</param>
15 /// <returns></returns>
16 public static string MD5(string source)
17 {
18 return MD5(source, true);
19 }
20
21 /// <summary>
22 /// MD5字符串加密
23 /// </summary>
24 /// <param name="source">待加密字符串</param>
25 /// <param name="ishalf">加密是16位还是32位,如果为true则是16位。</param>
26 /// <returns></returns>
27 public static string MD5(string source, bool ishalf)
28 {
29 string outputStr = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(source, "MD5").ToLower();
30 if (ishalf)//16位MD5加密(取32位加密的9~25字符)
31 outputStr = outputStr.Substring(8, 16);
32 return outputStr;
33 }
34
35 /// <summary>
36 /// 对字符串进行Base64编码
37 /// </summary>
38 /// <param name="source">待编码字符串</param>
39 /// <returns></returns>
40 public static string EncodeBase64(string source)
41 {
42 UnicodeEncoding code = new UnicodeEncoding();
43 byte[] bytes = code.GetBytes(source);
44 return Convert.ToBase64String(bytes);
45 }
46
47 /// <summary>
48 /// 对字符串进行Base64解码
49 /// </summary>
50 /// <param name="source">待解码字符串</param>
51 /// <returns></returns>
52 public static string DecodeBase64(string source)
53 {
54 UnicodeEncoding code = new UnicodeEncoding();
55 byte[] bytes = Convert.FromBase64String(source);
56 return code.GetString(bytes);
57 }
58
59 /// <summary>
60 /// 检查当前IP是否是受限IP
61 /// </summary>
62 /// <param name="LimitedIP">受限的IP,格式如:192.168.1.110|212.235.*.*|232.*.*.*</param>
63 /// <returns>返回true表示IP未受到限制</returns>
64 public static bool CheckIPIsLimited(string limitedIP)
65 {
66 string currentIP = GetUserIP();
67 if (limitedIP == null || limitedIP.Trim() == string.Empty)
68 return true;
69 limitedIP.Replace(".", @"\.");
70 limitedIP.Replace("*", @"[^\.]{1,3}");
71 Regex reg = new Regex(limitedIP, RegexOptions.Compiled);
72 Match match = reg.Match(currentIP);
73 return !match.Success;
74 }
75
76 /// <summary>
77 /// 得到用户IP
78 /// </summary>
79 /// <returns></returns>
80 public static string GetUserIP()
81 {
82 return HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
83 }
84 }
85 }
2:DES加密/解密类
1 using System;
2 using System.Security.Cryptography;
3 using System.Text;
4 namespace Maticsoft.Common.DEncrypt
5 {
6 /// <summary>
7 /// DES加密/解密类。
8 /// LiTianPing
9 /// </summary>
10 public class DESEncrypt
11 {
12 public DESEncrypt()
13 {
14 }
15
16 #region ========加密========
17
18 /// <summary>
19 /// 加密
20 /// </summary>
21 /// <param name="Text"></param>
22 /// <returns></returns>
23 public static string Encrypt(string Text)
24 {
25 return Encrypt(Text,"MATICSOFT");
26 }
27 /// <summary>
28 /// 加密数据
29 /// </summary>
30 /// <param name="Text"></param>
31 /// <param name="sKey"></param>
32 /// <returns></returns>
33 public static string Encrypt(string Text,string sKey)
34 {
35 DESCryptoServiceProvider des = new DESCryptoServiceProvider();
36 byte[] inputByteArray;
37 inputByteArray=Encoding.Default.GetBytes(Text);
38 des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
39 des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
40 System.IO.MemoryStream ms=new System.IO.MemoryStream();
41 CryptoStream cs=new CryptoStream(ms,des.CreateEncryptor(),CryptoStreamMode.Write);
42 cs.Write(inputByteArray,0,inputByteArray.Length);
43 cs.FlushFinalBlock();
44 StringBuilder ret=new StringBuilder();
45 foreach( byte b in ms.ToArray())
46 {
47 ret.AppendFormat("{0:X2}",b);
48 }
49 return ret.ToString();
50 }
51
52 #endregion
53
54 #region ========解密========
55
56
57 /// <summary>
58 /// 解密
59 /// </summary>
60 /// <param name="Text"></param>
61 /// <returns></returns>
62 public static string Decrypt(string Text)
63 {
64 return Decrypt(Text,"MATICSOFT");
65 }
66 /// <summary>
67 /// 解密数据
68 /// </summary>
69 /// <param name="Text"></param>
70 /// <param name="sKey"></param>
71 /// <returns></returns>
72 public static string Decrypt(string Text,string sKey)
73 {
74 DESCryptoServiceProvider des = new DESCryptoServiceProvider();
75 int len;
76 len=Text.Length/2;
77 byte[] inputByteArray = new byte[len];
78 int x,i;
79 for(x=0;x<len;x++)
80 {
81 i = Convert.ToInt32(Text.Substring(x * 2, 2), 16);
82 inputByteArray[x]=(byte)i;
83 }
84 des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
85 des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
86 System.IO.MemoryStream ms=new System.IO.MemoryStream();
87 CryptoStream cs=new CryptoStream(ms,des.CreateDecryptor(),CryptoStreamMode.Write);
88 cs.Write(inputByteArray,0,inputByteArray.Length);
89 cs.FlushFinalBlock();
90 return Encoding.Default.GetString(ms.ToArray());
91 }
92
93 #endregion
94
95
96 }
97 }
3:RSA加密解密及RSA签名和验证
1 using System;
2 using System.Text;
3 using System.Security.Cryptography;
4 namespace Maticsoft.Common.DEncrypt
5 {
6 /// <summary>
7 /// RSA加密解密及RSA签名和验证
8 /// </summary>
9 public class RSACryption
10 {
11 public RSACryption()
12 {
13 }
14
15
16 #region RSA 加密解密
17
18 #region RSA 的密钥产生
19
20 /// <summary>
21 /// RSA 的密钥产生 产生私钥 和公钥
22 /// </summary>
23 /// <param name="xmlKeys"></param>
24 /// <param name="xmlPublicKey"></param>
25 public void RSAKey(out string xmlKeys,out string xmlPublicKey)
26 {
27 System.Security.Cryptography.RSACryptoServiceProvider rsa=new RSACryptoServiceProvider();
28 xmlKeys=rsa.ToXmlString(true);
29 xmlPublicKey = rsa.ToXmlString(false);
30 }
31 #endregion
32
33 #region RSA的加密函数
34 //##############################################################################
35 //RSA 方式加密
36 //说明KEY必须是XML的行式,返回的是字符串
37 //在有一点需要说明!!该加密方式有 长度 限制的!!
38 //##############################################################################
39
40 //RSA的加密函数 string
41 public string RSAEncrypt(string xmlPublicKey,string m_strEncryptString )
42 {
43
44 byte[] PlainTextBArray;
45 byte[] CypherTextBArray;
46 string Result;
47 RSACryptoServiceProvider rsa=new RSACryptoServiceProvider();
48 rsa.FromXmlString(xmlPublicKey);
49 PlainTextBArray = (new UnicodeEncoding()).GetBytes(m_strEncryptString);
50 CypherTextBArray = rsa.Encrypt(PlainTextBArray, false);
51 Result=Convert.ToBase64String(CypherTextBArray);
52 return Result;
53
54 }
55 //RSA的加密函数 byte[]
56 public string RSAEncrypt(string xmlPublicKey,byte[] EncryptString )
57 {
58
59 byte[] CypherTextBArray;
60 string Result;
61 RSACryptoServiceProvider rsa=new RSACryptoServiceProvider();
62 rsa.FromXmlString(xmlPublicKey);
63 CypherTextBArray = rsa.Encrypt(EncryptString, false);
64 Result=Convert.ToBase64String(CypherTextBArray);
65 return Result;
66
67 }
68 #endregion
69
70 #region RSA的解密函数
71 //RSA的解密函数 string
72 public string RSADecrypt(string xmlPrivateKey, string m_strDecryptString )
73 {
74 byte[] PlainTextBArray;
75 byte[] DypherTextBArray;
76 string Result;
77 System.Security.Cryptography.RSACryptoServiceProvider rsa=new RSACryptoServiceProvider();
78 rsa.FromXmlString(xmlPrivateKey);
79 PlainTextBArray =Convert.FromBase64String(m_strDecryptString);
80 DypherTextBArray=rsa.Decrypt(PlainTextBArray, false);
81 Result=(new UnicodeEncoding()).GetString(DypherTextBArray);
82 return Result;
83
84 }
85
86 //RSA的解密函数 byte
87 public string RSADecrypt(string xmlPrivateKey, byte[] DecryptString )
88 {
89 byte[] DypherTextBArray;
90 string Result;
91 System.Security.Cryptography.RSACryptoServiceProvider rsa=new RSACryptoServiceProvider();
92 rsa.FromXmlString(xmlPrivateKey);
93 DypherTextBArray=rsa.Decrypt(DecryptString, false);
94 Result=(new UnicodeEncoding()).GetString(DypherTextBArray);
95 return Result;
96
97 }
98 #endregion
99
100 #endregion
101
102 #region RSA数字签名
103
104 #region 获取Hash描述表
105 //获取Hash描述表
106 public bool GetHash(string m_strSource, ref byte[] HashData)
107 {
108 //从字符串中取得Hash描述
109 byte[] Buffer;
110 System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");
111 Buffer = System.Text.Encoding.GetEncoding("GB2312").GetBytes(m_strSource);
112 HashData = MD5.ComputeHash(Buffer);
113
114 return true;
115 }
116
117 //获取Hash描述表
118 public bool GetHash(string m_strSource, ref string strHashData)
119 {
120
121 //从字符串中取得Hash描述
122 byte[] Buffer;
123 byte[] HashData;
124 System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");
125 Buffer = System.Text.Encoding.GetEncoding("GB2312").GetBytes(m_strSource);
126 HashData = MD5.ComputeHash(Buffer);
127
128 strHashData = Convert.ToBase64String(HashData);
129 return true;
130
131 }
132
133 //获取Hash描述表
134 public bool GetHash(System.IO.FileStream objFile, ref byte[] HashData)
135 {
136
137 //从文件中取得Hash描述
138 System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");
139 HashData = MD5.ComputeHash(objFile);
140 objFile.Close();
141
142 return true;
143
144 }
145
146 //获取Hash描述表
147 public bool GetHash(System.IO.FileStream objFile, ref string strHashData)
148 {
149
150 //从文件中取得Hash描述
151 byte[] HashData;
152 System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");
153 HashData = MD5.ComputeHash(objFile);
154 objFile.Close();
155
156 strHashData = Convert.ToBase64String(HashData);
157
158 return true;
159
160 }
161 #endregion
162
163 #region RSA签名
164 //RSA签名
165 public bool SignatureFormatter(string p_strKeyPrivate, byte[] HashbyteSignature, ref byte[] EncryptedSignatureData)
166 {
167
168 System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
169
170 RSA.FromXmlString(p_strKeyPrivate);
171 System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
172 //设置签名的算法为MD5
173 RSAFormatter.SetHashAlgorithm("MD5");
174 //执行签名
175 EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);
176
177 return true;
178
179 }
180
181 //RSA签名
182 public bool SignatureFormatter(string p_strKeyPrivate, byte[] HashbyteSignature, ref string m_strEncryptedSignatureData)
183 {
184
185 byte[] EncryptedSignatureData;
186
187 System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
188
189 RSA.FromXmlString(p_strKeyPrivate);
190 System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
191 //设置签名的算法为MD5
192 RSAFormatter.SetHashAlgorithm("MD5");
193 //执行签名
194 EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);
195
196 m_strEncryptedSignatureData = Convert.ToBase64String(EncryptedSignatureData);
197
198 return true;
199
200 }
201
202 //RSA签名
203 public bool SignatureFormatter(string p_strKeyPrivate, string m_strHashbyteSignature, ref byte[] EncryptedSignatureData)
204 {
205
206 byte[] HashbyteSignature;
207
208 HashbyteSignature = Convert.FromBase64String(m_strHashbyteSignature);
209 System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
210
211 RSA.FromXmlString(p_strKeyPrivate);
212 System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
213 //设置签名的算法为MD5
214 RSAFormatter.SetHashAlgorithm("MD5");
215 //执行签名
216 EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);
217
218 return true;
219
220 }
221
222 //RSA签名
223 public bool SignatureFormatter(string p_strKeyPrivate, string m_strHashbyteSignature, ref string m_strEncryptedSignatureData)
224 {
225
226 byte[] HashbyteSignature;
227 byte[] EncryptedSignatureData;
228
229 HashbyteSignature = Convert.FromBase64String(m_strHashbyteSignature);
230 System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
231
232 RSA.FromXmlString(p_strKeyPrivate);
233 System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
234 //设置签名的算法为MD5
235 RSAFormatter.SetHashAlgorithm("MD5");
236 //执行签名
237 EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);
238
239 m_strEncryptedSignatureData = Convert.ToBase64String(EncryptedSignatureData);
240
241 return true;
242
243 }
244 #endregion
245
246 #region RSA 签名验证
247
248 public bool SignatureDeformatter(string p_strKeyPublic, byte[] HashbyteDeformatter, byte[] DeformatterData)
249 {
250
251 System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
252
253 RSA.FromXmlString(p_strKeyPublic);
254 System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
255 //指定解密的时候HASH算法为MD5
256 RSADeformatter.SetHashAlgorithm("MD5");
257
258 if(RSADeformatter.VerifySignature(HashbyteDeformatter,DeformatterData))
259 {
260 return true;
261 }
262 else
263 {
264 return false;
265 }
266
267 }
268
269 public bool SignatureDeformatter(string p_strKeyPublic, string p_strHashbyteDeformatter, byte[] DeformatterData)
270 {
271
272 byte[] HashbyteDeformatter;
273
274 HashbyteDeformatter = Convert.FromBase64String(p_strHashbyteDeformatter);
275
276 System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
277
278 RSA.FromXmlString(p_strKeyPublic);
279 System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
280 //指定解密的时候HASH算法为MD5
281 RSADeformatter.SetHashAlgorithm("MD5");
282
283 if(RSADeformatter.VerifySignature(HashbyteDeformatter,DeformatterData))
284 {
285 return true;
286 }
287 else
288 {
289 return false;
290 }
291
292 }
293
294 public bool SignatureDeformatter(string p_strKeyPublic, byte[] HashbyteDeformatter, string p_strDeformatterData)
295 {
296
297 byte[] DeformatterData;
298
299 System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
300
301 RSA.FromXmlString(p_strKeyPublic);
302 System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
303 //指定解密的时候HASH算法为MD5
304 RSADeformatter.SetHashAlgorithm("MD5");
305
306 DeformatterData =Convert.FromBase64String(p_strDeformatterData);
307
308 if(RSADeformatter.VerifySignature(HashbyteDeformatter,DeformatterData))
309 {
310 return true;
311 }
312 else
313 {
314 return false;
315 }
316
317 }
318
319 public bool SignatureDeformatter(string p_strKeyPublic, string p_strHashbyteDeformatter, string p_strDeformatterData)
320 {
321
322 byte[] DeformatterData;
323 byte[] HashbyteDeformatter;
324
325 HashbyteDeformatter = Convert.FromBase64String(p_strHashbyteDeformatter);
326 System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
327
328 RSA.FromXmlString(p_strKeyPublic);
329 System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
330 //指定解密的时候HASH算法为MD5
331 RSADeformatter.SetHashAlgorithm("MD5");
332
333 DeformatterData =Convert.FromBase64String(p_strDeformatterData);
334
335 if(RSADeformatter.VerifySignature(HashbyteDeformatter,DeformatterData))
336 {
337 return true;
338 }
339 else
340 {
341 return false;
342 }
343
344 }
345
346
347 #endregion
348
349
350 #endregion
351
352 }
353 }
4:哈希加密/解密
1 using System;
2 using System.Text;
3 using System.Security.Cryptography;
4 namespace Maticsoft.Common.DEncrypt
5 {
6 /// <summary>
7 /// 得到随机安全码(哈希加密)。
8 /// </summary>
9 public class HashEncode
10 {
11 public HashEncode()
12 {
13 //
14 // TODO: 在此处添加构造函数逻辑
15 //
16 }
17 /// <summary>
18 /// 得到随机哈希加密字符串
19 /// </summary>
20 /// <returns></returns>
21 public static string GetSecurity()
22 {
23 string Security = HashEncoding(GetRandomValue());
24 return Security;
25 }
26 /// <summary>
27 /// 得到一个随机数值
28 /// </summary>
29 /// <returns></returns>
30 public static string GetRandomValue()
31 {
32 Random Seed = new Random();
33 string RandomVaule = Seed.Next(1, int.MaxValue).ToString();
34 return RandomVaule;
35 }
36 /// <summary>
37 /// 哈希加密一个字符串
38 /// </summary>
39 /// <param name="Security"></param>
40 /// <returns></returns>
41 public static string HashEncoding(string Security)
42 {
43 byte[] Value;
44 UnicodeEncoding Code = new UnicodeEncoding();
45 byte[] Message = Code.GetBytes(Security);
46 SHA512Managed Arithmetic = new SHA512Managed();
47 Value = Arithmetic.ComputeHash(Message);
48 Security = "";
49 foreach(byte o in Value)
50 {
51 Security += (int) o + "O";
52 }
53 return Security;
54 }
55 }
56 }
5:Encrypt
1 using System;
2 using System.Security.Cryptography;
3 using System.Text;
4 namespace Maticsoft.Common.DEncrypt
5 {
6 /// <summary>
7 /// Encrypt 的摘要说明。
8 /// LiTianPing
9 /// </summary>
10 public class DEncrypt
11 {
12 /// <summary>
13 /// 构造方法
14 /// </summary>
15 public DEncrypt()
16 {
17 }
18
19 #region 使用 缺省密钥字符串 加密/解密string
20
21 /// <summary>
22 /// 使用缺省密钥字符串加密string
23 /// </summary>
24 /// <param name="original">明文</param>
25 /// <returns>密文</returns>
26 public static string Encrypt(string original)
27 {
28 return Encrypt(original,"MATICSOFT");
29 }
30 /// <summary>
31 /// 使用缺省密钥字符串解密string
32 /// </summary>
33 /// <param name="original">密文</param>
34 /// <returns>明文</returns>
35 public static string Decrypt(string original)
36 {
37 return Decrypt(original,"MATICSOFT",System.Text.Encoding.Default);
38 }
39
40 #endregion
41
42 #region 使用 给定密钥字符串 加密/解密string
43 /// <summary>
44 /// 使用给定密钥字符串加密string
45 /// </summary>
46 /// <param name="original">原始文字</param>
47 /// <param name="key">密钥</param>
48 /// <param name="encoding">字符编码方案</param>
49 /// <returns>密文</returns>
50 public static string Encrypt(string original, string key)
51 {
52 byte[] buff = System.Text.Encoding.Default.GetBytes(original);
53 byte[] kb = System.Text.Encoding.Default.GetBytes(key);
54 return Convert.ToBase64String(Encrypt(buff,kb));
55 }
56 /// <summary>
57 /// 使用给定密钥字符串解密string
58 /// </summary>
59 /// <param name="original">密文</param>
60 /// <param name="key">密钥</param>
61 /// <returns>明文</returns>
62 public static string Decrypt(string original, string key)
63 {
64 return Decrypt(original,key,System.Text.Encoding.Default);
65 }
66
67 /// <summary>
68 /// 使用给定密钥字符串解密string,返回指定编码方式明文
69 /// </summary>
70 /// <param name="encrypted">密文</param>
71 /// <param name="key">密钥</param>
72 /// <param name="encoding">字符编码方案</param>
73 /// <returns>明文</returns>
74 public static string Decrypt(string encrypted, string key,Encoding encoding)
75 {
76 byte[] buff = Convert.FromBase64String(encrypted);
77 byte[] kb = System.Text.Encoding.Default.GetBytes(key);
78 return encoding.GetString(Decrypt(buff,kb));
79 }
80 #endregion
81
82 #region 使用 缺省密钥字符串 加密/解密/byte[]
83 /// <summary>
84 /// 使用缺省密钥字符串解密byte[]
85 /// </summary>
86 /// <param name="encrypted">密文</param>
87 /// <param name="key">密钥</param>
88 /// <returns>明文</returns>
89 public static byte[] Decrypt(byte[] encrypted)
90 {
91 byte[] key = System.Text.Encoding.Default.GetBytes("MATICSOFT");
92 return Decrypt(encrypted,key);
93 }
94 /// <summary>
95 /// 使用缺省密钥字符串加密
96 /// </summary>
97 /// <param name="original">原始数据</param>
98 /// <param name="key">密钥</param>
99 /// <returns>密文</returns>
100 public static byte[] Encrypt(byte[] original)
101 {
102 byte[] key = System.Text.Encoding.Default.GetBytes("MATICSOFT");
103 return Encrypt(original,key);
104 }
105 #endregion
106
107 #region 使用 给定密钥 加密/解密/byte[]
108
109 /// <summary>
110 /// 生成MD5摘要
111 /// </summary>
112 /// <param name="original">数据源</param>
113 /// <returns>摘要</returns>
114 public static byte[] MakeMD5(byte[] original)
115 {
116 MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
117 byte[] keyhash = hashmd5.ComputeHash(original);
118 hashmd5 = null;
119 return keyhash;
120 }
121
122
123 /// <summary>
124 /// 使用给定密钥加密
125 /// </summary>
126 /// <param name="original">明文</param>
127 /// <param name="key">密钥</param>
128 /// <returns>密文</returns>
129 public static byte[] Encrypt(byte[] original, byte[] key)
130 {
131 TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
132 des.Key = MakeMD5(key);
133 des.Mode = CipherMode.ECB;
134
135 return des.CreateEncryptor().TransformFinalBlock(original, 0, original.Length);
136 }
137
138 /// <summary>
139 /// 使用给定密钥解密数据
140 /// </summary>
141 /// <param name="encrypted">密文</param>
142 /// <param name="key">密钥</param>
143 /// <returns>明文</returns>
144 public static byte[] Decrypt(byte[] encrypted, byte[] key)
145 {
146 TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
147 des.Key = MakeMD5(key);
148 des.Mode = CipherMode.ECB;
149
150 return des.CreateDecryptor().TransformFinalBlock(encrypted, 0, encrypted.Length);
151 }
152
153 #endregion
154
155
156
157
158 }
159 }
WebApi程序可在方法参数前加[FromBody]标识,表示该参数值应该从请求的Body中获取,而不是从URL中获取。
从URL获取参数值的方式的弊端是URL有长度限制,当超过浏览器的最大URL长度时请求将被浏览器拒绝,根本不会发出去。
因此,当参数值过大时需要用[FromBody]参数进行传输。
以下是WebApi接口定义,很简单,只为说明用法:
private string SendObjectAsJsonInBody(string url, object objBody)
{
string result;
HttpClient client;
StringContent content;
client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
content = new StringContent(ParkingSqlHelper.JsonHelper.SerializeObject(objBody), Encoding.UTF8, "application/json");
result = client.PostAsync(url, content).Result.Content.ReadAsStringAsync().Result;
return result;
}
protected HttpResponseMessage GetJsonResponse(string json)
{
HttpResponseMessage result;
result = new HttpResponseMessage { Content = new StringContent(json, Encoding.GetEncoding("UTF-8"), "application/json") };
//result.Headers.Add("Access-Control-Allow-Origin", "*"); //设置HTTP头允许 返回的跨域信息给浏览器解析
return result;
}
需要注意的是: [FromBody] 参数不能是基本的数据类型(如byte、int、bool、DateTime、string等)。
以下是C#客户端请求的代码
/// <summary>
/// 通过请求体向指定URL传输数据
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="objBody">需传输的数据</param>
/// <returns></returns>
private string SendObjectAsJsonInBody(string url, object objBody)
{
string result;
HttpClient client;
StringContent content;
client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
content = new StringContent(ParkingSqlHelper.JsonHelper.SerializeObject(objBody), Encoding.UTF8, "application/json");
result = client.PostAsync(url, content).Result.Content.ReadAsStringAsync().Result;
return result;
}
以下是JQuery请求的代码
function Send(url, objBody) {
$.ajax({
url: url,
type: "post",
data: JSON.stringify(objBody),
contentType: "application/json; charset=UTF-8",
timeout: 5000,
success: function (result) {
alert("data = " + JSON.stringify(result));
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
});
};
---------------------
简单说一下加密解密:
加密解密有挺多方式去实现,今天呢我做为宇宙第一帅的人就给大家来分享以下源代码!听清楚是源代码哦!!
话不多说上干货
1:MD5加密/解密
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4 using System.Web;
5 using System.Text.RegularExpressions;
6
7 namespace hic.Common
8 {
9 public class SecurityHelper
10 {
11 /// <summary>
12 /// MD5字符串加密
13 /// </summary>
14 /// <param name="source">待加密字符串</param>
15 /// <returns></returns>
16 public static string MD5(string source)
17 {
18 return MD5(source, true);
19 }
20
21 /// <summary>
22 /// MD5字符串加密
23 /// </summary>
24 /// <param name="source">待加密字符串</param>
25 /// <param name="ishalf">加密是16位还是32位,如果为true则是16位。</param>
26 /// <returns></returns>
27 public static string MD5(string source, bool ishalf)
28 {
29 string outputStr = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(source, "MD5").ToLower();
30 if (ishalf)//16位MD5加密(取32位加密的9~25字符)
31 outputStr = outputStr.Substring(8, 16);
32 return outputStr;
33 }
34
35 /// <summary>
36 /// 对字符串进行Base64编码
37 /// </summary>
38 /// <param name="source">待编码字符串</param>
39 /// <returns></returns>
40 public static string EncodeBase64(string source)
41 {
42 UnicodeEncoding code = new UnicodeEncoding();
43 byte[] bytes = code.GetBytes(source);
44 return Convert.ToBase64String(bytes);
45 }
46
47 /// <summary>
48 /// 对字符串进行Base64解码
49 /// </summary>
50 /// <param name="source">待解码字符串</param>
51 /// <returns></returns>
52 public static string DecodeBase64(string source)
53 {
54 UnicodeEncoding code = new UnicodeEncoding();
55 byte[] bytes = Convert.FromBase64String(source);
56 return code.GetString(bytes);
57 }
58
59 /// <summary>
60 /// 检查当前IP是否是受限IP
61 /// </summary>
62 /// <param name="LimitedIP">受限的IP,格式如:192.168.1.110|212.235.*.*|232.*.*.*</param>
63 /// <returns>返回true表示IP未受到限制</returns>
64 public static bool CheckIPIsLimited(string limitedIP)
65 {
66 string currentIP = GetUserIP();
67 if (limitedIP == null || limitedIP.Trim() == string.Empty)
68 return true;
69 limitedIP.Replace(".", @"\.");
70 limitedIP.Replace("*", @"[^\.]{1,3}");
71 Regex reg = new Regex(limitedIP, RegexOptions.Compiled);
72 Match match = reg.Match(currentIP);
73 return !match.Success;
74 }
75
76 /// <summary>
77 /// 得到用户IP
78 /// </summary>
79 /// <returns></returns>
80 public static string GetUserIP()
81 {
82 return HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
83 }
84 }
85 }
2:DES加密/解密类
1 using System;
2 using System.Security.Cryptography;
3 using System.Text;
4 namespace Maticsoft.Common.DEncrypt
5 {
6 /// <summary>
7 /// DES加密/解密类。
8 /// LiTianPing
9 /// </summary>
10 public class DESEncrypt
11 {
12 public DESEncrypt()
13 {
14 }
15
16 #region ========加密========
17
18 /// <summary>
19 /// 加密
20 /// </summary>
21 /// <param name="Text"></param>
22 /// <returns></returns>
23 public static string Encrypt(string Text)
24 {
25 return Encrypt(Text,"MATICSOFT");
26 }
27 /// <summary>
28 /// 加密数据
29 /// </summary>
30 /// <param name="Text"></param>
31 /// <param name="sKey"></param>
32 /// <returns></returns>
33 public static string Encrypt(string Text,string sKey)
34 {
35 DESCryptoServiceProvider des = new DESCryptoServiceProvider();
36 byte[] inputByteArray;
37 inputByteArray=Encoding.Default.GetBytes(Text);
38 des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
39 des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
40 System.IO.MemoryStream ms=new System.IO.MemoryStream();
41 CryptoStream cs=new CryptoStream(ms,des.CreateEncryptor(),CryptoStreamMode.Write);
42 cs.Write(inputByteArray,0,inputByteArray.Length);
43 cs.FlushFinalBlock();
44 StringBuilder ret=new StringBuilder();
45 foreach( byte b in ms.ToArray())
46 {
47 ret.AppendFormat("{0:X2}",b);
48 }
49 return ret.ToString();
50 }
51
52 #endregion
53
54 #region ========解密========
55
56
57 /// <summary>
58 /// 解密
59 /// </summary>
60 /// <param name="Text"></param>
61 /// <returns></returns>
62 public static string Decrypt(string Text)
63 {
64 return Decrypt(Text,"MATICSOFT");
65 }
66 /// <summary>
67 /// 解密数据
68 /// </summary>
69 /// <param name="Text"></param>
70 /// <param name="sKey"></param>
71 /// <returns></returns>
72 public static string Decrypt(string Text,string sKey)
73 {
74 DESCryptoServiceProvider des = new DESCryptoServiceProvider();
75 int len;
76 len=Text.Length/2;
77 byte[] inputByteArray = new byte[len];
78 int x,i;
79 for(x=0;x<len;x++)
80 {
81 i = Convert.ToInt32(Text.Substring(x * 2, 2), 16);
82 inputByteArray[x]=(byte)i;
83 }
84 des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
85 des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
86 System.IO.MemoryStream ms=new System.IO.MemoryStream();
87 CryptoStream cs=new CryptoStream(ms,des.CreateDecryptor(),CryptoStreamMode.Write);
88 cs.Write(inputByteArray,0,inputByteArray.Length);
89 cs.FlushFinalBlock();
90 return Encoding.Default.GetString(ms.ToArray());
91 }
92
93 #endregion
94
95
96 }
97 }
3:RSA加密解密及RSA签名和验证
1 using System;
2 using System.Text;
3 using System.Security.Cryptography;
4 namespace Maticsoft.Common.DEncrypt
5 {
6 /// <summary>
7 /// RSA加密解密及RSA签名和验证
8 /// </summary>
9 public class RSACryption
10 {
11 public RSACryption()
12 {
13 }
14
15
16 #region RSA 加密解密
17
18 #region RSA 的密钥产生
19
20 /// <summary>
21 /// RSA 的密钥产生 产生私钥 和公钥
22 /// </summary>
23 /// <param name="xmlKeys"></param>
24 /// <param name="xmlPublicKey"></param>
25 public void RSAKey(out string xmlKeys,out string xmlPublicKey)
26 {
27 System.Security.Cryptography.RSACryptoServiceProvider rsa=new RSACryptoServiceProvider();
28 xmlKeys=rsa.ToXmlString(true);
29 xmlPublicKey = rsa.ToXmlString(false);
30 }
31 #endregion
32
33 #region RSA的加密函数
34 //##############################################################################
35 //RSA 方式加密
36 //说明KEY必须是XML的行式,返回的是字符串
37 //在有一点需要说明!!该加密方式有 长度 限制的!!
38 //##############################################################################
39
40 //RSA的加密函数 string
41 public string RSAEncrypt(string xmlPublicKey,string m_strEncryptString )
42 {
43
44 byte[] PlainTextBArray;
45 byte[] CypherTextBArray;
46 string Result;
47 RSACryptoServiceProvider rsa=new RSACryptoServiceProvider();
48 rsa.FromXmlString(xmlPublicKey);
49 PlainTextBArray = (new UnicodeEncoding()).GetBytes(m_strEncryptString);
50 CypherTextBArray = rsa.Encrypt(PlainTextBArray, false);
51 Result=Convert.ToBase64String(CypherTextBArray);
52 return Result;
53
54 }
55 //RSA的加密函数 byte[]
56 public string RSAEncrypt(string xmlPublicKey,byte[] EncryptString )
57 {
58
59 byte[] CypherTextBArray;
60 string Result;
61 RSACryptoServiceProvider rsa=new RSACryptoServiceProvider();
62 rsa.FromXmlString(xmlPublicKey);
63 CypherTextBArray = rsa.Encrypt(EncryptString, false);
64 Result=Convert.ToBase64String(CypherTextBArray);
65 return Result;
66
67 }
68 #endregion
69
70 #region RSA的解密函数
71 //RSA的解密函数 string
72 public string RSADecrypt(string xmlPrivateKey, string m_strDecryptString )
73 {
74 byte[] PlainTextBArray;
75 byte[] DypherTextBArray;
76 string Result;
77 System.Security.Cryptography.RSACryptoServiceProvider rsa=new RSACryptoServiceProvider();
78 rsa.FromXmlString(xmlPrivateKey);
79 PlainTextBArray =Convert.FromBase64String(m_strDecryptString);
80 DypherTextBArray=rsa.Decrypt(PlainTextBArray, false);
81 Result=(new UnicodeEncoding()).GetString(DypherTextBArray);
82 return Result;
83
84 }
85
86 //RSA的解密函数 byte
87 public string RSADecrypt(string xmlPrivateKey, byte[] DecryptString )
88 {
89 byte[] DypherTextBArray;
90 string Result;
91 System.Security.Cryptography.RSACryptoServiceProvider rsa=new RSACryptoServiceProvider();
92 rsa.FromXmlString(xmlPrivateKey);
93 DypherTextBArray=rsa.Decrypt(DecryptString, false);
94 Result=(new UnicodeEncoding()).GetString(DypherTextBArray);
95 return Result;
96
97 }
98 #endregion
99
100 #endregion
101
102 #region RSA数字签名
103
104 #region 获取Hash描述表
105 //获取Hash描述表
106 public bool GetHash(string m_strSource, ref byte[] HashData)
107 {
108 //从字符串中取得Hash描述
109 byte[] Buffer;
110 System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");
111 Buffer = System.Text.Encoding.GetEncoding("GB2312").GetBytes(m_strSource);
112 HashData = MD5.ComputeHash(Buffer);
113
114 return true;
115 }
116
117 //获取Hash描述表
118 public bool GetHash(string m_strSource, ref string strHashData)
119 {
120
121 //从字符串中取得Hash描述
122 byte[] Buffer;
123 byte[] HashData;
124 System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");
125 Buffer = System.Text.Encoding.GetEncoding("GB2312").GetBytes(m_strSource);
126 HashData = MD5.ComputeHash(Buffer);
127
128 strHashData = Convert.ToBase64String(HashData);
129 return true;
130
131 }
132
133 //获取Hash描述表
134 public bool GetHash(System.IO.FileStream objFile, ref byte[] HashData)
135 {
136
137 //从文件中取得Hash描述
138 System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");
139 HashData = MD5.ComputeHash(objFile);
140 objFile.Close();
141
142 return true;
143
144 }
145
146 //获取Hash描述表
147 public bool GetHash(System.IO.FileStream objFile, ref string strHashData)
148 {
149
150 //从文件中取得Hash描述
151 byte[] HashData;
152 System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");
153 HashData = MD5.ComputeHash(objFile);
154 objFile.Close();
155
156 strHashData = Convert.ToBase64String(HashData);
157
158 return true;
159
160 }
161 #endregion
162
163 #region RSA签名
164 //RSA签名
165 public bool SignatureFormatter(string p_strKeyPrivate, byte[] HashbyteSignature, ref byte[] EncryptedSignatureData)
166 {
167
168 System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
169
170 RSA.FromXmlString(p_strKeyPrivate);
171 System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
172 //设置签名的算法为MD5
173 RSAFormatter.SetHashAlgorithm("MD5");
174 //执行签名
175 EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);
176
177 return true;
178
179 }
180
181 //RSA签名
182 public bool SignatureFormatter(string p_strKeyPrivate, byte[] HashbyteSignature, ref string m_strEncryptedSignatureData)
183 {
184
185 byte[] EncryptedSignatureData;
186
187 System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
188
189 RSA.FromXmlString(p_strKeyPrivate);
190 System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
191 //设置签名的算法为MD5
192 RSAFormatter.SetHashAlgorithm("MD5");
193 //执行签名
194 EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);
195
196 m_strEncryptedSignatureData = Convert.ToBase64String(EncryptedSignatureData);
197
198 return true;
199
200 }
201
202 //RSA签名
203 public bool SignatureFormatter(string p_strKeyPrivate, string m_strHashbyteSignature, ref byte[] EncryptedSignatureData)
204 {
205
206 byte[] HashbyteSignature;
207
208 HashbyteSignature = Convert.FromBase64String(m_strHashbyteSignature);
209 System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
210
211 RSA.FromXmlString(p_strKeyPrivate);
212 System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
213 //设置签名的算法为MD5
214 RSAFormatter.SetHashAlgorithm("MD5");
215 //执行签名
216 EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);
217
218 return true;
219
220 }
221
222 //RSA签名
223 public bool SignatureFormatter(string p_strKeyPrivate, string m_strHashbyteSignature, ref string m_strEncryptedSignatureData)
224 {
225
226 byte[] HashbyteSignature;
227 byte[] EncryptedSignatureData;
228
229 HashbyteSignature = Convert.FromBase64String(m_strHashbyteSignature);
230 System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
231
232 RSA.FromXmlString(p_strKeyPrivate);
233 System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
234 //设置签名的算法为MD5
235 RSAFormatter.SetHashAlgorithm("MD5");
236 //执行签名
237 EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);
238
239 m_strEncryptedSignatureData = Convert.ToBase64String(EncryptedSignatureData);
240
241 return true;
242
243 }
244 #endregion
245
246 #region RSA 签名验证
247
248 public bool SignatureDeformatter(string p_strKeyPublic, byte[] HashbyteDeformatter, byte[] DeformatterData)
249 {
250
251 System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
252
253 RSA.FromXmlString(p_strKeyPublic);
254 System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
255 //指定解密的时候HASH算法为MD5
256 RSADeformatter.SetHashAlgorithm("MD5");
257
258 if(RSADeformatter.VerifySignature(HashbyteDeformatter,DeformatterData))
259 {
260 return true;
261 }
262 else
263 {
264 return false;
265 }
266
267 }
268
269 public bool SignatureDeformatter(string p_strKeyPublic, string p_strHashbyteDeformatter, byte[] DeformatterData)
270 {
271
272 byte[] HashbyteDeformatter;
273
274 HashbyteDeformatter = Convert.FromBase64String(p_strHashbyteDeformatter);
275
276 System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
277
278 RSA.FromXmlString(p_strKeyPublic);
279 System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
280 //指定解密的时候HASH算法为MD5
281 RSADeformatter.SetHashAlgorithm("MD5");
282
283 if(RSADeformatter.VerifySignature(HashbyteDeformatter,DeformatterData))
284 {
285 return true;
286 }
287 else
288 {
289 return false;
290 }
291
292 }
293
294 public bool SignatureDeformatter(string p_strKeyPublic, byte[] HashbyteDeformatter, string p_strDeformatterData)
295 {
296
297 byte[] DeformatterData;
298
299 System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
300
301 RSA.FromXmlString(p_strKeyPublic);
302 System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
303 //指定解密的时候HASH算法为MD5
304 RSADeformatter.SetHashAlgorithm("MD5");
305
306 DeformatterData =Convert.FromBase64String(p_strDeformatterData);
307
308 if(RSADeformatter.VerifySignature(HashbyteDeformatter,DeformatterData))
309 {
310 return true;
311 }
312 else
313 {
314 return false;
315 }
316
317 }
318
319 public bool SignatureDeformatter(string p_strKeyPublic, string p_strHashbyteDeformatter, string p_strDeformatterData)
320 {
321
322 byte[] DeformatterData;
323 byte[] HashbyteDeformatter;
324
325 HashbyteDeformatter = Convert.FromBase64String(p_strHashbyteDeformatter);
326 System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
327
328 RSA.FromXmlString(p_strKeyPublic);
329 System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
330 //指定解密的时候HASH算法为MD5
331 RSADeformatter.SetHashAlgorithm("MD5");
332
333 DeformatterData =Convert.FromBase64String(p_strDeformatterData);
334
335 if(RSADeformatter.VerifySignature(HashbyteDeformatter,DeformatterData))
336 {
337 return true;
338 }
339 else
340 {
341 return false;
342 }
343
344 }
345
346
347 #endregion
348
349
350 #endregion
351
352 }
353 }
4:哈希加密/解密
1 using System;
2 using System.Text;
3 using System.Security.Cryptography;
4 namespace Maticsoft.Common.DEncrypt
5 {
6 /// <summary>
7 /// 得到随机安全码(哈希加密)。
8 /// </summary>
9 public class HashEncode
10 {
11 public HashEncode()
12 {
13 //
14 // TODO: 在此处添加构造函数逻辑
15 //
16 }
17 /// <summary>
18 /// 得到随机哈希加密字符串
19 /// </summary>
20 /// <returns></returns>
21 public static string GetSecurity()
22 {
23 string Security = HashEncoding(GetRandomValue());
24 return Security;
25 }
26 /// <summary>
27 /// 得到一个随机数值
28 /// </summary>
29 /// <returns></returns>
30 public static string GetRandomValue()
31 {
32 Random Seed = new Random();
33 string RandomVaule = Seed.Next(1, int.MaxValue).ToString();
34 return RandomVaule;
35 }
36 /// <summary>
37 /// 哈希加密一个字符串
38 /// </summary>
39 /// <param name="Security"></param>
40 /// <returns></returns>
41 public static string HashEncoding(string Security)
42 {
43 byte[] Value;
44 UnicodeEncoding Code = new UnicodeEncoding();
45 byte[] Message = Code.GetBytes(Security);
46 SHA512Managed Arithmetic = new SHA512Managed();
47 Value = Arithmetic.ComputeHash(Message);
48 Security = "";
49 foreach(byte o in Value)
50 {
51 Security += (int) o + "O";
52 }
53 return Security;
54 }
55 }
56 }
5:Encrypt
1 using System;
2 using System.Security.Cryptography;
3 using System.Text;
4 namespace Maticsoft.Common.DEncrypt
5 {
6 /// <summary>
7 /// Encrypt 的摘要说明。
8 /// LiTianPing
9 /// </summary>
10 public class DEncrypt
11 {
12 /// <summary>
13 /// 构造方法
14 /// </summary>
15 public DEncrypt()
16 {
17 }
18
19 #region 使用 缺省密钥字符串 加密/解密string
20
21 /// <summary>
22 /// 使用缺省密钥字符串加密string
23 /// </summary>
24 /// <param name="original">明文</param>
25 /// <returns>密文</returns>
26 public static string Encrypt(string original)
27 {
28 return Encrypt(original,"MATICSOFT");
29 }
30 /// <summary>
31 /// 使用缺省密钥字符串解密string
32 /// </summary>
33 /// <param name="original">密文</param>
34 /// <returns>明文</returns>
35 public static string Decrypt(string original)
36 {
37 return Decrypt(original,"MATICSOFT",System.Text.Encoding.Default);
38 }
39
40 #endregion
41
42 #region 使用 给定密钥字符串 加密/解密string
43 /// <summary>
44 /// 使用给定密钥字符串加密string
45 /// </summary>
46 /// <param name="original">原始文字</param>
47 /// <param name="key">密钥</param>
48 /// <param name="encoding">字符编码方案</param>
49 /// <returns>密文</returns>
50 public static string Encrypt(string original, string key)
51 {
52 byte[] buff = System.Text.Encoding.Default.GetBytes(original);
53 byte[] kb = System.Text.Encoding.Default.GetBytes(key);
54 return Convert.ToBase64String(Encrypt(buff,kb));
55 }
56 /// <summary>
57 /// 使用给定密钥字符串解密string
58 /// </summary>
59 /// <param name="original">密文</param>
60 /// <param name="key">密钥</param>
61 /// <returns>明文</returns>
62 public static string Decrypt(string original, string key)
63 {
64 return Decrypt(original,key,System.Text.Encoding.Default);
65 }
66
67 /// <summary>
68 /// 使用给定密钥字符串解密string,返回指定编码方式明文
69 /// </summary>
70 /// <param name="encrypted">密文</param>
71 /// <param name="key">密钥</param>
72 /// <param name="encoding">字符编码方案</param>
73 /// <returns>明文</returns>
74 public static string Decrypt(string encrypted, string key,Encoding encoding)
75 {
76 byte[] buff = Convert.FromBase64String(encrypted);
77 byte[] kb = System.Text.Encoding.Default.GetBytes(key);
78 return encoding.GetString(Decrypt(buff,kb));
79 }
80 #endregion
81
82 #region 使用 缺省密钥字符串 加密/解密/byte[]
83 /// <summary>
84 /// 使用缺省密钥字符串解密byte[]
85 /// </summary>
86 /// <param name="encrypted">密文</param>
87 /// <param name="key">密钥</param>
88 /// <returns>明文</returns>
89 public static byte[] Decrypt(byte[] encrypted)
90 {
91 byte[] key = System.Text.Encoding.Default.GetBytes("MATICSOFT");
92 return Decrypt(encrypted,key);
93 }
94 /// <summary>
95 /// 使用缺省密钥字符串加密
96 /// </summary>
97 /// <param name="original">原始数据</param>
98 /// <param name="key">密钥</param>
99 /// <returns>密文</returns>
100 public static byte[] Encrypt(byte[] original)
101 {
102 byte[] key = System.Text.Encoding.Default.GetBytes("MATICSOFT");
103 return Encrypt(original,key);
104 }
105 #endregion
106
107 #region 使用 给定密钥 加密/解密/byte[]
108
109 /// <summary>
110 /// 生成MD5摘要
111 /// </summary>
112 /// <param name="original">数据源</param>
113 /// <returns>摘要</returns>
114 public static byte[] MakeMD5(byte[] original)
115 {
116 MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
117 byte[] keyhash = hashmd5.ComputeHash(original);
118 hashmd5 = null;
119 return keyhash;
120 }
121
122
123 /// <summary>
124 /// 使用给定密钥加密
125 /// </summary>
126 /// <param name="original">明文</param>
127 /// <param name="key">密钥</param>
128 /// <returns>密文</returns>
129 public static byte[] Encrypt(byte[] original, byte[] key)
130 {
131 TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
132 des.Key = MakeMD5(key);
133 des.Mode = CipherMode.ECB;
134
135 return des.CreateEncryptor().TransformFinalBlock(original, 0, original.Length);
136 }
137
138 /// <summary>
139 /// 使用给定密钥解密数据
140 /// </summary>
141 /// <param name="encrypted">密文</param>
142 /// <param name="key">密钥</param>
143 /// <returns>明文</returns>
144 public static byte[] Decrypt(byte[] encrypted, byte[] key)
145 {
146 TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
147 des.Key = MakeMD5(key);
148 des.Mode = CipherMode.ECB;
149
150 return des.CreateDecryptor().TransformFinalBlock(encrypted, 0, encrypted.Length);
151 }
152
153 #endregion
154
155
156
157
158 }
159 }
WebApi程序可在方法参数前加[FromBody]标识,表示该参数值应该从请求的Body中获取,而不是从URL中获取。
从URL获取参数值的方式的弊端是URL有长度限制,当超过浏览器的最大URL长度时请求将被浏览器拒绝,根本不会发出去。
因此,当参数值过大时需要用[FromBody]参数进行传输。
以下是WebApi接口定义,很简单,只为说明用法:
private string SendObjectAsJsonInBody(string url, object objBody)
{
string result;
HttpClient client;
StringContent content;
client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
content = new StringContent(ParkingSqlHelper.JsonHelper.SerializeObject(objBody), Encoding.UTF8, "application/json");
result = client.PostAsync(url, content).Result.Content.ReadAsStringAsync().Result;
return result;
}
protected HttpResponseMessage GetJsonResponse(string json)
{
HttpResponseMessage result;
result = new HttpResponseMessage { Content = new StringContent(json, Encoding.GetEncoding("UTF-8"), "application/json") };
//result.Headers.Add("Access-Control-Allow-Origin", "*"); //设置HTTP头允许 返回的跨域信息给浏览器解析
return result;
}
需要注意的是: [FromBody] 参数不能是基本的数据类型(如byte、int、bool、DateTime、string等)。
以下是C#客户端请求的代码
/// <summary>
/// 通过请求体向指定URL传输数据
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="objBody">需传输的数据</param>
/// <returns></returns>
private string SendObjectAsJsonInBody(string url, object objBody)
{
string result;
HttpClient client;
StringContent content;
client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
content = new StringContent(ParkingSqlHelper.JsonHelper.SerializeObject(objBody), Encoding.UTF8, "application/json");
result = client.PostAsync(url, content).Result.Content.ReadAsStringAsync().Result;
return result;
}
以下是JQuery请求的代码
function Send(url, objBody) {
$.ajax({
url: url,
type: "post",
data: JSON.stringify(objBody),
contentType: "application/json; charset=UTF-8",
timeout: 5000,
success: function (result) {
alert("data = " + JSON.stringify(result));
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
});
};
---------------------
来源:https://www.cnblogs.com/cjm123/p/10745946.html