using System.Text;
using System.IO;
using System.Security.Cryptography;
/// <summary>
/// 字符串加密、解密类,利用DES算法
/// </summary>
public class myEncrypt
{
private static byte[] key = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 };
private static byte[] iv = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 };
/// <summary>
/// 加密
/// </summary>
/// <param name="notEncryptStr">待加密的明文字符串</param>
/// <returns>加密后的字符串</returns>
public static string EncryptString(string notEncryptStr)
{
//初始化加密器生成器
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] byteNotEncrypt = Encoding.UTF8.GetBytes(notEncryptStr);//将字符串转换成字节
MemoryStream encryptMs = new MemoryStream();//创建内存数据流
CryptoStream encryptCs = new CryptoStream(encryptMs, des.CreateEncryptor(key,iv), CryptoStreamMode.Write);//创建加密器
//加密数据
encryptCs.Write(byteNotEncrypt, 0, byteNotEncrypt.Length);//将字节加密并写入内存
encryptCs.FlushFinalBlock();//将缓存中的数据写入内存
encryptMs.Seek(0, SeekOrigin.Begin);//回到内存流开始的位置
//将加密后的数据读取出来
byte[] byteEncrypt = new byte[1024];
int i = encryptMs.Read(byteEncrypt, 0, 1024);
encryptCs.Close();
//将加密后的字节转换为BASE64编码
string decryptStr = Convert.ToBase64String(byteEncrypt, 0, i);
return decryptStr;
}
void test()
{
string str1 = "Hello";
string str2 = myEncrypt.EncryptString(str1);
}
/// <summary>
/// 解密
/// </summary>
/// <param name="decryptStr">待解密的密文字符串</param>
/// <returns>解密后的字符串</returns>
public static string DecryptString(string decryptStr)
{
//初始化解密器生成器
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] byteNotDecrypt = Convert.FromBase64String(decryptStr);//将加密后的BASE64编码的字符串转换成字节
MemoryStream decryptMs = new MemoryStream(byteNotDecrypt);//创建内存数据流
CryptoStream decryptCs = new CryptoStream(decryptMs, des.CreateDecryptor(key, iv), CryptoStreamMode.Read);//创建解密器
//解密数据
byte[] byteDecrypt = new byte[1024];
int i = decryptCs.Read(byteDecrypt, 0, 1024);
decryptCs.Close();
//将解密后的字节转换为BASE64编码
string notEncryptStr = Encoding.UTF8.GetString(byteDecrypt, 0, i);
return notEncryptStr;
}
}