我正在使用VS 2010(C#)。我正在尝试加密(解密)从FTP站点上载(下载)文件的文件。我认为这比使用本地临时文件在上载之前加密和下载后解密要快。我在下面的代码中收到错误。我似乎无法获得对齐的各种流类型(即FileStream,CryptoStream和Stream)。非常感谢任何帮助。
public void Upload(byte[] desKey, byte[] desIV)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(Destination);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(UserName, Password);
FileStream fStream = File.Open(SourceFile, FileMode.OpenOrCreate);
CryptoStream responseStream = new CryptoStream(fStream, new DESCryptoServiceProvider().CreateDecryptor(desKey, desIV), CryptoStreamMode.Read);
byte[] fileContents = Encoding.UTF8.GetBytes(responseStream.ToString());
responseStream.Close(); ///ERROR here
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
response.Close();
}
单元测试:
public void CleanEncryptUploadTest()
{
FT.ftp uploadTest = new FT.ftp();
uploadTest.UserName = "ausername";
uploadTest.Password = "apassword";
uploadTest.SourceFile = "D:\\Temp\\Test\\file.txt";
uploadTest.Destination = "ftp://ftp.mysite.com/test2.txt";
byte[] key = ASCIIEncoding.ASCII.GetBytes("TestZone");
byte[] initVector = ASCIIEncoding.ASCII.GetBytes("TestZone");
uploadTest.Upload(key, initVector);
}
答案 0 :(得分:0)
这对我有用,我使用了一个内存流并将加密的字节写入其中。还改变了cryptostream模式来编写。
public void Upload(byte[] key, byte[] iv)
{
byte[] fileContents;
using (FileStream inputeFile = new FileStream(this.SourceFile, FileMode.Open, FileAccess.Read))
{
using (MemoryStream encryptedStream = new MemoryStream())
{
using (CryptoStream cryptostream = new CryptoStream(encryptedStream, new DESCryptoServiceProvider().CreateEncryptor(key, iv), CryptoStreamMode.Write))
{
byte[] bytearrayinput = new byte[inputeFile.Length];
inputeFile.Read(bytearrayinput, 0, bytearrayinput.Length);
cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
fileContents = encryptedStream.ToArray();
}
}
}
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(this.Destination);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(this.UserName, this.Password);
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
response.Close();
}