加密解密
DES可逆对称加密
特点:加密速度较快
不足:秘钥管理安全性有待思考(可以采用秘钥分离保存,和二次加密) //秘钥长度规定为8位
大家在使用加密方法的时候,根据自己的使用情况,选择加密和解密方法,请务必验证!
生活实例:有的锁是钥匙开,钥匙锁。
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190508004431454.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTI3NjEzNzM=,size_16,color_FFFFFF,t_70)
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace EncryptDecrypt
{
public class BasedDESHelper : IBasicEncryptDecrypt
{
public static readonly string key = "fengzhilu000";//这个可以采取动态获取的方式。
//可以通过用户输入、特殊文件的保存,或者数据库读取等...
/// <summary>
/// DES加密
/// </summary>
/// <param name="key">密钥</param>
/// <param name="content">需要加密的字符串内容</param>
/// <returns></returns>
public string Encrypt(string key, string content)
{
StringBuilder returnString = new StringBuilder();
byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 8));
byte[] keyIV = keyBytes;
byte[] inputByteArray = Encoding.UTF8.GetBytes(content);
DESCryptoServiceProvider dsp = new DESCryptoServiceProvider();
dsp.Mode = CipherMode.ECB;
dsp.Padding = PaddingMode.Zeros;
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, dsp.CreateEncryptor(keyBytes, keyIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
//组织成16进制字符串
foreach (byte b in mStream.ToArray())
{
returnString.AppendFormat("{0:X2}", b);
}
return returnString.ToString();
}
/// <summary>
/// DES解密
/// </summary>
/// <param name="key">密钥</param>
/// <param name="content">需要解密的字符串内容</param>
/// <returns></returns>
public string Decrypt(string key, string content)
{
byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 8));
byte[] keyIV = keyBytes;
byte[] inputByteArray = new byte[content.Length / 2];
for (int x = 0; x < content.Length / 2; x++)
{
int i = (Convert.ToInt32(content.Substring(x * 2, 2), 16));
inputByteArray[x] = (byte)i;
}
DESCryptoServiceProvider dsp = new DESCryptoServiceProvider();
dsp.Mode = CipherMode.ECB;
dsp.Padding = PaddingMode.Zeros;
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, dsp.CreateDecryptor(keyBytes, keyIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
return Encoding.UTF8.GetString(mStream.ToArray()).TrimEnd('\0');
}
}
}
#region 【1】DES可逆对称加密
private static string content = "Bloss.Guo";
IBasicEncryptDecrypt basedDESHelper = new BasedDESHelper();
string desEncryptResult = basedDESHelper.Encrypt(BasedDESHelper.key, content);
string desDecryptResult = basedDESHelper.Decrypt(BasedDESHelper.key, desEncryptResult);
#endregion
'''
RSA解密非对称加密
RSA可逆非对称加密
非对称:也就说是加密和解密秘钥不是一个。
不对称的好处:可以公开其中的一个(加秘钥、解秘钥)
秘钥可以分为:加秘钥、解秘钥 这种分类是从功能上。
公钥、私钥是相对的,谁公开课,谁就是公钥。谁保密谁就是私钥。
应用好处:可以唯一的确定对方身份 。
不对称可逆加密-1
公开加密密钥 私有了解密密钥
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190508004532408.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTI3NjEzNzM=,size_16,color_FFFFFF,t_70)
不对称可逆加密-2
公开解密密钥 私有了加密密钥
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190508004549693.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTI3NjEzNzM=,size_16,color_FFFFFF,t_70)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace EncryptDecrypt
{
public class BasedRSAHelper : IBasicEncryptDecrypt
{
/// <summary>
/// 生成秘钥对
/// </summary>
/// <returns></returns>
public static KeyValuePair<string, string> CreateKeyValuePair()
{
RSACryptoServiceProvider reaProvider = new RSACryptoServiceProvider();
string publicKey = reaProvider.ToXmlString(false);//公开的秘钥
string privateKey = reaProvider.ToXmlString(true);//私有的秘钥
return new KeyValuePair<string, string>(publicKey, privateKey);
}
/// <summary>
/// 基于RSA算法执行加密
/// </summary>
/// <param name="encryptKey">加密秘钥</param>
/// <param name="content">需要加密的内容</param>
/// <returns></returns>
public string Encrypt(string encryptKey, string content)
{
RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider();
rsaProvider.FromXmlString(encryptKey);
UnicodeEncoding encoding = new UnicodeEncoding();
byte[] resultBytes = rsaProvider.Encrypt(encoding.GetBytes(content), false);
return Convert.ToBase64String(resultBytes);
}
/// <summary>
/// 基于RSA算法执行解密
/// </summary>
/// <param name="decryptKey">解密秘钥</param>
/// <param name="content">需要解密的内容</param>
/// <returns></returns>
public string Decrypt(string decryptKey, string content)
{
byte[] btyes = Convert.FromBase64String(content);
RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider();
rsaProvider.FromXmlString(decryptKey);
byte[] resultBytes = rsaProvider.Decrypt(btyes, false);
UnicodeEncoding encoding = new UnicodeEncoding();
return encoding.GetString(resultBytes);
}
}
}
#region 【2】RSA可逆非对称加密
IBasicEncryptDecrypt basedRSAHelper = new BasedRSAHelper();
KeyValuePair<string, string> keyValuePair = BasedRSAHelper.CreateKeyValuePair();//加密和解密秘钥对有系统格根据算法生成
string rsaEncryptResult = basedRSAHelper.Encrypt(keyValuePair.Key, content);
string RsaDecryptResult = basedRSAHelper.Decrypt(keyValuePair.Value, rsaEncryptResult);
#endregion
MD5加密和基于MD5生成文件摘要
单独加密信息的好处:我们在数据库中存放密码,通常是用MD5,就是让DBA也看不到。以后,你不想让别人看到明文,都可以使用。
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190508004637482.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTI3NjEzNzM=,size_16,color_FFFFFF,t_70)
文件摘要的好处:
1. 防止文件被篡改。
2. 能够快速识别相同的文件。秒传的原理。(文件的MD5摘要解决了相同文件的判断问题)
3. 能够快速识别正确的文件。下载的数据保护。
以上综合运用: Git 、TFS 在这些团队管理软件中鉴别文件是否被修改,然后执行操作,非常重要。
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190508004705606.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTI3NjEzNzM=,size_16,color_FFFFFF,t_70)
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace EncryptDecrypt
{
public class BasedMD5Helper
{
#region 基于的MD5的加密方法
/// <summary>
/// MD5加密
/// </summary>
/// <param name="content">需要加密的字符串内容</param>
/// <param name="length">长度</param>
/// <returns></returns>
public static string Encrypt(string content, int length = 32)//默认参数
{
if (string.IsNullOrEmpty(content)) return string.Empty;
HashAlgorithm hashAlgorithm = CryptoConfig.CreateFromName("MD5") as HashAlgorithm;
byte[] bytes = Encoding.UTF8.GetBytes(content); //这里需要区别编码的
byte[] hashValue = hashAlgorithm.ComputeHash(bytes);
StringBuilder builder = new StringBuilder();
if (length == 16)//16位密文是32位密文的9到24位字符
{
for (int i = 4; i < 12; i++)
{
builder.Append(hashValue[i].ToString("x2"));
}
}
else if (length == 32)
{
for (int i = 0; i < 16; i++)
{
builder.Append(hashValue[i].ToString("x2"));
}
}
else
{
for (int i = 0; i < hashValue.Length; i++)
{
builder.Append(hashValue[i].ToString("x2"));
}
}
return builder.ToString();
}
#endregion MD5
#region 基于MD5对文件内容进行摘要
/// <summary>
/// 获取文件的MD5摘要
/// </summary>
/// <param name="fileName">完整的文件路径</param>
/// <returns></returns>
public static string CreateFileAbstract(string fileName)
{
StringBuilder returnString = new StringBuilder();
FileStream fs = new FileStream(fileName, FileMode.Open);
MD5 md5 = new MD5CryptoServiceProvider();
byte[] bytes = md5.ComputeHash(fs);
for (int i = 0; i < bytes.Length; i++)
{
returnString.Append(bytes[i].ToString("x2"));
}
fs.Close();
return returnString.ToString();
}
#endregion
}
}
#region 【3】实现MD5加密和基于MD5生成文件摘要
string result1 = BasedMD5Helper.Encrypt("jack");
string result2 = BasedMD5Helper.Encrypt("jack");
string result3 = BasedMD5Helper.Encrypt("Tom");
Console.WriteLine(result1);
Console.WriteLine(result2);
Console.WriteLine("----------------------------------------\r\n");
Console.WriteLine(result3);
Console.WriteLine("----------------------------------------\r\n");
string fileAbstract1 = BasedMD5Helper.CreateFileAbstract("1.docx");
string fileAbstract2 = BasedMD5Helper.CreateFileAbstract("2.docx");
Console.WriteLine("-----------------文件摘要---------------\r\n");
Console.WriteLine(fileAbstract1);
Console.WriteLine(fileAbstract2);
Console.Read();
#endregion