用.NET自带的DES加解密程序,可是发现在解密时,如果密码错误时会有异常(“不正确的数据”)产生,这是为什么呢。
照我的理解,DES是对称加密。如果密码错误,应返回乱码才对(假设加密对象为字符串)。附源码,网上搜索出来的,全是一个模样。using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;namespace Common {
 /// 
 /// 加密和解密
 /// 
 public sealed class EncryptDecrypt {
  private EncryptDecrypt(){}  //默认密钥向量
  private static byte[] Keys = {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF};  /// 
  /// 利用MD5对字符串进行加密
  /// 
  /// 待加密的字符串
  /// 返回加密后的字符串
  public static string EncryptMD5(string encryptString) {
   MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
   UTF8Encoding Encode = new UTF8Encoding();
   byte[] HashedBytes = md5Hasher.ComputeHash(Encode.GetBytes(encryptString));
   return Encode.GetString(HashedBytes);
  }  /// 
  /// DES加密字符串
  /// 
  /// 待加密的字符串
  /// 加密密钥,要求为8位
  /// 加密成功返回加密后的字符串,失败返回源串
  public static string EncryptDES(string encryptString,string encryptKey) {
   try {
    byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0,8));
    byte[] rgbIV = Keys;
    byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
    DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
    MemoryStream mStream = new MemoryStream();
    CryptoStream cStream = new CryptoStream(mStream,dCSP.CreateEncryptor(rgbKey,rgbIV),CryptoStreamMode.Write);
    cStream.Write(inputByteArray,0,inputByteArray.Length);
    cStream.FlushFinalBlock();
    return Convert.ToBase64String(mStream.ToArray());
   }
   catch {
    return encryptString;
   }
  }  /// 
  /// DES解密字符串
  /// 
  /// 待解密的字符串
  /// 解密密钥,要求为8位,和加密密钥相同
  /// 解密成功返回解密后的字符串,失败返源串
  public static string DecryptDES(string decryptString,string decryptKey) {
   try {
    byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);
    byte[] rgbIV = Keys;
    byte[] inputByteArray = Convert.FromBase64String(decryptString);
    DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
    MemoryStream mStream = new MemoryStream();
    CryptoStream cStream = new CryptoStream(mStream,DCSP.CreateDecryptor(rgbKey,rgbIV),CryptoStreamMode.Write);
    cStream.Write(inputByteArray,0,inputByteArray.Length);
    cStream.FlushFinalBlock();
    return Encoding.UTF8.GetString(mStream.ToArray());
   }
   catch {
    return decryptString;
   }
  }
  
 }}