最近工作中用到了des解密,之前沒接觸過,花了點時間去研究了一下,des算是比較基礎的加密方式了,這邊主要講的是ECB模式,ECB模式作為一種基本工作模式,具有操作簡單,易於實現的特點。同時由於其分組的獨立性,利於實現並行處理,並且能很好地防止誤差傳播。個人覺得ECB比較適用於密鑰保護。代碼如下:
public class DesHelper
{
private static String _ConstValue = "12345678";
public static String Decipher(String Str, bool IncludeLocalInfo)
{
if (null == Str || 0 == Str.Length) return "";
try
{
SymmetricAlgorithm sa = new DESCryptoServiceProvider();
String _Key = _ConstValue;
sa.Key = Encoding.UTF8.GetBytes(_Key);
sa.IV = Encoding.UTF8.GetBytes(_ConstValue);
sa.Mode = System.Security.Cryptography.CipherMode.ECB;
sa.Padding = PaddingMode.PKCS7;
ICryptoTransform ct = sa.CreateDecryptor();
byte[] byt = Convert.FromBase64String(Str);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
cs.Write(byt, 0, byt.Length);
cs.FlushFinalBlock();
cs.Close();
return Encoding.UTF8.GetString(ms.ToArray());
}
catch(Exception e) {
}
return "";
}
}
沒錯,代碼就是如此簡單