加密的是一个xml文件,存产品信息,方法如下:
public static bool EncryptFile(byte[] buffer, string sOutputFilename, string sKey) { bool IsSuccess = true; FileStream fsEncrypted = null; CryptoStream cryptostream = null; try { FileInfo f = new FileInfo(sOutputFilename); if (!Directory.Exists(f.Directory.FullName)) { Directory.CreateDirectory(f.Directory.FullName); } fsEncrypted = new FileStream(sOutputFilename, FileMode.Create, FileAccess.Write); DESCryptoServiceProvider DES = new DESCryptoServiceProvider(); //DES.BlockSize = 64; DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey); DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey); ICryptoTransform desencrypt = DES.CreateEncryptor(); cryptostream = new CryptoStream(fsEncrypted, desencrypt, CryptoStreamMode.Write); cryptostream.Write(buffer, 0, buffer.Length); cryptostream.Close(); fsEncrypted.Close(); IsSuccess = true; } catch (Exception ex) { IsSuccess = false; } finally { try { if (cryptostream != null) cryptostream.Close(); if (fsEncrypted != null) fsEncrypted.Close(); } catch { } } return IsSuccess; }
第一个参数是一个xdocument对象然后tostring(),然后 Encoding.UTF8.GetBytes()得到的。
解密代码:
public static XDocument DecryptFile(string sInputFilename, string sKey) { FileStream fsread = null; StreamWriter fsDecrypted = null; XDocument xdData = null; try { DESCryptoServiceProvider DES = new DESCryptoServiceProvider(); //A 64 bit key and IV is required for this provider. //Set secret key For DES algorithm. DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey); //Set initialization vector. DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey); //Create a file stream to read the encrypted file back. fsread = new FileStream(sInputFilename, FileMode.Open, FileAccess.Read); //Create a DES decryptor from the DES instance. ICryptoTransform desdecrypt = DES.CreateDecryptor(); //Create crypto stream set to read and do a //DES decryption transform on incoming bytes. CryptoStream cryptostreamDecr = new CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read); xdData = XDocument.Load(new StreamReader(cryptostreamDecr)); } catch (Exception ex) { throw ex; } finally { try { if (fsread != null) fsread.Close(); if (fsDecrypted != null) fsDecrypted.Close(); } catch { } } return xdData; }
XDocument.load哪行报错:根级别上的数据无效。 行 1,位置 1。
在这一行运行new StreamReader(cryptostreamDecr).ReadToEnd(),提示
cryptostream.FlushFinalBlock
能具体讲下吗
@拖鞋王子:
cryptostream = new CryptoStream(fsEncrypted,
desencrypt,
CryptoStreamMode.Write);
cryptostream.Write(buffer, 0, buffer.Length);
cryptostream.FlushFinalBlock();
cryptostream.Close();
@拖鞋王子:
EncryptFile(byte[] buffer,
假设这里的 buffer 是 utf-8 编码,那么解密时要修改成这样:
xdData = XDocument.Load(new StreamReader(cryptostreamDecr,Encoding.GetEncoding("UTF-8")));
@Launcher: 上面那段代码是加密的吧,可是我现在是解密时出错了
@拖鞋王子: 我这试了 什么问题也没有
@Yu: 之前用了两年多是没问题的
@拖鞋王子:是不是换服务器了
你的sKey?
8个字母