33.NET对加密和解密的支持
散列运算
mscorlib.dll下的System.Security.Cryptography下:
抽象类HashAlgorithm
抽象类MD5
MD5CryptoServiceProvider
SHA1
SHA1CryptoServiceProvider密封类:调用Windows Crypto API
SHA1Managed普通类:用托管代码写的
SHA256
SHA256CryptoServiceProvider
SHA256Managed
SHA384
SHA512
□ 对字节数组或流散列运算
class Program
{
static void Main(string[] args)
{
string str = "Hello World";
HashAlgorithm hashAlgorithm = HashAlgorithm.Create(HashAlgorithmType.SHA1);
byte[] data = Encoding.Default.GetBytes(str);
byte[] digest = hashAlgorithm.ComputeHash(data);
foreach (byte b in digest)
{
Console.Write("{0:X}",b);
}
Console.ReadKey();
}
}
public class HashAlgorithmType
{
public const string SHA1 = "SHA1";
public const string SHA256 = "SHA256";
public const string SHA384 = "SHA384";
public const string SHA512 = "SHA512";
public const string MD5 = "MD5";
}
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
□ 密匙散列运算
string key = "secret key";
byte[] data = Encoding.Default.GetBytes(key);
KeyedHashAlgorithm kha = new HMACSHA1();
byte[] digest = kha.ComputeHash(data);
foreach (byte b in digest)
{
Console.Write("{0:x}",b);
}
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
对称加密和解密
SymmetricAlgorithm
DES
DESCryptoServiceProvider
TripleDES
TripleDESCryptoServiceProvider
Rijndael
RijindaelManaged
RC2
RC2CryptoServiceProvider
IV:Initialization vector初始化向量:
-为了解决加密字符串加密后仍然有重复部分,引入IV,加密字符串即使有重复,也会被打乱。
-IV值可以随意指定,但长度固定,通常为64位byte类型
-密匙长度也是固定的,通常为128位或196位byte类型
使用Encoding类将字符串转换为byte[]:
-如果使用UTF8,会变长编码
加密解密方法:
-加密方法:CreateEncryptor(),返回ICryptoTransform接口类型
-解密方法:CreateDecryptor(),返回ICrtyptoTransform接口类型
明文流和加密流的转换:
public CryptoStream(Stream stream, ICryptoTransform transform, CryptoStreamMode mode)
class Program
{
static void Main(string[] args)
{
#region 对称加密和解密
string key = "secret key";
string str = "Hello World";
//加密
string encryptedText = SymmetricCryptoHelper.Encrypt(str, key);
Console.WriteLine(encryptedText);
//解密
string clearText = SymmetricCryptoHelper.Decrypt(encryptedText, key);
Console.WriteLine(clearText);
Console.ReadKey();
#endregion
}
}
//对称加密帮助类
public class SymmetricCryptoHelper
{
private ICryptoTransform encryptor; //加密器对象
private ICryptoTransform decryptor; //解密器对象
private const int BufferSize = 1024;
public SymmetricCryptoHelper(string algorithmName, byte[] key)
{
SymmetricAlgorithm provider = SymmetricAlgorithm.Create(algorithmName);
provider.Key = key;
provider.IV = new byte[] { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
encryptor = provider.CreateEncryptor();
decryptor = provider.CreateDecryptor();
}
public SymmetricCryptoHelper(byte[] key) : this("TripleDES", key){}
//加密算法
public string Encrypt(string clearText)
{
//创建明文流
byte[] clearBuffer = Encoding.UTF8.GetBytes(clearText);
//byte[] clearBuffer = Encoding.Default.GetBytes(clearText);
MemoryStream clearStream = new MemoryStream(clearBuffer);
//创建空的密文流
MemoryStream encryptedStream = new MemoryStream();
//明文流和密文流转换流,准备写到密文流中
CryptoStream cryptoStream = new CryptoStream(encryptedStream, encryptor, CryptoStreamMode.Write);
int bytesRead = 0;
byte[] buffer = new byte[BufferSize];
do
{
//读取明文流到buffer中
bytesRead = clearStream.Read(buffer, 0, BufferSize);
//通过CryptoStream将buffer中的明文流字节数组写到明文流中
cryptoStream.Write(buffer, 0, bytesRead);
} while (bytesRead > 0);
cryptoStream.FlushFinalBlock();
//获取加密后的字节数组
buffer = encryptedStream.ToArray();
//将加密后的字节数组转换成字符串
string encryptedText = Convert.ToBase64String(buffer);
return encryptedText;
}
//解密算法
public string Decrypt(string encryptedText)
{
//把加密字符串转换为加密字节数组
byte[] encryptedBuffer = Convert.FromBase64String(encryptedText);
//创建密文流
Stream encryptedStream = new MemoryStream(encryptedBuffer);
//创建空的明文流
MemoryStream clearStream = new MemoryStream();
//创建明文流和密文流的转化流,读取密文流
CryptoStream cryptoStream = new CryptoStream(encryptedStream, decryptor, CryptoStreamMode.Read);
int bytesRead = 0;
byte[] buffer = new byte[BufferSize];
do
{
//通过CryptoStream读取密文流到Buffer
bytesRead = cryptoStream.Read(buffer, 0, BufferSize);
//把Buffer中的密文流写到明文流中
clearStream.Write(buffer, 0, bytesRead);
} while (bytesRead > 0);
//将明文流转换成字节数组
buffer = clearStream.GetBuffer();
string clearText = Encoding.UTF8.GetString(buffer, 0, (int)clearStream.Length);
//string clearText = Encoding.Default.GetString(buffer, 0, (int)clearStream.Length);
return clearText;
}
//密匙加密
public static string Encrypt(string clearText, string key)
{
byte[] keyData = new byte[16]; //TripleDES密匙固定长度为16个字节
//把密匙字符串转换成字节数组
byte[] sourceData = Encoding.Default.GetBytes(key);
int copyBytes = 16;
if (sourceData.Length < 16)
{
copyBytes = sourceData.Length;
}
//把密匙数组复制到keyData字节数组中
Array.Copy(sourceData,keyData,copyBytes);
SymmetricCryptoHelper helper = new SymmetricCryptoHelper(keyData);
return helper.Encrypt(clearText);
}
//密匙解密
public static string Decrypt(string encryptedText, string key)
{
byte[] keyData = new byte[16];
byte[] sourceData = Encoding.Default.GetBytes(key);
int copyBytes = 16;
if (sourceData.Length < 16)
{
copyBytes = sourceData.Length;
}
Array.Copy(sourceData,keyData,copyBytes);
SymmetricCryptoHelper helper = new SymmetricCryptoHelper(keyData);
return helper.Decrypt(encryptedText);
}
}
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
非对称加密
AsymmetricAlgorithm
RSA
RSACryptoServiceProvider
DSA
DSACryptoServiceProvider:只能进行认证模式,即数字签名
对称加密中的密匙:
密匙为由开发者设定的字符串
非对称加密中的密匙:
● 通常是自动生成,不同的算法有不同的密匙格式
● 在创建RSACryptoServiceProvider实例时,会自动创建一个公/私密匙对。在实例上调用ToXmlString()方法获得。
RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
string publicPrivate = provider.ToXmlString(true);//获得公/私匙对
//string publicOnly = provider.ToXmlString(false); //只获得公匙
Console.Write(publicPrivate);
Console.ReadKey();
□ 非对称加密帮助类
//非对称加密帮助类
public class RSACryptoHelper
{
//加密
public static string Encrypt(string publicKeyXml, string plainText)
{
RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
provider.FromXmlString(publicKeyXml); //使用公匙初始化对象
byte[] plainData = Encoding.Default.GetBytes(plainText);
byte[] encryptedData = provider.Encrypt(plainData, true);
return Convert.ToBase64String(encryptedData);
}
//解密
public static string Decrypt(string privateKeyXml, string encryptedText)
{
RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
provider.FromXmlString(privateKeyXml);
byte[] encryptedData = Convert.FromBase64String(encryptedText);
byte[] plainData = provider.Decrypt(encryptedData, true);
string plainText = Encoding.Default.GetString(plainData);
return plainText;
}
}
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
数字签名
RSACryptoServiceProvider或DSACryptoServiceProvider
SignData()对摘要进行签名,并返回签名后的摘要。
VerifyData()得出本地摘要,并解密传递进来的原始摘要,对比返回bool类型结果。
□ 数字签名帮助类
public class RSACryptoHelper
{
public static string SignData(string plainText, string privateKeyXml)
{
RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
provider.FromXmlString(privateKeyXml);
byte[] plainData = Encoding.Default.GetBytes(plainText);
//设置获取摘要的算法
HashAlgorithm sha1 = HashAlgorithm.Create("SHA1");
//获取签名过的摘要,是使用私匙加密过的摘要
byte[] signedDigest = provider.SignData(plainData, sha1);
return Convert.ToBase64String(signedDigest);
}
public static bool VerifyData(string plainText, string signature, string publicKeyXml)
{
RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
provider.FromXmlString(publicKeyXml);
byte[] plainData = Encoding.Default.GetBytes(plainText);
byte[] signedDigest = Convert.FromBase64String(signature);
HashAlgorithm sha1 = HashAlgorithm.Create("SHA1");
bool isDataIntact = provider.VerifyData(plainData, sha1, signedDigest);
return isDataIntact;
}
//使用SingnHash
public static string SignData2(string plainText, string privateKeyXml)
{
RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
provider.FromXmlString(privateKeyXml);
byte[] plainData = Encoding.Default.GetBytes(plainText);
//设置获取摘要的算法
HashAlgorithm sha1 = HashAlgorithm.Create("SHA1");
//获得原始摘要
byte[] digestData = sha1.ComputeHash(plainData);
//对元素摘要进行签名
byte[] signedDigest = provider.SignHash(digestData, "SHA1");
return Convert.ToBase64String(signedDigest);
}
//使用VerifyHash
public static bool VerifyData2(string plainText, string signedDigest, string publicKeyXml)
{
RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
provider.FromXmlString(publicKeyXml);
byte[] plainData = Encoding.Default.GetBytes("SHA1");
byte[] signedDigestData = Convert.FromBase64String(signedDigest);
//获得本地摘要
HashAlgorithm sha1 = HashAlgorithm.Create("SHA1");
byte[] digest = sha1.ComputeHash(plainData);
//解密签名
bool isDataIntact = provider.VerifyHash(digest, "SHA1", signedDigestData);
return isDataIntact;
}
}
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
参考资料:
※ 《.NET之美》--张子阳,感谢写了这么好的书!
33.NET对加密和解密的支持的更多相关文章
- php+js的 authcode 混淆加密和解密,php和js可以通用加密和解密
<script> //md5.js var hexcase = 0; function hex_md5(a) { return rstr2hex(rstr_md5(str2rstr_utf ...
- iOS,一行代码进行RSA、DES 、AES、MD5加密、解密
本文为投稿文章,作者:Flying_Einstein(简书) 加密的Demo,欢迎下载 JAVA端的加密解密,读者可以看我同事的这篇文章:http://www.jianshu.com/p/98569e ...
- 如何对web.config进行加密和解密
http://blog.csdn.net/jf_jifei/article/details/6527390 在WEB网站开发过程中,如果我们将数据库连接字符串封装到.DLL文件中,将会给数据库和程序的 ...
- JS URL 使用base64加密与解密
JS编码方式: <script type="text/javascript"> document.write(encodeURI("http://www.w3 ...
- 基于私钥加密公钥解密的RSA算法C#实现
RSA算法是第一个能同时用于加密和数字签名的算法,也易于理解和操作. RSA是被研究得最广泛的公钥算法,从提出到现在已近二十年,经历了各种攻击的考验,逐渐为人们接受,普遍认为是目前最优秀的公钥方案之一 ...
- (转)DES、RSA、MD5、SHA、随机生成加密与解密
一.数据加密/编码算法列表 常见用于保证安全的加密或编码算法如下: 1.常用密钥算法 密钥算法用来对敏感数据.摘要.签名等信息进行加密,常用的密钥算法包括: DES(Data Encr ...
- 银联手机支付(.Net Csharp),3DES加密解密,RSA加密解密,RSA私钥加密公钥解密,.Net RSA 3DES C#
前段时间做的银联支付,折腾了好久,拼凑的一些代码,有需要的朋友可以参考,本人.Net新手,不保证准确性! 这个银联手机支付没有SDK提供,技术支持也没有.Net的,真心不好搞! RSA加解密,这里有个 ...
- RSA不对称加密,公钥加密私钥解密,私钥加密公钥解密
RSA算法是第一个能同时用于加密和数字签名的算法,也易于理解和操作. RSA是被研究得最广泛的公钥算法,从提出到现在已近二十年,经历了各种攻击的考验,逐渐为人们接受,普遍认为是目前最优秀的公钥方案之一 ...
- DES加密和解密PHP,Java,ObjectC统一的方法
原文:DES加密和解密PHP,Java,ObjectC统一的方法 PHP的加解密函数 <?php class DesComponent { var $key = '12345678'; func ...
随机推荐
- python图片处理(三)
ji那天用到了python图片处理中的二值图像的骨架提取,在matlab中通过输入图像的二值,来处理得到图像的骨架, skelimage = bwmorph(im, 'skel', inf); 在ma ...
- python 统计MySQL大于100万的表
一.需求分析 线上的MySQL服务器,最近有很多慢查询.需要统计出行数大于100万的表,进行统一优化. 需要筛选出符合条件的表,统计到excel中,格式如下: 库名 表名 行数 db1 users 1 ...
- Visual Studio 2013百度云下载地址
Visual Studio 2013百度云下载地址: 链接: https://pan.baidu.com/s/1JkVYLnFo2TWSu4dkDdZP3Q 提取码: 关注公众号[获取 winf ...
- 修改linux下默认的python版本
首先在终端输入:python --verison 查看本机默认采用的python 版本 接着进入/usr/local/lib 目录查看当前系统中安装了多少个python版本 如果只有一个,就安装你需要 ...
- ODBC在注册表中的位置
增加一个oracle的odbc regedit打开注册表 64位 :HKEY_LOCAL_MACHINE -> SOFTWARE -> 32位: HKEY_LOCAL_MACHINE -& ...
- hdoj1102 Constructing Roads(Prime || Kruskal)
题目链接 http://acm.hdu.edu.cn/showproblem.php?pid=1102 题意 有n个村庄(编号1~n),给出n个村庄之间的距离,开始时n个村庄之间已经有了q条路,现在需 ...
- 【原创】SQL Server常用脚本整理
--1.禁用启用账号账号 set nocount on SELECT 'ALTER LOGIN ' + name + ' ENABLE' FROM master.sys.server_principa ...
- Linux VXLAN
VXLAN协议 VXLAN是Virtual eXtensible Local Area Network的缩写,RFC 7348的标题“A Framework for Overlaying Virtua ...
- CSS3组件化之菊花loading
<div class="juhua-loading"> <div class="jh-circle"></div> < ...
- jQuery中bind,live,delegate,on的区别
bind(),live()都是调用on()函数,只不过传递的参数不同. 一.$(selector).bind(event,data,fn); $('#J_btn').bind('click',func ...