我需要ZIP和GPG加密文件流。 然后通过SFTP上传。 我正在使用Zip存档创建条目。 我正在使用GPG加密starksoft.aspen Nuget。
在此处获取本地文件流并返回一个I Eumerable的本地文件流
private static IEnumerable<LocalFile> GetLocalFiles(string dir) =>
Directory.EnumerateFiles(dir, "*", SearchOption.AllDirectories)
.Select(path =>
{
var relativePath = path.Substring(dir.Length + 1);
var localFile = new LocalFile(relativePath, () => File.OpenRead(path));
localFile.Folder = Directory.GetDirectories(dir, "*", SearchOption.TopDirectoryOnly)
.Select(d => d.Split('\\').LastOrDefault()).FirstOrDefault();
return localFile;
});
然后我压缩本地流的IEnumerable
public async Task WriteAsync(IEnumerable<LocalFile> files)
{
FileStream GetTempFileStream() =>
new FileStream(
path: Path.GetTempFileName(),
mode: FileMode.Open,
access: FileAccess.ReadWrite,
share: FileShare.None,
bufferSize: 4096,
options: FileOptions.DeleteOnClose);
//temp fix to resolve the arb naming for zip files
var folder = files.Select(x => x.Folder).FirstOrDefault()
?? DateTime.Now.ToString("yyyy-MM-dd hh-mm-ss");
var zipFile = new LocalFile(
folder+".zip",
async () =>
{
var tempFileStream = GetTempFileStream();
using (var archive = new ZipArchive(tempFileStream, ZipArchiveMode.Create, true))
{
foreach (var file in files)
{
using (var localStream = (await file.OpenLocal()))
using (var zipEntryStream = archive.CreateEntry(file.RelativePath).Open())
{
await localStream.CopyToAsync(zipEntryStream);
}
}
}
tempFileStream.Seek(0, SeekOrigin.Begin);
return tempFileStream;
});
然后我需要对zip流的IEnumerable进行加密...
谢谢
答案 0 :(得分:0)
深入到此 我遇到的问题是,在将流传递给Writer之前,流没有进行加密。
这是我所做的压缩和加密操作,希望对您有所帮助
public async Task WriteAsync(IEnumerable<LocalFile> files)
{
var folder = files.Select(x => x.Folder).FirstOrDefault()
?? DateTime.Now.ToString("yyyy-MM-dd hh-mm-ss");
using (var archiveStream = new MemoryStream())
{
using (var archive = new ZipArchive(archiveStream, ZipArchiveMode.Create, true))
{
foreach (var file in files)
{
using (var entry = archive.CreateEntry(file.RelativePath).Open())
using (var local = (await file.OpenLocal()))
{
local.CopyTo(entry);
}
}
}
var bytes = archiveStream.ToArray();
var encryptionClient = new EncryptionClient("ahmad.zeitoun@medxm1.com", "Password7");
var encryption = new EncryptFiles(encryptionClient);
using (var encryptedStream = new MemoryStream())
{
using (var zipStream = new MemoryStream(bytes))
{
encryption.Gpg.Encrypt(zipStream, encryptedStream);
}
this.bytesArr = encryptedStream.ToArray();
}
}
await this.Writer.WriteAsync(new[] { new LocalFile(folder + ".zip.gpg", () => new MemoryStream(this.bytesArr)) });