先附上源码

加密解密算法目前已经应用到我们生活中的各个方面

加密用于达到以下目的:

  • 保密性:帮助保护用户的标识或数据不被读取。

  • 数据完整性:帮助保护数据不被更改。

  • 身份验证:确保数据发自特定的一方。

  • 不可否认性:防止特定的一方否认发送过消息。

为了达到这些目的,我们可以使用以下做法:

私钥加密(对称加密)

对数据执行转换,使第三方无法读取该数据。 此类型的加密使用单个共享的机密密钥来加密和解密数据。

公钥加密(不对称加密)

对数据执行转换,使第三方无法读取该数据。 此类加密使用公钥/私钥对来加密和解密数据。

加密签名

通过创建对特定方唯一的数字签名来帮助验证数据是否发自特定方。 此过程还使用哈希函数。

加密哈希

将数据从任意长度映射为定长字节序列。 哈希在统计上是唯一的;不同的双字节序列不会哈希为同一个值。

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

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

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

.NET Framework 提供的以下类实现了哈希算法:

System.Security.Cryptography 命名空间

  说明
Aes 表示高级加密标准 (AES) 的所有实现都必须从中继承的抽象基类。
AesCryptoServiceProvider 使用高级加密标准 (AES) 算法的加密应用程序编程接口 (CAPI) 实现来执行对称加密和解密。
AesManaged 提供高级加密标准 (AES) 对称算法的托管实现。
AsnEncodedData 表示 Abstract Syntax Notation One (ASN.1) 编码数据。
AsnEncodedDataCollection 表示 AsnEncodedData 对象的集合。 此类不能被继承。
AsnEncodedDataEnumerator 提供在 AsnEncodedDataCollection 对象中导航的能力。 此类不能被继承。
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 CryptographicAttributeObjectCollection 集合提供枚举功能。 此类不能被继承。
CryptographicException 当加密操作中出现错误时引发的异常。
CryptographicUnexpectedOperationException 当加密操作中出现意外操作时引发的异常。
CryptoStream 定义将数据流链接到加密转换的流。
CspKeyContainerInfo 提供有关加密密钥对的附加信息。 此类不能被继承。
CspParameters 包含传递给执行加密计算的加密服务提供程序 (CSP) 的参数。 此类不能被继承。
DataProtector 提供数据保护程序的基类。
DeriveBytes 表示抽象基类,导出指定长度字节序列的所有类都从该基类继承。
DES 表示所有 DES 实现都必须从中派生的数据加密标准 (DES) 算法的基类。
DESCryptoServiceProvider 定义访问数据加密标准 (DES) 算法的加密服务提供程序 (CSP) 版本的包装对象。 此类不能被继承。
DpapiDataProtector 提供简单数据保护方法。
DSA 表示所有数字签名算法 (DSA) 的实现都必须从中继承的抽象基类。
DSACryptoServiceProvider 定义访问 DSA 算法的加密服务提供程序 (CSP) 实现的包装对象。 此类不能被继承。
DSASignatureDeformatter 验证数字签名算法 (DSA) PKCS#1 1.5 版签名。
DSASignatureFormatter 创建数字签名算法 (DSA) 签名。
ECDiffieHellman 提供一个抽象基类,可以从它派生椭圆曲线 Diffie-Hellman (ECDH) 算法实现。 此类提供一个所有 ECDH 实现都必须支持的基本操作集。
ECDiffieHellmanCng 提供椭圆曲线 Diffie-Hellman (ECDH) 算法的下一代加密技术 (CNG) 实现。 此类用于执行加密操作。
ECDiffieHellmanCngPublicKey 指定与 ECDiffieHellmanCng 类一起使用的椭圆曲线 Diffie-Hellman (ECDH) 公钥。
ECDiffieHellmanPublicKey 提供所有 ECDiffieHellmanCngPublicKey 实现必须从中继承的抽象基类。
ECDsa 提供一个封装椭圆曲线数字签名算法 (ECDSA) 的抽象基类。
ECDsaCng 提供椭圆曲线数字签名算法 (ECDSA) 的下一代加密技术 (CNG) 实现。
FromBase64Transform 从 Base 64 转换 CryptoStream
HashAlgorithm 表示所有加密哈希算法实现均必须从中派生的基类。
HMAC 表示基于哈希的消息验证代码 (HMAC) 的所有实现必须从中派生的抽象类。
HMACMD5 计算基于哈希的消息身份验证代码 (HMAC) 使用 MD5 哈希函数,。
HMACRIPEMD160 计算基于哈希的消息身份验证代码 (HMAC) 使用 RIPEMD160 哈希函数,。
HMACSHA1 使用 SHA1 哈希函数计算基于哈希值的消息验证代码 (HMAC)。
HMACSHA256 使用 SHA256 哈希函数计算基于哈希值的消息验证代码 (HMAC)。
HMACSHA384 使用 SHA384 哈希函数计算基于哈希值的消息验证代码 (HMAC)。
HMACSHA512 使用 SHA512 哈希函数计算基于哈希值的消息验证代码 (HMAC)。
KeyedHashAlgorithm 显示所有加密哈希算法实现均必须从中派生的抽象类。
KeySizes 确定对称加密算法的有效密钥大小设置。
MACTripleDES 使用 TripleDES 计算输入数据 CryptoStream 的消息验证代码 (MAC)。
ManifestSignatureInformation 提供清单签名的相关信息。
ManifestSignatureInformationCollection 表示 ManifestSignatureInformation 对象的只读集合。 
MaskGenerationMethod 表示所有掩码生成器算法均必须从中派生的抽象类。
MD5 表示 MD5 哈希算法的所有实现均从中继承的抽象类。
MD5Cng 提供 MD5(消息摘要 5)128 位哈希算法的 CNG(下一代加密技术)实现。
MD5CryptoServiceProvider 使用加密服务提供程序 (CSP) 提供的实现,计算输入数据的 MD5 哈希值。 此类不能被继承。
Oid 表示加密对象标识符。 此类不能被继承。
OidCollection 表示 Oid 对象的集合。 此类不能被继承。
OidEnumerator 提供在 OidCollection 对象中导航的能力。 此类不能被继承。
PasswordDeriveBytes 使用 PBKDF1 算法的扩展从密码派生密钥。
PKCS1MaskGenerationMethod 根据 PKCS #1 计算用于密钥交换算法的掩码。
ProtectedData 为加密和解密数据提供方法。 此类不能被继承。
ProtectedMemory 提供保护内存和取消内存保护的方法。 此类不能被继承。
RandomNumberGenerator 表示加密随机数生成器的所有实现均从中派生的抽象类。
RC2 表示 RC2 算法的所有实现都必须从中派生的基类。
RC2CryptoServiceProvider 定义访问 RC2 算法的加密服务提供程序 (CSP) 实现的包装对象。 此类不能被继承。
Rfc2898DeriveBytes 通过使用基于 HMACSHA1 的伪随机数生成器,实现基于密码的密钥派生功能 (PBKDF2)。
Rijndael 表示 Rijndael 对称加密算法的所有实现必须从其继承的基类。
RijndaelManaged 访问 Rijndael 算法的托管版本。 此类不能被继承。
RijndaelManagedTransform 使用 Rijndael 算法执行数据的加密转换。 此类不能被继承。
RIPEMD160 表示 MD160 哈希算法的所有实现均从中继承的抽象类。
RIPEMD160Managed 使用托管库计算输入数据的 RIPEMD160 哈希值。
RNGCryptoServiceProvider 使用加密服务提供程序 (CSP) 提供的实现来实现加密随机数生成器 (RNG)。 此类不能被继承。
RSA 表示 RSA 算法的所有实现均从中继承的基类。
RSACryptoServiceProvider 使用加密服务提供程序 (CSP) 提供的 RSA 算法的实现执行不对称加密和解密。 此类不能被继承。
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 使用加密服务提供程序 (CSP) 提供的实现计算输入数据的 SHA1 哈希值。 此类不能被继承。
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 定义访问 TripleDES 算法的加密服务提供程序 (CSP) 版本的包装对象。 此类不能被继承。

以上内容摘自微软官网

下面我来介绍一下最近接触的几个加解密算法,包含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 = ;
while (_reader.ReadNextRecord())
{
if (rowIndex > && rowIndex % == && action != null)
{
if (!action(string.Format("正在处理第{0}行...", rowIndex)))
break;
}
string[] objs = new string[_reader.FieldCount];
for (int index = ; 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 = ;
while (_reader.ReadNextRecord())
{
if (rowIndex > && rowIndex % == && action != null)
{
if (!action(string.Format("正在处理第{0}行...", rowIndex)))
break;
}
string[] objs = new string[_reader.FieldCount];
for (int index = ; 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, , 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, , 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 == )
continue;
cs.Write(src, , 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 == )
continue;
cs.Write(src, , 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 = ;
while (_reader.ReadNextRecord())
{
if (rowIndex > && rowIndex % == && action != null)
{
if (!action(string.Format("正在处理第{0}行...", rowIndex)))
break;
}
string[] objs = new string[_reader.FieldCount];
for (int index = ; 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 == )
continue;
cs.Write(_bytes, , _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 = ;
while (_reader.ReadNextRecord())
{
if (rowIndex > && rowIndex % == && action != null)
{
if (!action(string.Format("正在处理第{0}行...", rowIndex)))
break;
}
string[] objs = new string[_reader.FieldCount];
for (int index = ; 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 == )
continue;
cs.Write(_bytes, , _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, , 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, , 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 == )
continue;
cs.Write(src, , 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 == )
continue;
cs.Write(src, , 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 = ;
while (_reader.ReadNextRecord())
{
if (rowIndex > && rowIndex % == && action != null)
{
if (!action(string.Format("正在处理第{0}行...", rowIndex)))
break;
}
string[] objs = new string[_reader.FieldCount];
for (int index = ; 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 == )
continue;
cs.Write(_bytes, , _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 = ;
while (_reader.ReadNextRecord())
{
if (rowIndex > && rowIndex % == && action != null)
{
if (!action(string.Format("正在处理第{0}行...", rowIndex)))
break;
}
string[] objs = new string[_reader.FieldCount];
for (int index = ; 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 == )
continue;
cs.Write(_bytes, , _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[];
iv = new byte[];
for (int i = ; i < ; i++)
{
iv[i] = _key[i];
key[i] = _key[i];
}
}
}
}

C#加解密算法的更多相关文章

  1. 3des加解密算法

    编号:1003时间:2016年4月1日09:51:11功能:openssl_3des加解密算法http://blog.csdn.net/alonesword/article/details/17385 ...

  2. QQ协议的TEA加解密算法

    QQ通讯协议里的加解密算法. #include <stdio.h> #include <stdlib.h> #include <memory.h> #include ...

  3. DES加解密算法Qt实现

      算法解密qt加密table64bit [声明] (1) 本文源码 大部分源码来自:DES算法代码.在此基础上,利用Qt编程进行了改写,实现了DES加解密算法,并添加了文件加解密功能.在此对署名为b ...

  4. AES加解密算法Qt实现

    [声明] (1) 本文源码 在一位未署名网友源码基础上,利用Qt编程,实现了AES加解密算法,并添加了文件加解密功能.在此表示感谢!该源码仅供学习交流,请勿用于商业目的. (2) 图片及描述 除图1外 ...

  5. AES加解密算法在Android中的应用及Android4.2以上版本调用问题

     from://http://blog.csdn.net/xinzheng_wang/article/details/9159969 AES加解密算法在Android中的应用及Android4.2以上 ...

  6. [转]RSA,DSA等加解密算法介绍

    From : http://blog.sina.com.cn/s/blog_a9303fd90101cgw4.html 1)      MD5/SHA MessageDigest是一个数据的数字指纹. ...

  7. JavaScript与C#互通的DES加解密算法

    原文地址:传送门 本文提供了一个能使JavaScript与C#互通的DES加解密算法的实现,在前台页面中用JavaScript版本的DES算法将数据加密之后,传到服务器端,在服务器端可用C#版本的DE ...

  8. RSA 加解密算法

    与DES不同,RSA算法中,每个通信主体都有两个钥匙,一个公钥一个私钥. 就是有2把钥匙1.使用publicKey可以对数据进行加密2.使用Key才能对数据进行解密单方向传输用公钥加密的数据,只有私钥 ...

  9. 加解密算法二:非对称加解密及RSA算法的实现

    加密和解密使用不同的密钥的一类加密算法.这类加密算法通常有两个密钥A和B,使用密钥A加密数据得到的密文,只有密钥B可以进行解密操作(即使密钥A也无法解密):相反,使用密钥B加密数据得到的密文,只有密钥 ...

随机推荐

  1. centos7 系统优化

    #!/usr/bin/env bash #设置环境变量 export PATH=$PATH:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/u ...

  2. POJ 2601

    #include<iostream> #include<iomanip> #include<stdio.h> using namespace std; int ma ...

  3. vue教程2-08 自定义键盘信息、监听数据变化vm.$watch

    vue教程2-08 自定义键盘信息 @keydown.up @keydown.enter @keydown.a/b/c.... 自定义键盘信息: Vue.directive('on').keyCode ...

  4. FireFox浏览器-xpath快速定位插件:Xpath Checker

    FireFox浏览器-xpath快速定位插件:Xpath Checker 插件截图:

  5. Bash算术运算

    使用let命令 let let let let let let let 使用expr命令 - ` # + ` # \* ` # / ` # / ` # − \* ` # +` # + -*· # -* ...

  6. Quartz.NET基础知识概述

    Quartz.NET是什么 由于我现在使用的Quartz.NET2.2版本,相对2.x变化不大,主要是相对于1.x更新了很多东西,如下基础知识摘录网络. Quartz.NET是一个开源的作业调度框架, ...

  7. list string 互转

    List转字符串,用逗号隔开 List<string> list = new List<string>();list.Add("a");list.Add(& ...

  8. [Java初探08]__简单学习Java类和对象

    前言 在前面的学习中,我们对面向对象的编程思想有了一个基本的了解,并且简单的了解了类和对象的定义.那么类和对象在Java语言中是如何表现的,这次,就从实际出发,学习一下一下类和对象在Java语言中的使 ...

  9. Python学习--12 异常处理、调试

    异常捕获 语法格式: try: pass except xxx as e: pass except xxx as e: pass ... else: pass finally: pass except ...

  10. 【详解】JNI (Java Native Interface) (三)

    案例三:C代码访问Java对象的实例变量   获取对象的实例变量的步骤: 1. 通过GetObjectClass()方法获得此对象的类引用 2. 通过类引用的GetFieldID()方法获得实例变量的 ...