常见加密解密(DES、RSA)以及摘要算法MD5的介绍
一、MD5不可逆加密
1.1-理解MD5
- MD5公开的算法,任何语言实现后其实都是一样的、通用的
- 不可逆加密:原文——加密——密文,密文无法解密出原文
1.2-MD5封装
using System.IO;
using System.Security.Cryptography;
/// <summary>
/// 不可逆加密
/// 1 防止被篡改
/// 2 防止明文存储
/// 3 防止抵赖,数字签名
/// </summary>
public class MD5Encrypt
{
#region MD5
/// <summary>
/// MD5加密,和动网上的16/32位MD5加密结果相同,
/// 使用的UTF8编码
/// </summary>
/// <param name="source">待加密字串</param>
/// <param name="length">16或32值之一,其它则采用.net默认MD5加密算法</param>
/// <returns>加密后的字串</returns>
public static 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);//这里需要区别编码的
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();
}
#endregion MD5
#region MD5摘要
/// <summary>
/// 获取文件的MD5摘要
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public static string AbstractFile(string fileName)
{
using (FileStream file = new FileStream(fileName, FileMode.Open))
{
return AbstractFile(file);
}
}
/// <summary>
/// 根据stream获取文件摘要
/// </summary>
/// <param name="stream"></param>
/// <returns></returns>
public static string AbstractFile(Stream stream)
{
MD5 md5 = new MD5CryptoServiceProvider();
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
}
1.3-MD5总结
- 相同原文加密的结果是一样的
- 不同长度的内容加密后都是32位,可以自行改变长度
- 原文件改动差别很小,结果差别很大
- 不管文件多大,都能产生32位长度的【摘要】,就是更具文件流进行加密的结果
- 文件内容有一点改动,结果变化非常大
- 文件内容不变,文件名变了,结果是不变的
1.4-MD5用途?
- 防篡改
- 源代码管理器
- 急速秒传
- 在本地进行MD5摘要,到服务器上去检查,如果存在就不需要上传,直接在服务器上复制一份,或者指向路径跳转一下。
- 密码保存:防止看到明文
- 密文是可见的,所以要求密码不能太检查;加盐(特殊字符+字母+数字)
- MD5是无法全部穷举出来的,无法全部解密出来的,像网上有很多这种;
- 防止抵赖,数字签名
- 吧一些内容摘要一下,不能抵赖。
二、对称可逆加密DES
2.1-理解DES
- 对称可逆加密是公开的算法,任何语言实现后其实都一样,通用的。
- 加密后能解密会原文,但是需要一个Key
- 加密key和加密Key是同一个,也就是开门和锁门都要用同一吧钥匙
- 优点:加密解密的速度快
- 缺点:问题是秘钥的安全(key在网络中传输呗窃取),不是很安全
理解什么是对称可逆加密:
- 对称:加密/解密是key要一模一样的
- 可逆:原文加密到密文,密文解密到原文
2.2-DES封装
/// <summary>
/// Des加密
/// </summary>
public class DesCrypto
{
//密钥
private const string sKey = "qJzGEh6hESZDVJeCnFPGuxzaiB7NLQM3";
//矢量,矢量可以为空
private const string sIV = "qcDY6X+aPLw=";
//构造一个对称算法
private SymmetricAlgorithm mCSP = new TripleDESCryptoServiceProvider();
/// <summary>
/// 构造函数
/// </summary>
public DesCrypto() {
}
#region public string EncryptString(string Value)
/// <summary>
/// 加密字符串
/// </summary>
/// <param name="Value">输入的字符串</param>
/// <returns>加密后的字符串</returns>
public string EncryptString(string Value)
{
ICryptoTransform ct;
MemoryStream ms;
CryptoStream cs;
byte[] byt;
mCSP.Key = Convert.FromBase64String(sKey);
mCSP.IV = Convert.FromBase64String(sIV);
//指定加密的运算模式
mCSP.Mode = System.Security.Cryptography.CipherMode.ECB;
//获取或设置加密算法的填充模式
mCSP.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
ct = mCSP.CreateEncryptor(mCSP.Key, mCSP.IV);
byt = Encoding.UTF8.GetBytes(Value);
ms = new MemoryStream();
cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
cs.Write(byt, 0, byt.Length);
cs.FlushFinalBlock();
cs.Close();
return Convert.ToBase64String(ms.ToArray());
}
#endregion
#region public string DecryptString(string Value)
/// <summary>
/// 解密字符串
/// </summary>
/// <param name="Value">加过密的字符串</param>
/// <returns>解密后的字符串</returns>
public string DecryptString(string Value)
{
ICryptoTransform ct;
MemoryStream ms;
CryptoStream cs;
byte[] byt;
mCSP.Key = Convert.FromBase64String(sKey);
mCSP.IV = Convert.FromBase64String(sIV);
mCSP.Mode = System.Security.Cryptography.CipherMode.ECB;
mCSP.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
ct = mCSP.CreateDecryptor(mCSP.Key, mCSP.IV);
byt = Convert.FromBase64String(Value);
ms = new MemoryStream();
cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
cs.Write(byt, 0, byt.Length);
cs.FlushFinalBlock();
cs.Close();
return Encoding.UTF8.GetString(ms.ToArray());
}
#endregion
}
三、非对称可逆加密RSA
2.1-理解RSA
- 非对称可逆加密公开的算法,任何语言实现后其实都一样,通用的;
- 加密key和解密key不是一个,而是一对
- 加密key和解密key不能相互推到,有密文,没有解密key,也推导不出原文
- 缺点:速度不快
- 优点:安全性好
2.2-RSA封装
/// <summary>
/// RSA加密解密及RSA签名和验证
/// </summary>
public class RsaEncrypt
{
public RsaEncrypt()
{
}
#region RSA 的密钥产生
/// <summary>
/// RSA 的密钥产生 产生私钥 和公钥
/// </summary>
/// <param name="xmlKeys"></param>
/// <param name="xmlPublicKey"></param>
public void RSAKey(out string xmlKeys, out string xmlPublicKey)
{
System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
xmlKeys = rsa.ToXmlString(true);
xmlPublicKey = rsa.ToXmlString(false);
}
#endregion
#region RSA的加密函数
//##############################################################################
//RSA 方式加密
//说明KEY必须是XML的行式,返回的是字符串
//在有一点需要说明!!该加密方式有 长度 限制的!!
//##############################################################################
//RSA的加密函数 string
public string RSAEncrypt(string xmlPublicKey, string m_strEncryptString)
{
byte[] PlainTextBArray;
byte[] CypherTextBArray;
string Result;
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(xmlPublicKey);
PlainTextBArray = (new UnicodeEncoding()).GetBytes(m_strEncryptString);
CypherTextBArray = rsa.Encrypt(PlainTextBArray, false);
Result = Convert.ToBase64String(CypherTextBArray);
return Result;
}
//RSA的加密函数 byte[]
public string RSAEncrypt(string xmlPublicKey, byte[] EncryptString)
{
byte[] CypherTextBArray;
string Result;
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(xmlPublicKey);
CypherTextBArray = rsa.Encrypt(EncryptString, false);
Result = Convert.ToBase64String(CypherTextBArray);
return Result;
}
#endregion
#region RSA的解密函数
//RSA的解密函数 string
public string RSADecrypt(string xmlPrivateKey, string m_strDecryptString)
{
byte[] PlainTextBArray;
byte[] DypherTextBArray;
string Result;
System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(xmlPrivateKey);
PlainTextBArray = Convert.FromBase64String(m_strDecryptString);
DypherTextBArray = rsa.Decrypt(PlainTextBArray, false);
Result = (new UnicodeEncoding()).GetString(DypherTextBArray);
return Result;
}
//RSA的解密函数 byte
public string RSADecrypt(string xmlPrivateKey, byte[] DecryptString)
{
byte[] DypherTextBArray;
string Result;
System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(xmlPrivateKey);
DypherTextBArray = rsa.Decrypt(DecryptString, false);
Result = (new UnicodeEncoding()).GetString(DypherTextBArray);
return Result;
}
#endregion
#region RSA数字签名
#region 获取Hash描述表
//获取Hash描述表 ,outofmemory.cn
public bool GetHash(string m_strSource, ref byte[] HashData)
{
//从字符串中取得Hash描述
byte[] Buffer;
System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");
Buffer = System.Text.Encoding.GetEncoding("GB2312").GetBytes(m_strSource);
HashData = MD5.ComputeHash(Buffer);
return true;
}
//获取Hash描述表
public bool GetHash(string m_strSource, ref string strHashData)
{
//从字符串中取得Hash描述
byte[] Buffer;
byte[] HashData;
System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");
Buffer = System.Text.Encoding.GetEncoding("GB2312").GetBytes(m_strSource);
HashData = MD5.ComputeHash(Buffer);
strHashData = Convert.ToBase64String(HashData);
return true;
}
//获取Hash描述表
public bool GetHash(System.IO.FileStream objFile, ref byte[] HashData)
{
//从文件中取得Hash描述
System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");
HashData = MD5.ComputeHash(objFile);
objFile.Close();
return true;
}
//获取Hash描述表
public bool GetHash(System.IO.FileStream objFile, ref string strHashData)
{
//从文件中取得Hash描述
byte[] HashData;
System.Security.Cryptography.HashAlgorithm MD5 = System.Security.Cryptography.HashAlgorithm.Create("MD5");
HashData = MD5.ComputeHash(objFile);
objFile.Close();
strHashData = Convert.ToBase64String(HashData);
return true;
}
#endregion
#region RSA签名
//RSA签名
public bool SignatureFormatter(string p_strKeyPrivate, byte[] HashbyteSignature, ref byte[] EncryptedSignatureData)
{
System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
RSA.FromXmlString(p_strKeyPrivate);
System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
//设置签名的算法为MD5
RSAFormatter.SetHashAlgorithm("MD5");
//执行签名
EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);
return true;
}
//RSA签名
public bool SignatureFormatter(string p_strKeyPrivate, byte[] HashbyteSignature, ref string m_strEncryptedSignatureData)
{
byte[] EncryptedSignatureData;
System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
RSA.FromXmlString(p_strKeyPrivate);
System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
//设置签名的算法为MD5
RSAFormatter.SetHashAlgorithm("MD5");
//执行签名
EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);
m_strEncryptedSignatureData = Convert.ToBase64String(EncryptedSignatureData);
return true;
}
//RSA签名
public bool SignatureFormatter(string p_strKeyPrivate, string m_strHashbyteSignature, ref byte[] EncryptedSignatureData)
{
byte[] HashbyteSignature;
HashbyteSignature = Convert.FromBase64String(m_strHashbyteSignature);
System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
RSA.FromXmlString(p_strKeyPrivate);
System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
//设置签名的算法为MD5
RSAFormatter.SetHashAlgorithm("MD5");
//执行签名
EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);
return true;
}
//RSA签名
public bool SignatureFormatter(string p_strKeyPrivate, string m_strHashbyteSignature, ref string m_strEncryptedSignatureData)
{
byte[] HashbyteSignature;
byte[] EncryptedSignatureData;
HashbyteSignature = Convert.FromBase64String(m_strHashbyteSignature);
System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
RSA.FromXmlString(p_strKeyPrivate);
System.Security.Cryptography.RSAPKCS1SignatureFormatter RSAFormatter = new System.Security.Cryptography.RSAPKCS1SignatureFormatter(RSA);
//设置签名的算法为MD5
RSAFormatter.SetHashAlgorithm("MD5");
//执行签名
EncryptedSignatureData = RSAFormatter.CreateSignature(HashbyteSignature);
m_strEncryptedSignatureData = Convert.ToBase64String(EncryptedSignatureData);
return true;
}
#endregion
#region RSA 签名验证
public bool SignatureDeformatter(string p_strKeyPublic, byte[] HashbyteDeformatter, byte[] DeformatterData)
{
System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
RSA.FromXmlString(p_strKeyPublic);
System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
//指定解密的时候HASH算法为MD5
RSADeformatter.SetHashAlgorithm("MD5");
if (RSADeformatter.VerifySignature(HashbyteDeformatter, DeformatterData))
{
return true;
}
else
{
return false;
}
}
public bool SignatureDeformatter(string p_strKeyPublic, string p_strHashbyteDeformatter, byte[] DeformatterData)
{
byte[] HashbyteDeformatter;
HashbyteDeformatter = Convert.FromBase64String(p_strHashbyteDeformatter);
System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
RSA.FromXmlString(p_strKeyPublic);
System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
//指定解密的时候HASH算法为MD5
RSADeformatter.SetHashAlgorithm("MD5");
if (RSADeformatter.VerifySignature(HashbyteDeformatter, DeformatterData))
{
return true;
}
else
{
return false;
}
}
public bool SignatureDeformatter(string p_strKeyPublic, byte[] HashbyteDeformatter, string p_strDeformatterData)
{
byte[] DeformatterData;
System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
RSA.FromXmlString(p_strKeyPublic);
System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
//指定解密的时候HASH算法为MD5
RSADeformatter.SetHashAlgorithm("MD5");
DeformatterData = Convert.FromBase64String(p_strDeformatterData);
if (RSADeformatter.VerifySignature(HashbyteDeformatter, DeformatterData))
{
return true;
}
else
{
return false;
}
}
public bool SignatureDeformatter(string p_strKeyPublic, string p_strHashbyteDeformatter, string p_strDeformatterData)
{
byte[] DeformatterData;
byte[] HashbyteDeformatter;
HashbyteDeformatter = Convert.FromBase64String(p_strHashbyteDeformatter);
System.Security.Cryptography.RSACryptoServiceProvider RSA = new System.Security.Cryptography.RSACryptoServiceProvider();
RSA.FromXmlString(p_strKeyPublic);
System.Security.Cryptography.RSAPKCS1SignatureDeformatter RSADeformatter = new System.Security.Cryptography.RSAPKCS1SignatureDeformatter(RSA);
//指定解密的时候HASH算法为MD5
RSADeformatter.SetHashAlgorithm("MD5");
DeformatterData = Convert.FromBase64String(p_strDeformatterData);
if (RSADeformatter.VerifySignature(HashbyteDeformatter, DeformatterData))
{
return true;
}
else
{
return false;
}
}
#endregion
#endregion
}
2.3-公钥/私钥
- 公钥:公开的Key
- 私钥:不公开的Key
- 公开加密Key——>保证数据的安全传递
- 公开解密Key——>保证数据的不可抵赖
- C#内置实现了公钥加密/私钥解密,如果想要用第三方的DLL-BounccyCastle
四、数字证书
2.1-CA证书
2.2-单边认证https
2.3-双边认证
版权声明:本文为原创文章,版权归 [西瓜程序猿] 所有,转载请注明出处,有任何疑问请私信咨询。
原文链接:https://www.cnblogs.com/kimiliucn/p/17607330.html