.net中System.Security.Cryptography命名空间

在.NETFramework出现之前,如果我们需要进行加密的话,我们只有各种较底层的技术可以选择,如 Microsoft Crypto API、Crypto++、Openssl等等,其用法相当复杂。而在 .NET Framework中,这些复杂内容已经被封装在各个 .NET 框架类中,并且由一个System.Security.Cryptography 命名空间包含这些与加密、签名相关的类。利用这些类,我们就可以很方便地使用各种广泛使用的算法,包括RSA, DSA, Rijndael, SHA和其他Hash算法等等。

首先,我们了解一下加密中的一些基本术语:

对称加密算法

加密算法的一般类型有对称和非对称两种。对称算法使用相同的密钥来加密和解密数据。对称密钥密码算法所用的加密密钥和解密密钥通常是相同的,即使不同也可以很容易地由其中的任意一个推导出另一个。在此算法中,加、解密双方所用的密钥都要保守秘密。由于计算速度快,对称加密算法被广泛应用于大量数据,如文件的加密过程中。

使用分组密码算法数字签名常用的加密标准有:DES,Tripl-DES,RC2,RC4,CAST等。

.NET Framework提供了以下类来实现对称加密算法:

DESCryptoServiceProvider

RC2CryptoServiceProvider

RijndaelManaged

TripleDESCryptoServiceProvider

下面是一个DESCryptoServiceProvider类的应用实例:

下面的示例使用 DESCryptoServiceProvider 类将一些数据加密到内存,然后解密数据。

//This sample demonstrates using a key based on the cryptographic serviceprovider (CSP) version
// of the Data Encryption Standard (DES)algorithm toencrypt a string to a byte array, and then
// to decrypt the byte array back to a string.

using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;

class CryptoMemoryStream
{
// Main method.
public static void Main()
{
// Create a new DES key.
DESCryptoServiceProvider key = newDESCryptoServiceProvider();

// Encrypt a string to a byte array.
byte[] buffer = Encrypt("This is some plaintext!", key);

// Decrypt the byte array back to a string.
string plaintext = Decrypt(buffer, key);

// Display the plaintext value to the console.
Console.WriteLine(plaintext);
}

// Encrypt the string.
public static byte[] Encrypt(stringPlainText, SymmetricAlgorithm key)
{
// Create a memory stream.
MemoryStream ms = new MemoryStream();

// Create a CryptoStream using the memory stream andthe
// CSP DES key.
CryptoStream encStream = new CryptoStream(ms,key.CreateEncryptor(), CryptoStreamMode.Write);

// Create a StreamWriter to write a string
// to the stream.
StreamWriter sw = new StreamWriter(encStream);

// Write the plaintext to the stream.
sw.WriteLine(PlainText);

// Close the StreamWriter and CryptoStream.
sw.Close();
encStream.Close();

// Get an array of bytes that represents
// the memory stream.
byte[] buffer = ms.ToArray();

// Close the memory stream.
ms.Close();

// Return the encrypted byte array.
return buffer;
}

// Decrypt the byte array.
public static string Decrypt(byte[]CypherText, SymmetricAlgorithm key)
{
// Create a memory stream to the passed buffer.
MemoryStream ms = new MemoryStream(CypherText);

// Create a CryptoStream using the memory stream andthe
// CSP DES key.
CryptoStream encStream = new CryptoStream(ms,key.CreateDecryptor(), CryptoStreamMode.Read);

// Create a StreamReader for reading the stream.
StreamReader sr = new StreamReader(encStream);

// Read the stream as a string.
string val = sr.ReadLine();

// Close the streams.
sr.Close();
encStream.Close();
ms.Close();

return val;
}
}

公共钥匙加密算法 (非对称密钥密码算法)

公共钥匙加密算法又称为非对称密钥密码算法。它使用到两个密钥:公开密钥和私有密钥,分别用于对数据的加密和解密,即如果用公开密钥对数据进行加密,只有用对应的私有密钥才能进行解密;如果用私有密钥对数据进行加密,则只有用对应的公开密钥才能解密。

使用公钥密码算法进行数字签名通用的加密标准有: RSA,DSA等。

.NET Framework提供了以下类来实现公共钥匙加密算法(非对称加密算法):

DSACryptoServiceProvider

RSACryptoServiceProvider

下面是一个RSACryptoServiceProvider类的应用实例:

//获取密钥和公钥
public void RSAKey(out string xmlKeys, out string xmlPublicKey)
{
try
{
System.Security.Cryptography.RSACryptoServiceProvider rsa = newRSACryptoServiceProvider();
xmlKeys = rsa.ToXmlString(true);
xmlPublicKey = rsa.ToXmlString(false);
}
catch (Exception ex)
{
throw ex;
}
}
//RSA的加密函数
public string RSAEncrypt(string xmlPublicKey, string m_strEncryptString)
{
try
{
byte[] PlainTextBArray;
byte[] CypherTextBArray;
string Result;
System.Security.Cryptography.RSACryptoServiceProvider rsa = newRSACryptoServiceProvider();
rsa.FromXmlString(xmlPublicKey);
PlainTextBArray = (new UnicodeEncoding()).GetBytes(m_strEncryptString);
CypherTextBArray = rsa.Encrypt(PlainTextBArray, false);
Result = Convert.ToBase64String(CypherTextBArray);
return Result;
}
catch (Exception ex)
{
throw ex;
}
}
//RSA的加密函数
public string RSAEncrypt(string xmlPublicKey, byte[] EncryptString)
{
try
{
byte[] CypherTextBArray;
string Result;
System.Security.Cryptography.RSACryptoServiceProvider rsa = newRSACryptoServiceProvider();
rsa.FromXmlString(xmlPublicKey);
CypherTextBArray = rsa.Encrypt(EncryptString, false);
Result = Convert.ToBase64String(CypherTextBArray);
return Result;
}
catch (Exception ex)
{
throw ex;
}
}

//RSA的解密函数
public string RSADecrypt(string xmlPrivateKey, string m_strDecryptString)
{
try
{
byte[] PlainTextBArray;
byte[] DypherTextBArray;
string Result;
System.Security.Cryptography.RSACryptoServiceProvider rsa = newRSACryptoServiceProvider();
rsa.FromXmlString(xmlPrivateKey);
PlainTextBArray = Convert.FromBase64String(m_strDecryptString);

//XP版本以上为true
DypherTextBArray = rsa.Decrypt(PlainTextBArray, false);
Result = (new UnicodeEncoding()).GetString(DypherTextBArray);
return Result;
}
catch (Exception ex)
{
throw ex;
}
}

//RSA的解密函数
public string RSADecrypt(string xmlPrivateKey, byte[] DecryptString)
{
try
{
byte[] DypherTextBArray;
string Result;
System.Security.Cryptography.RSACryptoServiceProvider rsa = newRSACryptoServiceProvider();
rsa.FromXmlString(xmlPrivateKey);
DypherTextBArray = rsa.Decrypt(DecryptString, false );
Result = (new UnicodeEncoding()).GetString(DypherTextBArray);
return Result;
}
catch (Exception ex)
{
throw ex;
}
}

数字签名

数字签名是指使用密码算法对待发的数据(报文、票证等)进行加密处理,生成一段信息,附着在原文上一起发送,这段信息类似现实中的签名或印章,接收方对其进行验证,判断原文真伪。

目的:提供数据完整性保护和抗否认功能。

.NET Framework提供了以下类来实现数字签名加密算法:

DSACryptoServiceProvider

RSACryptoServiceProvider

Hash 算法

Hash算法也称作散列算法或报文摘要(digital digest)。Hash算法将任意长度数据转化为固定长度字符序列。Hash结果是始终维一的。任意二个序列的Hash结果是不同的。Hash结果亦称为数字指纹(Finger Print),它有固定的长度,且相同的明文摘要必定一致。这样这串摘要使可成为验证明文是否是"真身"的"指纹"了。

Hash算法数字签字通用的加密标准有: SHA-1,MD5等。

.NET Framework提供了以下类来实现加密Hash算法:

HMACSHA1

MACTripleDES

MD5CryptoServiceProvider

SHA1Managed

SHA256Managed

SHA384Managed

SHA512Managed

下面是一个SHA512Managed类的应用实例:

面的示例计算 dataSHA512Managed 哈希值,并将它存储在 result 中。此示例假定存在一个预定义的常数 DATA_SIZE

byte[] data = new byte[DATA_SIZE];

byte[] result;

SHA512 shaM= new SHA512Managed();

result =shaM.ComputeHash(data);

其他

自定义算法:

在machine.config中 .NET 定义了cryptography 设置的Schema。 我们可以通过在machine.config 中的定义,来实现替代某些已有算法并调用自定义算法:

具体的方法,可以参考MSDN中的信息:

Cryptography Settings Schema

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/gngrfcryptographysettingsschema.asp

Configuring Cryptography

<mscorlib><cryptographySettings> <cryptoNameMapping> <cryptoClasses><cryptoClass myMD5="System.Security.Cryptography.MD5CryptoServiceProvider, mscorlib,Ver=1.0.2411.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/></cryptoClasses> <nameEntry name="dan"class="myMD5"/> <nameEntryname="System.Security.Cryptography.HashAlgorithm"class="myMD5"/> </cryptoNameMapping></cryptographySettings></mscorlib>

X.509数字证书

在System.Security.Cryptography.X509Certificates命名空间中,.NET Framework包含了X.509 v.3数字证书的实现。

XML数字签名

在System.Security.Cryptography.XML命名空间中,.NET Framework包含了XML数字签名实现。通过调用该命名空间中的类,我们可以实现对XML对象进行数字签名。

总结

总而言之,.NETFramework 中的System.Security.Cryptography命名空间实现了各类加密,签名的实现。通过调用相应的类库,我们可以很方便地实现各类加密,签名的操作。

System.Security.Cryptography 命名空间的具体定义,我们可以在以下链接找到:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemsecuritycryptography.asp

http://msdn.microsoft.com/zh-cn/library/system.security.cryptography.aspx

net中System.Security.Cryptography 命名空间 下的加密算法的更多相关文章

  1. 高并发分布式系统中生成全局唯一(订单号)Id js返回上一页并刷新、返回上一页、自动刷新页面 父页面操作嵌套iframe子页面的HTML标签元素 .net判断System.Data.DataRow中是否包含某列 .Net使用system.Security.Cryptography.RNGCryptoServiceProvider类与System.Random类生成随机数

    高并发分布式系统中生成全局唯一(订单号)Id   1.GUID数据因毫无规律可言造成索引效率低下,影响了系统的性能,那么通过组合的方式,保留GUID的10个字节,用另6个字节表示GUID生成的时间(D ...

  2. .Net使用system.Security.Cryptography.RNGCryptoServiceProvider类与System.Random类生成随机数

    .Net中我们通常使用Random类生成随机数,在一些场景下,我却发现Random生成的随机数并不可靠,在下面的例子中我们通过循环随机生成10个随机数: ; i < ; i++) { Rando ...

  3. 多线程下System.Security.Cryptography.Aes CreateDecryptor报“Safe handle has been closed”的解决方案

    因为系统需要对一些核心数据进行预加载以保证查询速度. 所以在application_start 事件中启用了后台线程对相关的数据进行加载并解密(为了保证解密的效率,将AES对像做了静态对像来保存:pr ...

  4. System.Security.Cryptography.CryptographicException: 指定了无效的提供程序类型

    这两天在调用银联在线的支付接口,把银联提供的demo代码copy过来放到自己网站上,生成通过了,但是运行的时候就报错了: 指定了无效的提供程序类型. 说明: 执行当前 Web 请求期间,出现未经处理的 ...

  5. 转:system.Security.Cryptography C# 加密和解密

    以下文转自: http://www.360doc.com/content/13/0122/05/19147_261678471.shtml 总结:注册的时候经过MD5加密存进数据库,在登录的时候需要先 ...

  6. "System.Security.Cryptography.CryptographicException: 拒绝访问" 问题的解决方法

    .net web程序使用rsa算法进行加解密时,程序报告“System.Security.Cryptography.CryptographicException: 拒绝访问”错.按网上搜的解决方法做了 ...

  7. 部署时,出现用户代码未处理 System.Security.Cryptography.CryptographicException 错误解决方法

    转载:http://www.cnblogs.com/jys509/p/4499978.html 在调用RSA加密的.pfx密钥时,在本地调试没有问题,可以布署到服务器,就会报以下的错误: 用户代码未处 ...

  8. 使用证书部署出现System.Security.Cryptography.CryptographicException 错误解决方案

    一.System.Security.Cryptography.CryptographicException: 找不到对象 at System.Security.Cryptography.Cryptog ...

  9. WCF:System.Security.Cryptography.CryptographicException: 密钥集不存在

    WCF使用IIS部署时,使用x509证书验证,在创建证书并正确配置程序后,访问出现错误提示: System.Security.Cryptography.CryptographicException: ...

随机推荐

  1. WPF 中,如何使用自定义的resources

    第一步,先自己自定义一个Resources 1.新建一个xaml文件,在其中自定义好自己的Resources 这个Resource 的根节点是 <ResourceDictionary xmlns ...

  2. 【开发】Form Validate 表单验证 扩展应用

    目录: ★.文本输入框(easyui-textbox) ★.数字框(easyui-numberbox) ★.时间(easyui-datebox) ★.文本域(easyui-textbox easyui ...

  3. RTTI(Runtime Type Information )

    RTTI 是“Runtime Type Information”的缩写,意思是:运行时类型信息.它提供了运行时确定对象类型的方法.本文将简略介绍 RTTI 的一些背景知识.描述 RTTI 的概念,并通 ...

  4. 九度OJ 1056--最大公约数 1439--Least Common Multiple 【辗转相除法】

    题目地址:http://ac.jobdu.com/problem.php?pid=1056 题目描述: 输入两个正整数,求其最大公约数. 输入: 测试数据有多组,每组输入两个正整数. 输出: 对于每组 ...

  5. Poj/OpenJudge 1094 Sorting It All Out

    1.链接地址: http://poj.org/problem?id=1094 http://bailian.openjudge.cn/practice/1094 2.题目: Sorting It Al ...

  6. php 一维数组排序,保留key值

    function sort_with_keyName($arr,$orderby='desc'){ //在内存的另一处 $a 复制内容与 $arr 一样的数组 foreach($arr as $key ...

  7. Centos7源码安装mysql及读写分离,互为主从

       Linux服务器 -源码安装mysql 及读写分离,互为主从   一.环境介绍: Linux版本: CentOS 7 64位 mysq版本: mysql-5.6.26 这是我安装时所使用的版本, ...

  8. Live帐号登陆win8系统不用输密码的方法

    win 8 系统旨在让大家日常的操作更加方便与快捷.因此,今天,小编将与大家分享的是如何利用Live帐号登陆win8系统,而不用输密码的方法.具体的步骤如下文所述. 按win+R打开运行输入cmd(在 ...

  9. hdu 1251 统计难题 trie入门

    统计难题 Problem Description Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本 ...

  10. java JDBC操作MySQL数据库

    一,首先在MYSQL建立一个数据库,例如Geek99DB: create database Geek99DB; use Geek99DB; 然后建立一个表CustomerTab: create tab ...