日期:2014-05-18  浏览次数:20826 次

关于C#中使用DES加解密问题
private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
  private 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;
  }
  }

  private static string DecryptDES(string decryptString, string decryptKey)
  {
  try
  {
  byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey.Substring(0, 8));
  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(Exception ex)
  {
  return decryptString;
  }
  }
以上是我使用的对于字符串加解密的方法,以前使用都是OK的,但是现在使用加密时在 CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
就有错误了,但是还可以继续,可以返回加密后的字符串,但是等到解密时,系统会Catch到Exception,也是在 CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);时就有错误了,错误信息是
+ Length “cStream.Length”引发了“System.NotSupportedException”类型的异常 long {System.NotSupportedException}
,,,+ Position “cStream.Position”引发了“System.NotSupportedException”类型的异常 long {System.NotSupportedException}

然后要运行到cStream.FlushFinalBlock();才会跳到异常捕获代码。异常信息为“不正确的数据”,ex.StackTrace为:
  在 System.Security.Cryptography.CryptographicException.ThrowCryptogaphicException(Int32 hr)
  在 System.Security.Cryptography.Utils._DecryptData(SafeKeyHandle hKey, Byte[] data, Int32 ib, Int32 cb, Byte[]& outputBuffer, Int32 outputOffset, PaddingMode PaddingMode, Boolean fDone)
  在 System.Security.Cryptography.CryptoAPITransform.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount)
  在 System.Security.Cryptography.CryptoStream.FlushFinalBlock()
  在 KM.Web.Utility.CryptBase.DecryptDES(String decryptString, String decryptKey) 位置 d:\KM3.0\03_Code\01_SourceCode\KM3.0\KM3.0\KMWeb\App_Code\CryptBase.cs:行号 57

请各位牛人帮忙解决,谢谢!

------解决方案--------------------


友情帮顶
------解决方案--------------------
记得C#里边的DES加密只能用ASC,用别的报错.
------解决方案----