本文转载自Smallbyte
:https://www.cnblogs.com/zhanqun/p/4432304.html
加密解密算法目前已经应用到我们生活中的各个方面
加密用于达到以下目的:
-
保密性:帮助保护用户的标识或数据不被读取。
-
数据完整性:帮助保护数据不被更改。
-
身份验证:确保数据发自特定的一方。
-
不可否认性:防止特定的一方否认发送过消息。
为了达到这些目的,我们可以使用以下做法:
| 私钥加密(对称加密) | 对数据执行转换,使第三方无法读取该数据。 此类型的加密使用单个共享的机密密钥来加密和解密数据。 |
| 公钥加密(不对称加密) | 对数据执行转换,使第三方无法读取该数据。 此类加密使用公钥/私钥对来加密和解密数据。 |
| 加密签名 | 通过创建对特定方唯一的数字签名来帮助验证数据是否发自特定方。 此过程还使用哈希函数。 |
| 加密哈希 | 将数据从任意长度映射为定长字节序列。 哈希在统计上是唯一的;不同的双字节序列不会哈希为同一个值。 |
.NET Framework 提供了以下类来实现私钥加密算法:
-
AesManaged (在 .NET Framework 3.5中引入)。
-
HMACSHA1 (从技术上讲,这是一种私钥算法,因为它表示结合使用加密哈希函数和私钥计算的消息身份验证代码。 请参见本主题后面的哈希值。)
.NET Framework 提供了以下类来实现公钥加密算法:
-
ECDiffieHellman (基类)
.NET Framework 提供了以下类来实现数字签名算法:
.NET Framework 提供的以下类实现了哈希算法:
-
HMACSHA1 .
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 = 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];
}
}
}
}
本文深入讲解了加密解密算法在日常生活中的广泛应用,包括保密性、数据完整性和身份验证等核心功能。介绍了私钥加密(对称加密)、公钥加密(不对称加密)、加密签名和加密哈希的基本原理,并详细列举了.NET Framework提供的多种加密类库。


158

被折叠的 条评论
为什么被折叠?



