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