标签:memory line encoding 输出 add mode buffer return reader
public static class DESEncryptionUtility
{
public static DESCryptoServiceProvider keyProvider = new DESCryptoServiceProvider();
//默认密钥向量
public static byte[] Encryption2Byte(string input,byte[] key=null,byte[] iv=null)
{
//加密
MemoryStream ms = new MemoryStream();
keyProvider.Mode = CipherMode.ECB;
keyProvider.Padding = PaddingMode.PKCS7;
ICryptoTransform cryptoTransform = key == null ? keyProvider.CreateEncryptor() : keyProvider.CreateEncryptor(key, iv);
//ICryptoTransform cryptoTransform = keyProvider.CreateEncryptor();
CryptoStream encStream = new CryptoStream(ms, cryptoTransform, CryptoStreamMode.Write);
StreamWriter sw = new StreamWriter(encStream);
sw.WriteLine(input);
sw.Close();
//获取加密后的字节
byte[] buffer = ms.ToArray();
return buffer;
}
public static string Encryption(string input,string key=null,string iv=null)
{
byte[] buffer;
if (key == null)
{
buffer = Encryption2Byte(input);
}
else
{
var bKey = Encoding.UTF8.GetBytes(key);
var bIV = Encoding.UTF8.GetBytes(iv);
buffer = Encryption2Byte(input, bKey,bIV);
}
return Convert.ToBase64String(buffer);
}
public static string DeEncryption2Byte(byte[] secret, byte[] key = null, byte[] iv = null)
{
MemoryStream ms = new MemoryStream(secret);
keyProvider.Mode = CipherMode.ECB;
keyProvider.Padding = PaddingMode.PKCS7;
ICryptoTransform cryptoTransform = key == null ? keyProvider.CreateDecryptor() : keyProvider.CreateDecryptor(key, iv);
CryptoStream encStream = new CryptoStream(ms, cryptoTransform, CryptoStreamMode.Read);
StreamReader sr = new StreamReader(encStream);
//输出解密后的内容
var result = sr.ReadLine();
keyProvider.Clear();
sr.Close();
return result;
}
public static string DeEncryption(string secret, string key = null, string iv = null)
{
byte[] buffer = Convert.FromBase64String(secret);
if (key == null)
{
return DeEncryption2Byte(buffer);
}
else
{
var bKey = Encoding.UTF8.GetBytes(key);
var bIV = Encoding.UTF8.GetBytes(iv);
return DeEncryption2Byte(buffer, bKey, bIV);
}
}
}
标签:memory line encoding 输出 add mode buffer return reader
原文地址:https://www.cnblogs.com/ives/p/des.html