目录
一、加密解密介绍
二、MD5
三、SHA-x系列
四、DES / 3DES
五、RC2
六、AES
七、Base64
八、Rsa
九、参考文献
不可逆加密:MD5、SHA-x系列
对称式加密:Des、3DES、RC2、AES、Base64
非对称加密:Rsa
介绍:
不可逆加密
本质是通过哈希计算,可以对普通的数据信息进行加密,也可以对文件生成文件的摘要。
规则:
不同长度的内容加密后加过都是 32 位
加密不可逆
原文差别很小,结果差别很大
主要用途:
1、用户密码加密
2、验证文件的完整性
3、极速秒传,扫描文件的MD5跟已有的文件MD5比对,吻合表示文件已存在不用再上传;
核心代码:
///
/// MD5加密 -- 不可逆
///
public class MD5Encrypt
{
///
/// 静态调用
///
public static MD5Encrypt MD5 { get { return new MD5Encrypt(); } }
#region 方法
///
/// MD5加密,和动网上的16/32位MD5加密结果相同
/// 使用的UTF8编码
///
/// 待加密字串
/// 16或32值之一,其它则采用.net默认MD5加密算法
/// 加密后的字串
internal string Encrypt(string source, int length = 32)//默认参数
{
if (string.IsNullOrEmpty(source)) return string.Empty;
HashAlgorithm provider = CryptoConfig.CreateFromName("MD5") as HashAlgorithm;
//转换成字节码
byte[] bytes = Encoding.UTF8.GetBytes(source);//这里需要区别编码的
//根据字节码转换成16个Hash码
byte[] hashValue = provider.ComputeHash(bytes);
//字符拼接
StringBuilder sb = new StringBuilder();
switch (length)
{
case 16://16位密文是32位密文的9到24位字符
for (int i = 4; i < 12; i++)
{
sb.Append(hashValue[i].ToString("x2"));
}
break;
case 32:
for (int i = 0; i < 16; i++)
{
sb.Append(hashValue[i].ToString("x2"));
}
break;
default:
for (int i = 0; i < hashValue.Length; i++)
{
sb.Append(hashValue[i].ToString("x2"));
}
break;
}
return sb.ToString();
}
///
/// 获取文件的MD5摘要
///
///
///
internal string AbstractFile(string fileName)
{
using (FileStream file = new FileStream(fileName, FileMode.Open))
{
return AbstractFile(file);
}
}
///
/// 根据stream获取文件摘要
///
/// 文件流
///
internal string AbstractFile(Stream stream)
{
MD5 md5 = new MD5CryptoServiceProvider();
//获取16个Hash码
byte[] retVal = md5.ComputeHash(stream);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < retVal.Length; i++)
{
sb.Append(retVal[i].ToString("x2"));
}
return sb.ToString();
}
#endregion
}
代码应用:
internal class Program
{
static void Main(string[] args)
{
string a = "111";
string result = MD5Encrypt.MD5.Encrypt(a);
Console.WriteLine(result); //结果显示:698d51a19d8a121ce581499d7b701668
string path_a = @"C:\Users\Rush\Desktop\C#\加密解码各种方法\a.txt";
string path_b = @"C:\Users\Rush\Desktop\C#\加密解码各种方法\b.txt";
string p_a = MD5Encrypt.MD5.AbstractFile(path_a);
Console.WriteLine(p_a); //结果显示:f9c2a9f852c31d2a8bb619033b4246f1
string p_b = MD5Encrypt.MD5.AbstractFile(path_b);
Console.WriteLine(p_b); //结果显示:f9c2a9f852c31d2a8bb619033b4246f1
}
}
介绍:
SHA-1(安全哈希算法,也称为安全哈希标准)是由美国政府发布的一种加密哈希算法。
可以根据任意长度的字符串生成160位的哈希值。HMACSHA1接受任何大小的密钥,并产生长度为160位的哈希序列。
比MD5安全性更高
主要用途:
数字签名、数字时间戳、数字证书
注:SHA-1 已经被破解,不推荐使用
核心代码:
///
/// SHA加密 -- 不可逆
///
public class SHAEncrypt
{
///
/// 静态方法
///
public static SHAEncrypt SHA { get { return new SHAEncrypt(); } }
#region 方法
///
/// SHA1加密
///
/// 待加密文本
/// 加密后的字符串。(40个字符)
public string SHA1Encrypt(string encryptText)
{
return SHAxEncrypt(new SHA1CryptoServiceProvider(), encryptText, true);
}
///
/// SHA1加密
///
/// 待加密文本
///
/// true -- 40个字符(默认)
/// false -- 28个字符
///
/// 加密后的字符串。(28个字符)
public string SHA1Encrypt(string encryptText, bool textLength)
{
return SHAxEncrypt(new SHA1CryptoServiceProvider(), encryptText, textLength);
}
///
/// SHA256加密
///
/// 待加密文本
/// 加密后的字符串。(64个字符)
public string SHA256Encrypt(string encryptText)
{
return SHAxEncrypt(new SHA256CryptoServiceProvider(), encryptText, true);
}
///
/// SHA256加密
///
/// 待加密文本
///
/// true -- 64个字符(默认)
/// false -- 44个字符
///
/// 加密后的字符串。(44个字符)
public string SHA256Encrypt(string encryptText, bool textLength)
{
return SHAxEncrypt(new SHA256CryptoServiceProvider(), encryptText, textLength);
}
///
/// SHA384加密
///
/// 待加密文本
/// 加密后的字符串。(96个字符)
public string SHA384Encrypt(string encryptText)
{
return SHAxEncrypt(new SHA384CryptoServiceProvider(), encryptText, true);
}
///
/// SHA384加密
///
/// 待加密文本
///
/// true -- 96个字符(默认)
/// false -- 64个字符
///
/// 加密后的字符串。(64个字符)
public string SHA384Encrypt(string encryptText, bool textLength)
{
return SHAxEncrypt(new SHA384CryptoServiceProvider(), encryptText, textLength);
}
///
/// SHA512加密
///
/// 待加密文本
/// 加密后的字符串。(96个字符)
public string SHA512Encrypt(string encryptText)
{
return SHAxEncrypt(new SHA512CryptoServiceProvider(), encryptText, true);
}
///
/// SHA512加密
///
/// 待加密文本
///
/// true -- 96个字符(默认)
/// false -- 88个字符
///
/// 加密后的字符串。(88个字符)
public string SHA512Encrypt(string encryptText, bool textLength)
{
return SHAxEncrypt(new SHA512CryptoServiceProvider(), encryptText, textLength);
}
///
/// SHA加密
///
/// 待加密文本
///
/// true -- 长字符
/// false -- 短字符
///
/// 加密后的字符
private string SHAxEncrypt(T t, string encryptText, bool textLength)
where T : HashAlgorithm, new()
{
T sha = new T();
if (textLength) //若长度固定
{
//获取字符
byte[] encryptedBytes = sha.ComputeHash(Encoding.ASCII.GetBytes(encryptText));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < encryptedBytes.Length; i++)
{
sb.AppendFormat("{0:x2}", encryptedBytes[i]);
}
return sb.ToString();
}
//若长度不固定
byte[] bytes = sha.ComputeHash(Encoding.ASCII.GetBytes(encryptText));
return Convert.ToBase64String(bytes);
}
#endregion
}
代码应用:
internal class Program
{
static void Main(string[] args)
{
string encryptText = "123";
Console.WriteLine(SHAEncrypt.SHA.SHA1Encrypt(encryptText));
//结果显示:40bd001563085fc35165329ea1ff5c5ecbdbbeef
Console.WriteLine(SHAEncrypt.SHA.SHA256Encrypt(encryptText));
//结果显示:a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3
Console.WriteLine(SHAEncrypt.SHA.SHA384Encrypt(encryptText));
//结果显示:9a0a82f0c0cf31470d7affede3406cc9aa8410671520b727044eda15b4c25532a9b5cd8aaf9cec4919d76255b6bfb00f
Console.WriteLine(SHAEncrypt.SHA.SHA512Encrypt(encryptText));
//结果显示:3c9909afec25354d551dae21590bb26e38d53f2173b8d3dc3eee4c047e7ab1c1eb8b85103e3be7ba613b31bb5c9c36214dc9f14a42fd7a2fdb84856bca5c44c2
Console.WriteLine(SHAEncrypt.SHA.SHA1Encrypt(encryptText,false));
//结果显示:QL0AFWMIX8NRZTKeof9cXsvbvu8=
Console.WriteLine(SHAEncrypt.SHA.SHA256Encrypt(encryptText,false));
//结果显示:pmWkWSBCL51Bfkhn79xPuKBKHz//H6B+mY6G9/eieuM=
Console.WriteLine(SHAEncrypt.SHA.SHA384Encrypt(encryptText, false));
//结果显示:mgqC8MDPMUcNev/t40BsyaqEEGcVILcnBE7aFbTCVTKptc2Kr5zsSRnXYlW2v7AP
Console.WriteLine(SHAEncrypt.SHA.SHA512Encrypt(encryptText, false));
//结果显示:PJkJr+wlNU1VHa4hWQuybjjVPyFzuNPcPu5MBH56scHri4UQPjvnumE7MbtcnDYhTcnxSkL9ei/bhIVrylxEwg==
}
}
DES介绍:
对称式加密
加密和解密均需要使用相同的密钥。
知道加密解密算法,无法推导出密钥的。
原文长,加密后,密文也长,原文短,加密后,密文也相对要短一些。
加密解密速度超快
容易泄露秘钥
DES是美国1977年公布的一种数据加密标准,该算法目前已经有多种破解方法,已被淘汰。
TripleDES介绍:
TripleDES算法(也叫3DES算法)是美国国家标准技术研究所(NIST)1999年提出的数据加密标准。
该算法是DES的一个变形,使用DES算法的3次连续迭代,支持128位和192位的密钥长度,其安全性比DES算法高。
主要用途:
互联网传输加密数据信息
Jwt鉴权授权
核心代码:
///
/// DES加密 -- 对称式
///
class DESEncrypt
{
///
/// 3DES 加密(基于DES,对一块数据用三个不同的密钥进行三次加密,强度更高)
///
/// 待加密密文
/// 密钥一
/// 密钥二
/// 密钥三
/// 加密后字符
public static string Encrypt(string encryptText, string encryptKey1, string encryptKey2, string encryptKey3)
{
string m_strEncrypt;
try
{
m_strEncrypt = Encrypt(encryptText, encryptKey3);
m_strEncrypt = Encrypt(m_strEncrypt, encryptKey2);
m_strEncrypt = Encrypt(m_strEncrypt, encryptKey1);
}
catch (Exception ex) { throw ex; }
return m_strEncrypt;
}
///
/// 3DES 解密(基于DES,对一块数据用三个不同的密钥进行三次加密,强度更高)
///
/// 待解密密文
/// 密钥一
/// 密钥二
/// 密钥三
/// 解密后字符
public static string Decrypt(string decryptText, string decryptKey1, string decryptKey2, string decryptKey3)
{
string m_strDecrypt = "";
try
{
m_strDecrypt = Decrypt(decryptText, decryptKey1);
m_strDecrypt = Decrypt(m_strDecrypt, decryptKey2);
m_strDecrypt = Decrypt(m_strDecrypt, decryptKey3);
}
catch (Exception ex) { throw ex; }
return m_strDecrypt;
}
///
/// DES 加密(数据加密标准,速度较快,适用于加密大量数据的场合)
///
/// 待加密的密文
/// 加密的密钥
/// 加密的字符
public static string Encrypt(string encryptText, string encryptKey)
{
if (string.IsNullOrEmpty(encryptText)) { throw (new Exception("密文不得为空")); }
if (string.IsNullOrEmpty(encryptKey)) { throw (new Exception("密钥不得为空")); }
if (encryptKey.Length != 8) { throw (new Exception("密钥必须为8位")); }
byte[] m_btIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
string m_strEncrypt = "";
DESCryptoServiceProvider m_DESProvider = new DESCryptoServiceProvider();
try
{
byte[] m_btEncryptString = Encoding.Default.GetBytes(encryptText);
MemoryStream m_stream = new MemoryStream();
CryptoStream m_cstream = new CryptoStream(m_stream, m_DESProvider.CreateEncryptor(Encoding.Default.GetBytes(encryptKey), m_btIV), CryptoStreamMode.Write);
m_cstream.Write(m_btEncryptString, 0, m_btEncryptString.Length);
m_cstream.FlushFinalBlock();
m_strEncrypt = Convert.ToBase64String(m_stream.ToArray());
m_stream.Close(); m_stream.Dispose();
m_cstream.Close(); m_cstream.Dispose();
}
catch (IOException ex) { throw ex; }
catch (CryptographicException ex) { throw ex; }
catch (ArgumentException ex) { throw ex; }
catch (Exception ex) { throw ex; }
finally { m_DESProvider.Clear(); }
return m_strEncrypt;
}
///
/// DES 解密(数据加密标准,速度较快,适用于加密大量数据的场合)
///
/// 待解密的密文
/// 解密的密钥
/// 解密的字符
public static string Decrypt(string decryptText, string decryptKey)
{
if (string.IsNullOrEmpty(decryptText)) { throw (new Exception("密文不得为空")); }
if (string.IsNullOrEmpty(decryptKey)) { throw (new Exception("密钥不得为空")); }
if (decryptKey.Length != 8) { throw (new Exception("密钥必须为8位")); }
byte[] m_btIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
string m_strDecrypt = "";
DESCryptoServiceProvider m_DESProvider = new DESCryptoServiceProvider();
try
{
byte[] m_btDecryptString = Convert.FromBase64String(decryptText);
MemoryStream m_stream = new MemoryStream();
CryptoStream m_cstream = new CryptoStream(m_stream, m_DESProvider.CreateDecryptor(Encoding.Default.GetBytes(decryptKey), m_btIV), CryptoStreamMode.Write);
m_cstream.Write(m_btDecryptString, 0, m_btDecryptString.Length);
m_cstream.FlushFinalBlock();
m_strDecrypt = Encoding.Default.GetString(m_stream.ToArray());
m_stream.Close(); m_stream.Dispose();
m_cstream.Close(); m_cstream.Dispose();
}
catch (IOException ex) { throw ex; }
catch (CryptographicException ex) { throw ex; }
catch (ArgumentException ex) { throw ex; }
catch (Exception ex) { throw ex; }
finally { m_DESProvider.Clear(); }
return m_strDecrypt;
}
}
代码应用:
internal class program
{
static void Main(string[] args)
{
string key_1 = "aaaaaaaa";
string key_2 = "bbbbbbbb";
string key_3 = "cccccccc";
string content = "张三";
string encryptResult = DESEncrypt.Encrypt(content, key_1, key_2, key_3);
Console.WriteLine(encryptResult); //结果显示: zQ71DHlFz6KqqKsg1J9jBYc+VRalcY48wXAGVGwNnhY=
string decryptResult = DESEncrypt.Decrypt(encryptResult, key_1, key_2, key_3);
Console.WriteLine(decryptResult); //结果显示: 张三
}
}
介绍:
RC2算法是Ron Rivest在1987年设计的一个块密码算法。该算法密钥长度为从40位~128位,以8位递增。
可替代DES算法
核心代码:
///
/// RC2加密 -- 对称式
///
class RC2Encrypt
{
///
/// RC2 加密(用变长密钥对大量数据进行加密)
///
/// 待加密密文
/// 加密密钥
/// 加密后字符
public static string Encrypt(string encryptText, string encryptKey)
{
if (string.IsNullOrEmpty(encryptText)) { throw (new Exception("密文不得为空")); }
if (string.IsNullOrEmpty(encryptKey)) { throw (new Exception("密钥不得为空")); }
if (encryptKey.Length < 5 || encryptKey.Length > 16) { throw (new Exception("密钥必须为5-16位")); }
string m_strEncrypt = "";
byte[] m_btIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
RC2CryptoServiceProvider m_RC2Provider = new RC2CryptoServiceProvider();
try
{
byte[] m_btEncryptString = Encoding.Default.GetBytes(encryptText);
MemoryStream m_stream = new MemoryStream();
CryptoStream m_cstream = new CryptoStream(m_stream, m_RC2Provider.CreateEncryptor(Encoding.Default.GetBytes(encryptKey), m_btIV), CryptoStreamMode.Write);
m_cstream.Write(m_btEncryptString, 0, m_btEncryptString.Length);
m_cstream.FlushFinalBlock();
m_strEncrypt = Convert.ToBase64String(m_stream.ToArray());
m_stream.Close(); m_stream.Dispose();
m_cstream.Close(); m_cstream.Dispose();
}
catch (IOException ex) { throw ex; }
catch (CryptographicException ex) { throw ex; }
catch (ArgumentException ex) { throw ex; }
catch (Exception ex) { throw ex; }
finally { m_RC2Provider.Clear(); }
return m_strEncrypt;
}
///
/// RC2 解密(用变长密钥对大量数据进行加密)
///
/// 待解密密文
/// 解密密钥
/// 解密后字符
public static string Decrypt(string decryptText, string decryptKey)
{
if (string.IsNullOrEmpty(decryptText)) { throw (new Exception("密文不得为空")); }
if (string.IsNullOrEmpty(decryptKey)) { throw (new Exception("密钥不得为空")); }
if (decryptKey.Length < 5 || decryptKey.Length > 16) { throw (new Exception("密钥必须为5-16位")); }
byte[] m_btIV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
string m_strDecrypt = "";
RC2CryptoServiceProvider m_RC2Provider = new RC2CryptoServiceProvider();
try
{
byte[] m_btDecryptString = Convert.FromBase64String(decryptText);
MemoryStream m_stream = new MemoryStream();
CryptoStream m_cstream = new CryptoStream(m_stream, m_RC2Provider.CreateDecryptor(Encoding.Default.GetBytes(decryptKey), m_btIV), CryptoStreamMode.Write);
m_cstream.Write(m_btDecryptString, 0, m_btDecryptString.Length);
m_cstream.FlushFinalBlock();
m_strDecrypt = Encoding.Default.GetString(m_stream.ToArray());
m_stream.Close(); m_stream.Dispose();
m_cstream.Close(); m_cstream.Dispose();
}
catch (IOException ex) { throw ex; }
catch (CryptographicException ex) { throw ex; }
catch (ArgumentException ex) { throw ex; }
catch (Exception ex) { throw ex; }
finally { m_RC2Provider.Clear(); }
return m_strDecrypt;
}
}
代码应用:
internal class Program
{
static void Main(string[] args)
{
string encryptText = "王五";
string encryptKey = "123456";
//加密结果
string encryptResult = RC2Encrypt.Encrypt(encryptText, encryptKey);
Console.WriteLine(encryptResult); //结果显示:a9chqCkYg88=
Console.WriteLine(RC2Encrypt.Decrypt(encryptResult, encryptKey));//结果显示:王五
}
}
介绍:
1997年美国国家标准技术协会(NIST)开始向全世界公开征集新的高级加密标准(Advanced Encryption Standard,AES)
Rijndael算法是由Vincent Rijmen和Joan Daemen两人提出的加密算法。
该算法作为新一代的数据加密标准,汇聚了强安全性、高性能、高效率、易用和灵活等优点。
算法支持128位(16个字节)、192位(24个字节)和256位(32个字节)的密钥长度,与DES算法相比,Rijndael的128位密钥比DES的56位密钥强1021倍。
由于Rijndael加密算法是AES选中的唯一算法,因此将其简称为AES算法。
核心代码:
///
/// AES加密 -- 对称式
///
class AESEncrypt
{
///
/// AES 加密(高级加密标准,是下一代的加密算法标准,速度快,安全级别高,目前 AES 标准的一个实现是 Rijndael 算法)
///
/// 待加密密文
/// 加密密钥
/// 加密的字符串
public static string Encrypt(string encryptText, string encryptKey)
{
if (string.IsNullOrEmpty(encryptText)) { throw (new Exception("密文不得为空")); }
if (string.IsNullOrEmpty(encryptKey)) { throw (new Exception("密钥不得为空")); }
if (!encryptKey.Length.Equals(32)) throw new Exception("密钥必须32位");
string m_strEncrypt = "";
byte[] m_btIV = Convert.FromBase64String("Rkb4jvUy/ye7Cd7k89QQgQ==");
Rijndael m_AESProvider = Rijndael.Create();
try
{
byte[] m_btEncryptString = Encoding.Default.GetBytes(encryptText);
MemoryStream m_stream = new MemoryStream();
CryptoStream m_csstream = new CryptoStream(m_stream, m_AESProvider.CreateEncryptor(Encoding.Default.GetBytes(encryptKey), m_btIV), CryptoStreamMode.Write);
m_csstream.Write(m_btEncryptString, 0, m_btEncryptString.Length); m_csstream.FlushFinalBlock();
m_strEncrypt = Convert.ToBase64String(m_stream.ToArray());
m_stream.Close(); m_stream.Dispose();
m_csstream.Close(); m_csstream.Dispose();
}
catch (IOException ex) { throw ex; }
catch (CryptographicException ex) { throw ex; }
catch (ArgumentException ex) { throw ex; }
catch (Exception ex) { throw ex; }
finally { m_AESProvider.Clear(); }
return m_strEncrypt;
}
///
/// AES 解密(高级加密标准,是下一代的加密算法标准,速度快,安全级别高,目前 AES 标准的一个实现是 Rijndael 算法)
///
/// 待解密密文
/// 解密密钥
/// 解密的字符
public static string Decrypt(string decryptText, string decryptKey)
{
if (string.IsNullOrEmpty(decryptText)) { throw (new Exception("密文不得为空")); }
if (string.IsNullOrEmpty(decryptKey)) { throw (new Exception("密钥不得为空")); }
if (!decryptKey.Length.Equals(32)) throw new Exception("密钥必须32位");
string m_strDecrypt = "";
byte[] m_btIV = Convert.FromBase64String("Rkb4jvUy/ye7Cd7k89QQgQ==");
Rijndael m_AESProvider = Rijndael.Create();
try
{
byte[] m_btDecryptString = Convert.FromBase64String(decryptText);
MemoryStream m_stream = new MemoryStream();
CryptoStream m_csstream = new CryptoStream(m_stream, m_AESProvider.CreateDecryptor(Encoding.Default.GetBytes(decryptKey), m_btIV), CryptoStreamMode.Write);
m_csstream.Write(m_btDecryptString, 0, m_btDecryptString.Length); m_csstream.FlushFinalBlock();
m_strDecrypt = Encoding.Default.GetString(m_stream.ToArray());
m_stream.Close(); m_stream.Dispose();
m_csstream.Close(); m_csstream.Dispose();
}
catch (IOException ex) { throw ex; }
catch (CryptographicException ex) { throw ex; }
catch (ArgumentException ex) { throw ex; }
catch (Exception ex) { throw ex; }
finally { m_AESProvider.Clear(); }
return m_strDecrypt;
}
}
代码应用:
internal class program
{
static void Main(string[] args)
{
string key = "ae125efkk4_54eeff444ferfkny6ox22";
string encryptText = "张三";
string encryptResult = AESEncrypt.Encrypt(encryptText, key);
Console.WriteLine(encryptResult); //结果显示: FiGP6FUqA05SZ0/D2cO0UA==
string decryptResult = AESEncrypt.Decrypt(encryptResult, key);
Console.WriteLine(decryptResult); //结果显示: 张三
}
}
核心代码:
///
/// Base64加密 -- 对称式
///
class Base64Encrypt
{
///
/// Base64加密,采用utf8编码方式加密
///
/// 待加密的明文
/// 加密的字符串
public static string Encrypt(string encryptText)
{
return Encrypt(Encoding.UTF8, encryptText);
}
///
/// Base64加密
///
/// 加密采用的编码方式
/// 待加密的明文
/// 加密的字符串
private static string Encrypt(Encoding encodeType, string encryptText)
{
string encode = string.Empty;
byte[] bytes = encodeType.GetBytes(encryptText);
try
{
encode = Convert.ToBase64String(bytes);
}
catch
{
encode = encryptText;
}
return encode;
}
///
/// Base64解密,采用utf8编码方式解密
///
/// 待解密的密文
/// 解密的字符串
public static string Decrypt(string decryptText)
{
return Decrypt(Encoding.UTF8, decryptText);
}
///
/// Base64解密
///
/// 解密采用的编码方式,注意和加密时采用的方式一致
/// 待解密的密文
/// 解密的字符串
private static string Decrypt(Encoding encodeType, string decryptText)
{
string decode = string.Empty;
byte[] bytes = Convert.FromBase64String(decryptText);
try
{
decode = encodeType.GetString(bytes);
}
catch
{
decode = decryptText;
}
return decode;
}
}
代码应用:
internal class program
{
static void Main(string[] args)
{
string encryptText = "张三";
string encryptResult = Base64Encrypt.Encrypt(encryptText);
Console.WriteLine(encryptResult); //结果显示: 5byg5LiJ
string DecryptResult = Base64Encrypt.Decrypt(encryptResult);
Console.WriteLine(DecryptResult); //结果显示: 张三
}
}
介绍:
非对称可逆加密
一组加密解密Key,这组Key是成套的,且两个Key不一样
两个Key可相互解码
原文短,加密后,密文长
加密速度相对要慢
安全性超强
主要用途:
数据的安全传输
直接支持的加密解密api,可以进行签名
签名:实际在数字签名的时候,是需要私有key加密,公有key解密
核心代码:
///
/// 密钥类
///
public class KeyModel
{
///
/// 公有Key---加密key
///
public string PublicKey { get; set; }
///
/// 私有Key--可以加密也可以加密
///
public string PrivateKey { get; set; }
///
/// 构造函数
///
/// 共有key
/// 私有key
public KeyModel(string publicKey, string privateKey)
{
this.PublicKey = publicKey;
this.PrivateKey = privateKey;
}
}
///
/// Rsa加密 -- 非对称式
///
public class RsaEncrypt
{
///
/// 获取公钥/私钥
/// 每次生成的公钥和私钥都不一样
///
/// Encrypt Decrypt
public static KeyModel GetKeyPair()
{
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
//包括专用参数: 如果为true,则包含公钥和私钥RSA密钥;false,仅包括公众钥匙
string publicKey = RSA.ToXmlString(false); //生成的是公开的解密key
string privateKey = RSA.ToXmlString(true); //生成的是私有的既可以加密也可以解密的key
return new KeyModel(publicKey, privateKey);
}
///
/// RSA加密
///
/// 待加密文本
/// 加密key
/// 加密后字符
public static string Encrypt(string encryptText, string encryptKey)
{
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(encryptKey);
UnicodeEncoding ByteConverter = new UnicodeEncoding();
//内容转成Unicode编码
byte[] DataToEncrypt = ByteConverter.GetBytes(encryptText);
//生成Rsa码
byte[] resultBytes = rsa.Encrypt(DataToEncrypt, false);
//字节转字符串
return Convert.ToBase64String(resultBytes);
}
///
/// RSA解密
///
/// 待解密文本
/// 解密key
/// 解密后字符
public static string Decrypt(string decryptText, string decryptKey)
{
//字符转字节
byte[] dataToDecrypt = Convert.FromBase64String(decryptText);
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSA.FromXmlString(decryptKey);
//解码
byte[] resultBytes = RSA.Decrypt(dataToDecrypt, false);
UnicodeEncoding ByteConverter = new UnicodeEncoding();
//根据Unicode转化成字符串
return ByteConverter.GetString(resultBytes);
}
///
/// 生成签名
///
/// 原文
/// 私钥
/// 加密后字符
public static string SignData(string content, string privatekey)
{
//字符转字节
byte[] messagebytes = Encoding.UTF8.GetBytes(content);
RSACryptoServiceProvider oRSA3 = new RSACryptoServiceProvider();
oRSA3.FromXmlString(privatekey);
//生成签名
byte[] AOutput = oRSA3.SignData(messagebytes, "SHA1");
//字节转字符
return Convert.ToBase64String(AOutput);
}
///
/// 验证签名
///
/// 原文
/// 签名
/// 共有key
///
/// true -- 验证成功
/// false -- 验证失败
///
public static bool VerifyData(string content, string autograph, string publickey)
{
//字符转字节
byte[] messagebytes = Encoding.UTF8.GetBytes(content);
byte[] messageAutographbytes = Convert.FromBase64String(autograph);
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSA.FromXmlString(publickey);
//验证 content 和 autograph 是否相同
bool bVerify = RSA.VerifyData(messagebytes, "SHA1", messageAutographbytes);
return bVerify;
}
///
/// 生成公钥私钥,同时完成加密
///
///
/// 加密key
/// 解密key
/// 加密后结果
private static string Encrypt(string content, out string publicKey, out string privateKey)
{
RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider();
publicKey = rsaProvider.ToXmlString(false);
privateKey = rsaProvider.ToXmlString(true);
UnicodeEncoding ByteConverter = new UnicodeEncoding();
byte[] DataToEncrypt = ByteConverter.GetBytes(content);
byte[] resultBytes = rsaProvider.Encrypt(DataToEncrypt, false);
return Convert.ToBase64String(resultBytes);
}
}
代码应用:
internal class Program
{
static void Main(string[] args)
{
//!!!结果显示太长,请自行运行!!!
//获取公钥和私钥,每次生成的都不一样
KeyModel encryptDecrypt = RsaEncrypt.GetKeyPair();
Console.WriteLine($"私钥:\n{encryptDecrypt.PrivateKey}");
Console.WriteLine($"公钥:\n{encryptDecrypt.PublicKey}");
//------------------------------私钥--------------------------------------
//加密 -- 私钥能加密的原因是私钥包含公钥
string encryptResultPrivate = RsaEncrypt.Encrypt("张三", encryptDecrypt.PrivateKey);
Console.WriteLine($"密文:\n{encryptResultPrivate}");
//解密
Console.WriteLine($"解密:{RsaEncrypt.Decrypt(encryptResultPrivate, encryptDecrypt.PrivateKey)}");
//------------------------------公钥--------------------------------------
//加密
string encryptResultPublic = RsaEncrypt.Encrypt("张三", encryptDecrypt.PublicKey);
Console.WriteLine($"密文:\n{encryptResultPublic}");
//解密
Console.WriteLine($"解密:{RsaEncrypt.Decrypt(encryptResultPublic, encryptDecrypt.PrivateKey)}");
//------------------------------签名--------------------------------------
//生成签名
Console.WriteLine($"生成签名");
string autograph = RsaEncrypt.SignData("生成签名的原文", encryptDecrypt.PrivateKey);
Console.WriteLine($"签名:{autograph}");
//验证签名
Console.WriteLine($"验证签名:{RsaEncrypt.VerifyData("生成签名的原文", autograph, encryptDecrypt.PublicKey)}");
Console.WriteLine($"验证签名原文改动:{RsaEncrypt.VerifyData("生成签名的原文改动", autograph, encryptDecrypt.PublicKey)}");
}
}
http://t.csdn.cn/jmfGa
http://t.csdn.cn/eotMH
如有错误,烦请批评指正