先附上 源码
加密解密算法目前已经应用到我们生活中的各个方面
加密用于达到以下目的:
保密性:帮助保护用户的标识或数据不被读取。
数据完整性:帮助保护数据不被更改。
身份验证:确保数据发自特定的一方。
不可否认性:防止特定的一方否认发送过消息。
为了达到这些目的 ,我们可以使用以下做法:
私钥加密(对称加密) |
此类型的加密使用单个共享的机密密钥来加密和解密数据。 |
公钥加密(不对称加密) |
此类加密使用公钥/私钥对来加密和解密数据。 |
加密签名 |
此过程还使用哈希函数。 |
加密哈希 |
哈希在统计上是唯一的;不同的双字节序列不会哈希为同一个值。 |
.NET Framework 提供了以下类来实现私钥加密算法:
AesManaged (在 .NET Framework 3.5中引入)。
DESCryptoServiceProvider .
哈希值。)
RC2CryptoServiceProvider .
RijndaelManaged .
TripleDESCryptoServiceProvider .
.NET Framework 提供了以下类来实现公钥加密算法:
DSACryptoServiceProvider
RSACryptoServiceProvider
ECDiffieHellman (基类)
ECDiffieHellmanCng
ECDiffieHellmanCngPublicKey (基类)
ECDiffieHellmanKeyDerivationFunction (基类)
ECDsaCng
.NET Framework 提供了以下类来实现数字签名算法:
DSACryptoServiceProvider
RSACryptoServiceProvider
ECDsa (基类)
ECDsaCng
.NET Framework 提供的以下类实现了哈希算法:
HMACSHA1 .
MACTripleDES .
MD5CryptoServiceProvider .
RIPEMD160 .
SHA1Managed .
SHA256Managed .
SHA384Managed .
SHA512Managed .
System.Security.Cryptography 命名空间
Aes | 表示高级加密标准 (AES) 的所有实现都必须从中继承的抽象基类。 | |
AesCryptoServiceProvider | 使用高级加密标准 (AES) 算法的加密应用程序编程接口 (CAPI) 实现来执行对称加密和解密。 | |
AesManaged | 提供高级加密标准 (AES) 对称算法的托管实现。 | |
AsnEncodedData | 表示 Abstract Syntax Notation One (ASN.1) 编码数据。 | |
AsnEncodedDataCollection | 此类不能被继承。 | |
AsnEncodedDataEnumerator | 此类不能被继承。 | |
AsymmetricAlgorithm | 表示所有非对称算法的实现都必须从中继承的抽象基类。 | |
AsymmetricKeyExchangeDeformatter | 表示所有非对称密钥交换反格式化程序均从中派生的基类。 | |
AsymmetricKeyExchangeFormatter | 表示所有非对称密钥交换格式化程序均从中派生的基类。 | |
AsymmetricSignatureDeformatter | 表示所有不对称签名反格式化程序实现均从中派生的抽象基类。 | |
AsymmetricSignatureFormatter | 表示所有不对称签名格式化程序实现均从中派生的基类。 | |
CngAlgorithm | 封装加密算法的名称。 | |
CngAlgorithmGroup | 封装加密算法组的名称。 | |
CngKey | 定义与下一代加密技术 (CNG) 对象一起使用的密钥的核心功能。 | |
CngKeyBlobFormat | 指定与 Microsoft 下一代加密技术 (CNG) 对象一起使用的密钥 BLOB 格式。 | |
CngKeyCreationParameters | 包含密钥创建的高级属性。 | |
CngPropertyCollection | 提供下一代加密技术 (CNG) 属性的强类型集合。 | |
CngProvider | 封装与下一代加密技术 (CNG) 对象一起使用的密钥存储提供程序 (KSP) 的名称。 | |
CngUIPolicy | 为用户界面 (UI) 封装可选配置参数,当您访问受保护的密钥时,下一代加密技术 (CNG) 将显示这些配置参数。 | |
CryptoAPITransform | 此类不能被继承。 | |
CryptoConfig | 访问加密配置信息。 | |
CryptographicAttributeObject | 包含一个类型和与该类型相关联的值的集合。 | |
CryptographicAttributeObjectCollection | CryptographicAttributeObject 对象的集合。 | |
CryptographicAttributeObjectEnumerator | 此类不能被继承。 | |
CryptographicException | 当加密操作中出现错误时引发的异常。 | |
CryptographicUnexpectedOperationException | 当加密操作中出现意外操作时引发的异常。 | |
CryptoStream | 定义将数据流链接到加密转换的流。 | |
CspKeyContainerInfo | 此类不能被继承。 | |
CspParameters | 此类不能被继承。 | |
DataProtector | 提供数据保护程序的基类。 | |
DeriveBytes | 表示抽象基类,导出指定长度字节序列的所有类都从该基类继承。 | |
DES | DES 实现都必须从中派生的数据加密标准 (DES) 算法的基类。 | |
DESCryptoServiceProvider | 此类不能被继承。 | |
DpapiDataProtector | 提供简单数据保护方法。 | |
DSA | DSA) 的实现都必须从中继承的抽象基类。 | |
DSACryptoServiceProvider | 此类不能被继承。 | |
DSASignatureDeformatter | DSA) PKCS#1 1.5 版签名。 | |
DSASignatureFormatter | DSA) 签名。 | |
ECDiffieHellman | 此类提供一个所有 ECDH 实现都必须支持的基本操作集。 | |
ECDiffieHellmanCng | 此类用于执行加密操作。 | |
ECDiffieHellmanCngPublicKey | ECDiffieHellmanCng 类一起使用的椭圆曲线 Diffie-Hellman (ECDH) 公钥。 | |
ECDiffieHellmanPublicKey | ECDiffieHellmanCngPublicKey 实现必须从中继承的抽象基类。 | |
ECDsa | 提供一个封装椭圆曲线数字签名算法 (ECDSA) 的抽象基类。 | |
ECDsaCng | 提供椭圆曲线数字签名算法 (ECDSA) 的下一代加密技术 (CNG) 实现。 | |
FromBase64Transform | CryptoStream。 | |
HashAlgorithm | 表示所有加密哈希算法实现均必须从中派生的基类。 | |
HMAC | 表示基于哈希的消息验证代码 (HMAC) 的所有实现必须从中派生的抽象类。 | |
HMACMD5 | MD5 哈希函数,。 | |
HMACRIPEMD160 | RIPEMD160 哈希函数,。 | |
HMACSHA1 | SHA1 哈希函数计算基于哈希值的消息验证代码 (HMAC)。 | |
HMACSHA256 | SHA256 哈希函数计算基于哈希值的消息验证代码 (HMAC)。 | |
HMACSHA384 | SHA384 哈希函数计算基于哈希值的消息验证代码 (HMAC)。 | |
HMACSHA512 | SHA512 哈希函数计算基于哈希值的消息验证代码 (HMAC)。 | |
KeyedHashAlgorithm | 显示所有加密哈希算法实现均必须从中派生的抽象类。 | |
KeySizes | 确定对称加密算法的有效密钥大小设置。 | |
MACTripleDES | CryptoStream 的消息验证代码 (MAC)。 | |
ManifestSignatureInformation | 提供清单签名的相关信息。 | |
ManifestSignatureInformationCollection | ManifestSignatureInformation 对象的只读集合。 | |
MaskGenerationMethod | 表示所有掩码生成器算法均必须从中派生的抽象类。 | |
MD5 | MD5 哈希算法的所有实现均从中继承的抽象类。 | |
MD5Cng | 提供 MD5(消息摘要 5)128 位哈希算法的 CNG(下一代加密技术)实现。 | |
MD5CryptoServiceProvider | 此类不能被继承。 | |
Oid | 此类不能被继承。 | |
OidCollection | 此类不能被继承。 | |
OidEnumerator | 此类不能被继承。 | |
PasswordDeriveBytes | 使用 PBKDF1 算法的扩展从密码派生密钥。 | |
PKCS1MaskGenerationMethod | 根据 PKCS #1 计算用于密钥交换算法的掩码。 | |
ProtectedData | 此类不能被继承。 | |
ProtectedMemory | 此类不能被继承。 | |
RandomNumberGenerator | 表示加密随机数生成器的所有实现均从中派生的抽象类。 | |
RC2 | RC2 算法的所有实现都必须从中派生的基类。 | |
RC2CryptoServiceProvider | 此类不能被继承。 | |
Rfc2898DeriveBytes | HMACSHA1 的伪随机数生成器,实现基于密码的密钥派生功能 (PBKDF2)。 | |
Rijndael | Rijndael 对称加密算法的所有实现必须从其继承的基类。 | |
RijndaelManaged | 此类不能被继承。 | |
RijndaelManagedTransform | 此类不能被继承。 | |
RIPEMD160 | 表示 MD160 哈希算法的所有实现均从中继承的抽象类。 | |
RIPEMD160Managed | RIPEMD160 哈希值。 | |
RNGCryptoServiceProvider | 此类不能被继承。 | |
RSA | RSA 算法的所有实现均从中继承的基类。 | |
RSACryptoServiceProvider | 此类不能被继承。 | |
RSAOAEPKeyExchangeDeformatter | 对最优不对称加密填充 (OAEP) 密钥交换数据进行解密。 | |
RSAOAEPKeyExchangeFormatter | RSA 创建最优不对称加密填充 (OAEP) 密钥交换数据。 | |
RSAPKCS1KeyExchangeDeformatter | 解密 PKCS #1 密钥交换数据。 | |
RSAPKCS1KeyExchangeFormatter | RSA 创建 PKCS#1 密钥交换数据。 | |
RSAPKCS1SignatureDeformatter | RSA PKCS #1 1.5 版签名。 | |
RSAPKCS1SignatureFormatter | RSA PKCS #1 1.5 版签名。 | |
SHA1 | SHA1 哈希值。 | |
SHA1Cng | 提供安全哈希算法 (SHA) 的下一代加密技术 (CNG) 实现。 | |
SHA1CryptoServiceProvider | 此类不能被继承。 | |
SHA1Managed | SHA1 哈希值。 | |
SHA256 | SHA256 哈希值。 | |
SHA256Cng | 为 256 位哈希值提供安全哈希算法 (SHA) 的下一代加密技术 (CNG) 实现。 | |
SHA256CryptoServiceProvider | SHA256 算法的加密服务提供程序 (CSP) 实现的包装对象。 | |
SHA256Managed | SHA256 哈希值。 | |
SHA384 | SHA384 哈希值。 | |
SHA384Cng | 提供具有 384 位哈希值的安全哈希算法 (SHA) 的下一代加密技术 (CNG) 实现。 | |
SHA384CryptoServiceProvider | SHA384 算法的加密服务提供程序 (CSP) 实现的包装对象。 | |
SHA384Managed | SHA384 哈希值。 | |
SHA512 | SHA512 哈希值。 | |
SHA512Cng | 提供使用 512 位哈希值的安全哈希算法 (SHA) 的下一代加密技术 (CNG) 实现。 | |
SHA512CryptoServiceProvider | SHA512 算法的加密服务提供程序 (CSP) 实现的包装对象。 | |
SHA512Managed | SHA512 哈希算法。 | |
SignatureDescription | 包含有关数字签名的属性的信息。 | |
StrongNameSignatureInformation | 保存清单的强名称签名信息。 | |
SymmetricAlgorithm | 表示所有对称算法的实现都必须从中继承的抽象基类。 | |
ToBase64Transform | CryptoStream 转换为 Base 64。 | |
TripleDES | TripleDES 的所有实现都必须从此基类派生。 | |
TripleDESCryptoServiceProvider | 此类不能被继承。 |
以上内容摘自 微软官网
下面我来介绍一下最近接触的几个加解密算法,包含RSA\AES\DES加解密算法,用到了 .NET Framework 中提供的RSACryptoServiceProvider类、AesCryptoServiceProvider类、AesManaged类、SHA256Managed类、MD5类、DESCryptoServiceProvider类、SHA1类;
1、RSA
using MY.Cipher.Csv; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; namespace MY.Cipher { public class RSACode { /// <summary> /// 创建RSA公钥和私钥 /// </summary> /// <param name="publicKey"></param> /// <param name="privateKey"></param> /// <returns></returns> public static bool CreateKey( out string publicKey, out string privateKey) { publicKey = null ; privateKey = null ; try { using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { #if RSAXML privateKey = rsa.ToXmlString( true ); publicKey = rsa.ToXmlString( false ); #else byte [] publicKeyBytes = rsa.ExportCspBlob( false ); byte [] privateKeyBytes = rsa.ExportCspBlob( true ); publicKey = Convert.ToBase64String(publicKeyBytes); privateKey = Convert.ToBase64String(privateKeyBytes); #endif return true ; } } catch (Exception) { return false ; } } /// <summary> /// RSA加密 /// </summary> /// <param name="publickey"></param> /// <param name="content"></param> /// <returns></returns> public static string Encrypt( string publickey, string content) { if ( string .IsNullOrEmpty(content)) return null ; using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { byte [] cipherbytes; #if RSAXML rsa.FromXmlString(publickey); #else byte [] keyBytes = Convert.FromBase64String(publickey); rsa.ImportCspBlob(keyBytes); #endif cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(content), false ); return Convert.ToBase64String(cipherbytes); } } /// <summary> /// RSA加密 /// </summary> /// <param name="publickey"></param> /// <param name="dt"></param> /// <param name="columnIndexs"></param> /// <returns></returns> public static DataTable Encrypt( string publickey, DataTable dt, int [] columnIndexs) { if (dt == null ) return null ; DataTable result = dt.Clone(); using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { #if RSAXML rsa.FromXmlString(publickey); #else byte [] keyBytes = Convert.FromBase64String(publickey); rsa.ImportCspBlob(keyBytes); #endif foreach (DataRow dr in dt.Rows) { object [] objs = dr.ItemArray; foreach ( int index in columnIndexs) { if (objs[index] != null && objs[index] != DBNull.Value) { byte [] bytes = rsa.Encrypt(Encoding.UTF8.GetBytes(objs[index].ToString()), false ); objs[index] = Convert.ToBase64String(bytes); } } result.Rows.Add(objs); } } return result; } /// <summary> /// RSA解密 /// </summary> /// <param name="privatekey"></param> /// <param name="content"></param> /// <returns></returns> public static string Decrypt( string privatekey, string content) { if ( string .IsNullOrEmpty(content)) return null ; using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { byte [] cipherbytes; #if RSAXML rsa.FromXmlString(privatekey); #else byte [] keyBytes = Convert.FromBase64String(privatekey); rsa.ImportCspBlob(keyBytes); #endif cipherbytes = rsa.Decrypt(Convert.FromBase64String(content), false ); return Encoding.UTF8.GetString(cipherbytes); } } /// <summary> /// RSA解密 /// </summary> /// <param name="privatekey"></param> /// <param name="dt"></param> /// <param name="columnIndexs"></param> /// <returns></returns> public static DataTable Decrypt( string privatekey, DataTable dt, int [] columnIndexs) { if (dt == null ) return null ; DataTable result = dt.Clone(); using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { #if RSAXML rsa.FromXmlString(privatekey); #else byte [] keyBytes = Convert.FromBase64String(privatekey); rsa.ImportCspBlob(keyBytes); #endif foreach (DataRow dr in dt.Rows) { object [] objs = dr.ItemArray; foreach ( int index in columnIndexs) { if (objs[index] != null && objs[index] != DBNull.Value) { byte [] bytes = rsa.Decrypt(Convert.FromBase64String(objs[index].ToString()), false ); objs[index] = Encoding.UTF8.GetString(bytes); } } result.Rows.Add(objs); } } return result; } public static int Encrypt( string publickey, string src, string dest, int [] columns, Predicate< string > action) { return Encrypt(publickey, src, dest, true , columns, action); } public static int Encrypt( string publickey, string src, string dest, bool hasHeaders, int [] columns, Predicate< string > action) { using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { #if RSAXML rsa.FromXmlString(publickey); #else byte [] keyBytes = Convert.FromBase64String(publickey); rsa.ImportCspBlob(keyBytes); #endif using (TextReader reader = new StreamReader(src, Encoding.Default)) { using (TextWriter writer = new StreamWriter(dest, false , Encoding.Default)) { CsvReader _reader = new CsvReader(reader, hasHeaders); if (hasHeaders) writer.WriteLine( string .Join( " , " , _reader.GetFieldHeaders())); int rowIndex = 0 ; while (_reader.ReadNextRecord()) { if (rowIndex > 0 && rowIndex % 100 == 0 && action != null ) { if (!action( string .Format( " 正在处理第{0}行... " , rowIndex))) break ; } string [] objs = new string [_reader.FieldCount]; for ( int index = 0 ; index < objs.Length; index++ ) { if (_reader[index] != null && Array.Exists(columns, (column) => { return Convert.ToInt32(column) == index; })) { byte [] bytes = rsa.Encrypt(Encoding.UTF8.GetBytes(_reader[index].ToString()), false ); objs[index] = Convert.ToBase64String(bytes); } else objs[index] = _reader[index]; } writer.WriteLine( string .Join( " , " , objs)); rowIndex ++ ; } reader.Close(); writer.Close(); return rowIndex; } } } } public static void Encrypt( string publickey, string src, string dest, int [] columns) { Encrypt(publickey, src, dest, columns, null ); } public static int Decrypt( string privatekey, string src, string dest, int [] columns, Predicate< string > action) { return Decrypt(privatekey, src, dest, true , columns, action); } public static int Decrypt( string privatekey, string src, string dest, bool hasHeaders, int [] columns, Predicate< string > action) { using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { #if RSAXML rsa.FromXmlString(privatekey); #else byte [] keyBytes = Convert.FromBase64String(privatekey); rsa.ImportCspBlob(keyBytes); #endif using (TextReader reader = new StreamReader(src, Encoding.Default)) { using (TextWriter writer = new StreamWriter(dest, false , Encoding.Default)) { CsvReader _reader = new CsvReader(reader, hasHeaders); if (hasHeaders) writer.WriteLine( string .Join( " , " , _reader.GetFieldHeaders())); int rowIndex = 0 ; while (_reader.ReadNextRecord()) { if (rowIndex > 0 && rowIndex % 100 == 0 && action != null ) { if (!action( string .Format( " 正在处理第{0}行... " , rowIndex))) break ; } string [] objs = new string [_reader.FieldCount]; for ( int index = 0 ; index < objs.Length; index++ ) { if (_reader[index] != null && Array.Exists(columns, (column) => { return Convert.ToInt32(column) == index; })) { byte [] bytes = rsa.Decrypt(Convert.FromBase64String(_reader[index].ToString()), false ); objs[index] = Encoding.UTF8.GetString(bytes); } else objs[index] = _reader[index]; } writer.WriteLine( string .Join( " , " , objs)); rowIndex ++ ; } reader.Close(); writer.Close(); return rowIndex; } } } } public static void Decrypt( string privatekey, string src, string dest, int [] columns) { Decrypt(privatekey, src, dest, columns, null ); } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; namespace MY.Cipher { interface ICipher { // string Key { get; set; } string Encrypt( string val); string Decrypt( string val); DataTable Encrypt(DataTable dt, int [] columnIndexs); DataTable Decrypt(DataTable dt, int [] columnIndexs); int Encrypt( string src, string dest, int [] columns, Predicate< string > action); int Decrypt( string src, string dest, int [] columns, Predicate< string > action); int Encrypt( string src, string dest, bool hasHeaders, int [] columns, Predicate< string > action); int Decrypt( string src, string dest, bool hasHeaders, int [] columns, Predicate< string > action); // void GeneralKeyIV(string keyStr, out byte[] key, out byte[] iv); } }
2、AES
using MY.Cipher.Csv; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; namespace MY.Cipher { public class AESCode : ICipher { public string Key { get ; set ; } public string Encrypt( string val) { if ( string .IsNullOrEmpty(val)) return null ; #if CSP using (AesCryptoServiceProvider des = new AesCryptoServiceProvider()) #else using (AesManaged des = new AesManaged()) #endif { byte [] inputByteArray = Encoding.UTF8.GetBytes(val); byte [] _key; byte [] _iv; GeneralKeyIV( this .Key, out _key, out _iv); des.Key = _key; des.IV = _iv; using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(inputByteArray, 0 , inputByteArray.Length); cs.FlushFinalBlock(); byte [] bytes = ( byte [])ms.ToArray(); return Convert.ToBase64String(bytes); } } } } public string Decrypt( string val) { if ( string .IsNullOrEmpty(val)) return null ; #if CSP using (AesCryptoServiceProvider des = new AesCryptoServiceProvider()) #else using (AesManaged des = new AesManaged()) #endif { byte [] inputByteArray = Convert.FromBase64String(val); byte [] _key; byte [] _iv; GeneralKeyIV( this .Key, out _key, out _iv); des.Key = _key; des.IV = _iv; using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(inputByteArray, 0 , inputByteArray.Length); cs.FlushFinalBlock(); return Encoding.UTF8.GetString(ms.ToArray()); } } } } public DataTable Encrypt(DataTable dt, int [] columnIndexs) { if (dt == null ) return null ; DataTable result = dt.Clone(); #if CSP using (AesCryptoServiceProvider des = new AesCryptoServiceProvider()) #else using (AesManaged des = new AesManaged()) #endif { byte [] _key; byte [] _iv; GeneralKeyIV( this .Key, out _key, out _iv); des.Key = _key; des.IV = _iv; ICryptoTransform transform = des.CreateEncryptor(); foreach (DataRow dr in dt.Rows) { object [] objs = dr.ItemArray; foreach ( int index in columnIndexs) { if (objs[index] != null && objs[index] != DBNull.Value) { using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, transform, CryptoStreamMode.Write)) { byte [] src = Encoding.UTF8.GetBytes(objs[index].ToString()); if (src.Length == 0 ) continue ; cs.Write(src, 0 , src.Length); cs.FlushFinalBlock(); byte [] bytes = ( byte [])ms.ToArray(); objs[index] = Convert.ToBase64String(bytes); } } } } result.Rows.Add(objs); } } return result; } public DataTable Decrypt(DataTable dt, int [] columnIndexs) { if (dt == null ) return null ; DataTable result = dt.Clone(); #if CSP using (AesCryptoServiceProvider des = new AesCryptoServiceProvider()) #else using (AesManaged des = new AesManaged()) #endif { byte [] _key; byte [] _iv; GeneralKeyIV( this .Key, out _key, out _iv); des.Key = _key; des.IV = _iv; ICryptoTransform transform = des.CreateDecryptor(); foreach (DataRow dr in dt.Rows) { object [] objs = dr.ItemArray; foreach ( int index in columnIndexs) { if (objs[index] != null && objs[index] != DBNull.Value) { using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, transform, CryptoStreamMode.Write)) { byte [] src = Convert.FromBase64String(objs[index].ToString()); if (src.Length == 0 ) continue ; cs.Write(src, 0 , src.Length); cs.FlushFinalBlock(); objs[index] = Encoding.UTF8.GetString(ms.ToArray()); } } } } result.Rows.Add(objs); } } return result; } public int Encrypt( string src, string dest, int [] columns, Predicate< string > action) { return Encrypt(src, dest, true , columns, action); } public int Decrypt( string src, string dest, int [] columns, Predicate< string > action) { return Decrypt(src, dest, true , columns, action); } public int Encrypt( string src, string dest, bool hasHeaders, int [] columns, Predicate< string > action) { #if CSP using (AesCryptoServiceProvider des = new AesCryptoServiceProvider()) #else using (AesManaged des = new AesManaged()) #endif { byte [] _key; byte [] _iv; GeneralKeyIV( this .Key, out _key, out _iv); des.Key = _key; des.IV = _iv; ICryptoTransform transform = des.CreateEncryptor(); using (TextReader reader = new StreamReader(src, Encoding.Default)) { using (TextWriter writer = new StreamWriter(dest, false , Encoding.Default)) { CsvReader _reader = new CsvReader(reader, hasHeaders); if (hasHeaders) writer.WriteLine( string .Join( " , " , _reader.GetFieldHeaders())); int rowIndex = 0 ; while (_reader.ReadNextRecord()) { if (rowIndex > 0 && rowIndex % 100 == 0 && action != null ) { if (!action( string .Format( " 正在处理第{0}行... " , rowIndex))) break ; } string [] objs = new string [_reader.FieldCount]; for ( int index = 0 ; index < objs.Length; index++ ) { if (_reader[index] != null && Array.Exists(columns, (column) => { return Convert.ToInt32(column) == index; })) { using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, transform, CryptoStreamMode.Write)) { byte [] _bytes = Encoding.UTF8.GetBytes(_reader[index].ToString()); if (_bytes.Length == 0 ) continue ; cs.Write(_bytes, 0 , _bytes.Length); cs.FlushFinalBlock(); byte [] bytes = ( byte [])ms.ToArray(); objs[index] = Convert.ToBase64String(bytes); } } } else objs[index] = _reader[index]; } writer.WriteLine( string .Join( " , " , objs)); rowIndex ++ ; } reader.Close(); writer.Close(); return rowIndex; } } } } public int Decrypt( string src, string dest, bool hasHeaders, int [] columns, Predicate< string > action) { #if CSP using (AesCryptoServiceProvider des = new AesCryptoServiceProvider()) #else using (AesManaged des = new AesManaged()) #endif { byte [] _key; byte [] _iv; GeneralKeyIV( this .Key, out _key, out _iv); des.Key = _key; des.IV = _iv; ICryptoTransform transform = des.CreateDecryptor(); using (TextReader reader = new StreamReader(src, Encoding.Default)) { using (TextWriter writer = new StreamWriter(dest, false , Encoding.Default)) { CsvReader _reader = new CsvReader(reader, hasHeaders); if (hasHeaders) writer.WriteLine( string .Join( " , " , _reader.GetFieldHeaders())); int rowIndex = 0 ; while (_reader.ReadNextRecord()) { if (rowIndex > 0 && rowIndex % 100 == 0 && action != null ) { if (!action( string .Format( " 正在处理第{0}行... " , rowIndex))) break ; } string [] objs = new string [_reader.FieldCount]; for ( int index = 0 ; index < objs.Length; index++ ) { if (_reader[index] != null && Array.Exists(columns, (column) => { return Convert.ToInt32(column) == index; })) { using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, transform, CryptoStreamMode.Write)) { byte [] _bytes = Convert.FromBase64String(_reader[index].ToString()); if (_bytes.Length == 0 ) continue ; cs.Write(_bytes, 0 , _bytes.Length); cs.FlushFinalBlock(); objs[index] = Encoding.UTF8.GetString(ms.ToArray()); } } } else objs[index] = _reader[index]; } writer.WriteLine( string .Join( " , " , objs)); rowIndex ++ ; } reader.Close(); writer.Close(); return rowIndex; } } } } public void GeneralKeyIV( string keyStr, out byte [] key, out byte [] iv) { byte [] bytes = Encoding.UTF8.GetBytes(keyStr); key = SHA256Managed.Create().ComputeHash(bytes); iv = MD5.Create().ComputeHash(bytes); } } }
3、DES
using MY.Cipher.Csv; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; namespace MY.Cipher { public class DESCode : ICipher { public string Key { get ; set ; } public string Encrypt( string val) { if ( string .IsNullOrEmpty(val)) return null ; using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) { byte [] inputByteArray = Encoding.UTF8.GetBytes(val); byte [] _key; byte [] _iv; GeneralKeyIV( this .Key, out _key, out _iv); des.Key = _key; des.IV = _iv; using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(inputByteArray, 0 , inputByteArray.Length); cs.FlushFinalBlock(); byte [] bytes = ( byte [])ms.ToArray(); return Convert.ToBase64String(bytes); } } } } public string Decrypt( string val) { if ( string .IsNullOrEmpty(val)) return null ; using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) { byte [] inputByteArray = Convert.FromBase64String(val); byte [] _key; byte [] _iv; GeneralKeyIV( this .Key, out _key, out _iv); des.Key = _key; des.IV = _iv; using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(inputByteArray, 0 , inputByteArray.Length); cs.FlushFinalBlock(); return Encoding.UTF8.GetString(ms.ToArray()); } } } } public DataTable Encrypt(DataTable dt, int [] columnIndexs) { if (dt == null ) return null ; DataTable result = dt.Clone(); using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) { byte [] _key; byte [] _iv; GeneralKeyIV( this .Key, out _key, out _iv); des.Key = _key; des.IV = _iv; ICryptoTransform transform = des.CreateEncryptor(); foreach (DataRow dr in dt.Rows) { object [] objs = dr.ItemArray; foreach ( int index in columnIndexs) { if (objs[index] != null && objs[index] != DBNull.Value) { using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, transform, CryptoStreamMode.Write)) { byte [] src = Encoding.UTF8.GetBytes(objs[index].ToString()); if (src.Length == 0 ) continue ; cs.Write(src, 0 , src.Length); cs.FlushFinalBlock(); byte [] bytes = ( byte [])ms.ToArray(); objs[index] = Convert.ToBase64String(bytes); } } } } result.Rows.Add(objs); } } return result; } public DataTable Decrypt(DataTable dt, int [] columnIndexs) { if (dt == null ) return null ; DataTable result = dt.Clone(); using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) { byte [] _key; byte [] _iv; GeneralKeyIV( this .Key, out _key, out _iv); des.Key = _key; des.IV = _iv; ICryptoTransform transform = des.CreateDecryptor(); foreach (DataRow dr in dt.Rows) { object [] objs = dr.ItemArray; foreach ( int index in columnIndexs) { if (objs[index] != null && objs[index] != DBNull.Value) { using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, transform, CryptoStreamMode.Write)) { byte [] src = Convert.FromBase64String(objs[index].ToString()); if (src.Length == 0 ) continue ; cs.Write(src, 0 , src.Length); cs.FlushFinalBlock(); objs[index] = Encoding.UTF8.GetString(ms.ToArray()); } } } } result.Rows.Add(objs); } } return result; } public int Encrypt( string src, string dest, int [] columns, Predicate< string > action) { return Encrypt(src, dest, true , columns, action); } public int Decrypt( string src, string dest, int [] columns, Predicate< string > action) { return Decrypt(src, dest, true , columns, action); } public int Encrypt( string src, string dest, bool hasHeaders, int [] columns, Predicate< string > action) { using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) { byte [] _key; byte [] _iv; GeneralKeyIV( this .Key, out _key, out _iv); des.Key = _key; des.IV = _iv; ICryptoTransform transform = des.CreateEncryptor(); using (TextReader reader = new StreamReader(src, Encoding.Default)) { using (TextWriter writer = new StreamWriter(dest, false , Encoding.Default)) { CsvReader _reader = new CsvReader(reader, hasHeaders); if (hasHeaders) writer.WriteLine( string .Join( " , " , _reader.GetFieldHeaders())); int rowIndex = 0 ; while (_reader.ReadNextRecord()) { if (rowIndex > 0 && rowIndex % 100 == 0 && action != null ) { if (!action( string .Format( " 正在处理第{0}行... " , rowIndex))) break ; } string [] objs = new string [_reader.FieldCount]; for ( int index = 0 ; index < objs.Length; index++ ) { if (_reader[index] != null && Array.Exists(columns, (column) => { return Convert.ToInt32(column) == index; })) { using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, transform, CryptoStreamMode.Write)) { byte [] _bytes = Encoding.UTF8.GetBytes(_reader[index].ToString()); if (_bytes.Length == 0 ) continue ; cs.Write(_bytes, 0 , _bytes.Length); cs.FlushFinalBlock(); byte [] bytes = ( byte [])ms.ToArray(); objs[index] = Convert.ToBase64String(bytes); } } } else objs[index] = _reader[index]; } writer.WriteLine( string .Join( " , " , objs)); rowIndex ++ ; } reader.Close(); writer.Close(); return rowIndex; } } } } public int Decrypt( string src, string dest, bool hasHeaders, int [] columns, Predicate< string > action) { using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) { byte [] _key; byte [] _iv; GeneralKeyIV( this .Key, out _key, out _iv); des.Key = _key; des.IV = _iv; ICryptoTransform transform = des.CreateDecryptor(); using (TextReader reader = new StreamReader(src, Encoding.Default)) { using (TextWriter writer = new StreamWriter(dest, false , Encoding.Default)) { CsvReader _reader = new CsvReader(reader, hasHeaders); if (hasHeaders) writer.WriteLine( string .Join( " , " , _reader.GetFieldHeaders())); int rowIndex = 0 ; while (_reader.ReadNextRecord()) { if (rowIndex > 0 && rowIndex % 100 == 0 && action != null ) { if (!action( string .Format( " 正在处理第{0}行... " , rowIndex))) break ; } string [] objs = new string [_reader.FieldCount]; for ( int index = 0 ; index < objs.Length; index++ ) { if (_reader[index] != null && Array.Exists(columns, (column) => { return Convert.ToInt32(column) == index; })) { using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, transform, CryptoStreamMode.Write)) { byte [] _bytes = Convert.FromBase64String(_reader[index].ToString()); if (_bytes.Length == 0 ) continue ; cs.Write(_bytes, 0 , _bytes.Length); cs.FlushFinalBlock(); objs[index] = Encoding.UTF8.GetString(ms.ToArray()); } } } else objs[index] = _reader[index]; } writer.WriteLine( string .Join( " , " , objs)); rowIndex ++ ; } reader.Close(); writer.Close(); return rowIndex; } } } } public void GeneralKeyIV( string keyStr, out byte [] key, out byte [] iv) { byte [] bytes = Encoding.UTF8.GetBytes(keyStr); byte [] _key = SHA1.Create().ComputeHash(bytes); key = new byte [ 8 ]; iv = new byte [ 8 ]; for ( int i = 0 ; i < 8 ; i++ ) { iv[i] = _key[i]; key[i] = _key[i]; } } } }