DES
Posted ives
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了DES相关的知识,希望对你有一定的参考价值。
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);
}
}
}
以上是关于DES的主要内容,如果未能解决你的问题,请参考以下文章