加密发布到 FTP 站点的文件
本文关键字:站点 文件 FTP 加密 | 更新日期: 2023-09-27 18:31:47
我正在使用VS 2010(C#)。我正在尝试加密(解密)从FTP站点上传(下载)的文件。 我认为这比使用本地临时文件在上传前加密并在下载后解密更快。 我在下面的代码上收到错误。 我似乎无法对齐各种流类型(即文件流、加密流和流)。 任何帮助都非常感谢。
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);
}
这对我有用,我使用了内存流并将加密的字节写入其中。 还将加密流模式更改为写入。
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();
}