C#實現DES對稱加密法
阿新 • • 發佈:2019-02-17
入口引數有三個:key、data、mode。 key為加密解密使用的金鑰,data為加密解密的資料,mode為其工作模式。當模式為加密模式時,明文按照64位進行分組,形成明文組,key用於對資料加密,當模式為解密模式時,key用於對資料解密。實際運用中,金鑰只用到了64位中的56位,這樣才具有高的安全性。
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--> 1 /// <summary>
/// DES對稱加密/// </summary>
public sealed class DES {
/// <summary>
/// Des解密方法
/// </summary>
/// <param name="val"></param>
/// <param name="key"></param>
/// <param name="IV"></param>
/// <returns></returns>
public static string Decrypt(string val, string key, string IV) {
try {
byte[] buffer1 = Convert.FromBase64String(key);
byte[] buffer2 = Convert.FromBase64String(IV);
DESCryptoServiceProvider provider1 = new DESCryptoServiceProvider();
provider1.Mode = CipherMode.ECB;
provider1.Key = buffer1;
provider1.IV = buffer2;
ICryptoTransform transform1 = provider1.CreateDecryptor(provider1.Key, provider1.IV);
byte[] buffer3 = Convert.FromBase64String(val);
MemoryStream stream1 = new MemoryStream();
CryptoStream stream2 = new CryptoStream(stream1, transform1, CryptoStreamMode.Write);
stream2.Write(buffer3, 0, buffer3.Length);
stream2.FlushFinalBlock();
stream2.Close();
return Encoding.Default.GetString(stream1.ToArray());
}
catch// (System.Exception ex)
{
return "";
}
}
/// <summary>
/// Des加密方法
/// </summary>
/// <param name="val"></param>
/// <param name="key"></param>
/// <param name="IV"></param>
/// <returns></returns>
public static string Encrypt(string val, string key, string IV) {
try {
byte[] buffer1 = Convert.FromBase64String(key);
byte[] buffer2 = Convert.FromBase64String(IV);
DESCryptoServiceProvider provider1 = new DESCryptoServiceProvider();
provider1.Mode = CipherMode.ECB;
provider1.Key = buffer1;
provider1.IV = buffer2;
ICryptoTransform transform1 = provider1.CreateEncryptor(provider1.Key, provider1.IV);
byte[] buffer3 = Encoding.Default.GetBytes(val);
MemoryStream stream1 = new MemoryStream();
CryptoStream stream2 = new CryptoStream(stream1, transform1, CryptoStreamMode.Write);
stream2.Write(buffer3, 0, buffer3.Length);
stream2.FlushFinalBlock();
stream2.Close();
return Convert.ToBase64String(stream1.ToArray());
}
catch// (Exception ex)
{
return "";
}
}
}