forked from icsharpcode/SharpZipLib
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathZipEncryptionHandling.cs
More file actions
330 lines (277 loc) · 8.11 KB
/
Copy pathZipEncryptionHandling.cs
File metadata and controls
330 lines (277 loc) · 8.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;
using NUnit.Framework;
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using ICSharpCode.SharpZipLib.Tests.TestSupport;
namespace ICSharpCode.SharpZipLib.Tests.Zip
{
[TestFixture]
public class ZipEncryptionHandling
{
[Test]
[Category("Encryption")]
[Category("Zip")]
public void Aes128Encryption()
{
CreateZipWithEncryptedEntries("foo", 128);
}
[Test]
[Category("Encryption")]
[Category("Zip")]
public void Aes128EncryptionStored()
{
CreateZipWithEncryptedEntries("foo", 128, CompressionMethod.Stored);
}
[Test]
[Category("Encryption")]
[Category("Zip")]
public void Aes256Encryption()
{
CreateZipWithEncryptedEntries("foo", 256);
}
[Test]
[Category("Encryption")]
[Category("Zip")]
public void Aes256EncryptionStored()
{
CreateZipWithEncryptedEntries("foo", 256, CompressionMethod.Stored);
}
[Test]
[Category("Encryption")]
[Category("Zip")]
public void ZipFileAesDecryption()
{
var password = "password";
using (var ms = new MemoryStream())
{
WriteEncryptedZipToStream(ms, password, 256);
var zipFile = new ZipFile(ms)
{
Password = password
};
foreach (ZipEntry entry in zipFile)
{
if (!entry.IsFile) continue;
using (var zis = zipFile.GetInputStream(entry))
using (var sr = new StreamReader(zis, Encoding.UTF8))
{
var content = sr.ReadToEnd();
Assert.AreEqual(DummyDataString, content, "Decompressed content does not match input data");
}
}
Assert.That(zipFile.TestArchive(false), Is.True, "Encrypted archive should pass validation.");
}
}
[Test]
[Category("Encryption")]
[Category("Zip")]
public void ZipFileAesRead()
{
var password = "password";
using (var ms = new SingleByteReadingStream())
{
WriteEncryptedZipToStream(ms, password, 256);
ms.Seek(0, SeekOrigin.Begin);
var zipFile = new ZipFile(ms)
{
Password = password
};
foreach (ZipEntry entry in zipFile)
{
if (!entry.IsFile) continue;
using (var zis = zipFile.GetInputStream(entry))
using (var sr = new StreamReader(zis, Encoding.UTF8))
{
var content = sr.ReadToEnd();
Assert.AreEqual(DummyDataString, content, "Decompressed content does not match input data");
}
}
}
}
/// <summary>
/// Test using AES encryption on a file whose contents are Stored rather than deflated
/// </summary>
[Test]
[Category("Encryption")]
[Category("Zip")]
public void ZipFileStoreAes()
{
string password = "password";
using (var memoryStream = new MemoryStream())
{
// Try to create a zip stream
WriteEncryptedZipToStream(memoryStream, password, 256, CompressionMethod.Stored);
// reset
memoryStream.Seek(0, SeekOrigin.Begin);
// try to read it
var zipFile = new ZipFile(memoryStream, leaveOpen: true)
{
Password = password
};
foreach (ZipEntry entry in zipFile)
{
if (!entry.IsFile) continue;
// Should be stored rather than deflated
Assert.That(entry.CompressionMethod, Is.EqualTo(CompressionMethod.Stored), "Entry should be stored");
using (var zis = zipFile.GetInputStream(entry))
using (var sr = new StreamReader(zis, Encoding.UTF8))
{
var content = sr.ReadToEnd();
Assert.That(content, Is.EqualTo(DummyDataString), "Decompressed content does not match input data");
}
}
}
}
/// <summary>
/// Test using AES encryption on a file whose contents are Stored rather than deflated
/// </summary>
[Test]
[Category("Encryption")]
[Category("Zip")]
public void ZipFileStoreAesPartialRead()
{
string password = "password";
using (var memoryStream = new MemoryStream())
{
// Try to create a zip stream
WriteEncryptedZipToStream(memoryStream, password, 256, CompressionMethod.Stored);
// reset
memoryStream.Seek(0, SeekOrigin.Begin);
// try to read it
var zipFile = new ZipFile(memoryStream, leaveOpen: true)
{
Password = password
};
foreach (ZipEntry entry in zipFile)
{
if (!entry.IsFile) continue;
// Should be stored rather than deflated
Assert.That(entry.CompressionMethod, Is.EqualTo(CompressionMethod.Stored), "Entry should be stored");
using (var ms = new MemoryStream())
{
using (var zis = zipFile.GetInputStream(entry))
{
byte[] buffer = new byte[1];
while (true)
{
int b = zis.ReadByte();
if (b == -1)
break;
ms.WriteByte((byte)b);
}
}
ms.Seek(0, SeekOrigin.Begin);
using (var sr = new StreamReader(ms, Encoding.UTF8))
{
var content = sr.ReadToEnd();
Assert.That(content, Is.EqualTo(DummyDataString), "Decompressed content does not match input data");
}
}
}
}
}
private static readonly string[] possible7zPaths = new[] {
// Check in PATH
"7z", "7za",
// Check in default install location
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "7-Zip", "7z.exe"),
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "7-Zip", "7z.exe"),
};
public static bool TryGet7zBinPath(out string path7z)
{
var runTimeLimit = TimeSpan.FromSeconds(3);
foreach (var testPath in possible7zPaths)
{
try
{
var p = Process.Start(new ProcessStartInfo(testPath, "i")
{
RedirectStandardOutput = true
});
while (!p.StandardOutput.EndOfStream && (DateTime.Now - p.StartTime) < runTimeLimit)
{
p.StandardOutput.DiscardBufferedData();
}
if (!p.HasExited)
{
p.Close();
Assert.Warn($"Timed out checking for 7z binary in \"{testPath}\"!");
continue;
}
if (p.ExitCode == 0)
{
path7z = testPath;
return true;
}
}
catch (Exception)
{
continue;
}
}
path7z = null;
return false;
}
public void WriteEncryptedZipToStream(Stream stream, string password, int keySize, CompressionMethod compressionMethod = CompressionMethod.Deflated)
{
using (var zs = new ZipOutputStream(stream))
{
zs.IsStreamOwner = false;
zs.SetLevel(9); // 0-9, 9 being the highest level of compression
zs.Password = password; // optional. Null is the same as not setting. Required if using AES.
ZipEntry zipEntry = new ZipEntry("test");
zipEntry.AESKeySize = keySize;
zipEntry.DateTime = DateTime.Now;
zipEntry.CompressionMethod = compressionMethod;
zs.PutNextEntry(zipEntry);
byte[] dummyData = Encoding.UTF8.GetBytes(DummyDataString);
using (var dummyStream = new MemoryStream(dummyData))
{
dummyStream.CopyTo(zs);
}
zs.CloseEntry();
}
}
public void CreateZipWithEncryptedEntries(string password, int keySize, CompressionMethod compressionMethod = CompressionMethod.Deflated)
{
using (var ms = new MemoryStream())
{
WriteEncryptedZipToStream(ms, password, keySize, compressionMethod);
if (TryGet7zBinPath(out string path7z))
{
Console.WriteLine($"Using 7z path: \"{path7z}\"");
ms.Seek(0, SeekOrigin.Begin);
var fileName = Path.GetTempFileName();
try
{
using (var fs = File.OpenWrite(fileName))
{
ms.CopyTo(fs);
}
var p = Process.Start(path7z, $"t -p{password} \"{fileName}\"");
if (!p.WaitForExit(2000))
{
Assert.Warn("Timed out verifying zip file!");
}
Assert.AreEqual(0, p.ExitCode, "Archive verification failed");
}
finally
{
File.Delete(fileName);
}
}
else
{
Assert.Warn("Skipping file verification since 7za is not in path");
}
}
}
private const string DummyDataString = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Fusce bibendum diam ac nunc rutrum ornare. Maecenas blandit elit ligula, eget suscipit lectus rutrum eu.
Maecenas aliquam, purus mattis pulvinar pharetra, nunc orci maximus justo, sed facilisis massa dui sed lorem.
Vestibulum id iaculis leo. Duis porta ante lorem. Duis condimentum enim nec lorem tristique interdum. Fusce in faucibus libero.";
}
}