-
Notifications
You must be signed in to change notification settings - Fork 989
/
Copy pathZipEncryptionHandling.cs
582 lines (485 loc) · 17 KB
/
ZipEncryptionHandling.cs
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
using ICSharpCode.SharpZipLib.Zip;
using NUnit.Framework;
using System;
using System.IO;
using System.Text;
using ICSharpCode.SharpZipLib.Tests.TestSupport;
using System.Threading.Tasks;
namespace ICSharpCode.SharpZipLib.Tests.Zip
{
[TestFixture]
public class ZipEncryptionHandling
{
[Test]
[Category("Encryption")]
[Category("Zip")]
[TestCase(CompressionMethod.Stored)]
[TestCase(CompressionMethod.Deflated)]
public void Aes128Encryption(CompressionMethod compressionMethod)
{
CreateZipWithEncryptedEntries("foo", 128, compressionMethod);
}
[Test]
[Category("Encryption")]
[Category("Zip")]
[TestCase(CompressionMethod.Stored)]
[TestCase(CompressionMethod.Deflated)]
public void Aes256Encryption(CompressionMethod compressionMethod)
{
CreateZipWithEncryptedEntries("foo", 256, compressionMethod);
}
[Test]
[Category("Encryption")]
[Category("Zip")]
[TestCase(CompressionMethod.Stored)]
[TestCase(CompressionMethod.Deflated)]
public void ZipCryptoEncryption(CompressionMethod compressionMethod)
{
CreateZipWithEncryptedEntries("foo", 0, compressionMethod);
}
/// <summary>
/// Test Known zero length encrypted entries with ZipOutputStream.
/// These are entries where the entry size is set to 0 ahead of time, so that PutNextEntry will fill in the header and there will be no patching.
/// Test with Zip64 on and off, as the logic is different for the two.
/// </summary>
[Test]
public void ZipOutputStreamEncryptEmptyEntries(
[Values] UseZip64 useZip64,
[Values(0, 128, 256)] int keySize,
[Values(CompressionMethod.Stored, CompressionMethod.Deflated)] CompressionMethod compressionMethod)
{
using (var ms = new MemoryStream())
{
using (var zipOutputStream = new ZipOutputStream(ms))
{
zipOutputStream.IsStreamOwner = false;
zipOutputStream.Password = "password";
zipOutputStream.UseZip64 = useZip64;
ZipEntry zipEntry = new ZipEntry("emptyEntry")
{
AESKeySize = keySize,
CompressionMethod = compressionMethod,
CompressedSize = 0,
Crc = 0,
Size = 0,
};
zipOutputStream.PutNextEntry(zipEntry);
zipOutputStream.CloseEntry();
}
SevenZipHelper.VerifyZipWith7Zip(ms, "password");
}
}
[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>
/// As <see cref="ZipFileStoreAes"/>, but with Async reads
/// </summary>
[Test]
[Category("Encryption")]
[Category("Zip")]
public async Task ZipFileStoreAesAsync()
{
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))
{
var buffer = new byte[entry.Size];
using (var inputStream = zipFile.GetInputStream(entry))
{
await zis.ReadAsync(buffer, 0, buffer.Length);
}
var content = Encoding.UTF8.GetString(buffer);
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([Values(1, 7, 17)] int readSize)
{
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[readSize];
while (true)
{
int read = zis.Read(buffer, 0, readSize);
if (read == 0)
break;
ms.Write(buffer, 0, read);
}
}
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");
}
}
}
}
}
/// <summary>
/// Test adding files to an encrypted zip
/// </summary>
[Test]
[Category("Encryption")]
[Category("Zip")]
public void ZipFileAesAdd()
{
string password = "password";
string testData = "AdditionalData";
int keySize = 256;
using (var memoryStream = new MemoryStream())
{
// Try to create a zip stream
WriteEncryptedZipToStream(memoryStream, password, keySize, CompressionMethod.Deflated);
// reset
memoryStream.Seek(0, SeekOrigin.Begin);
// Update the archive with ZipFile
{
using (var zipFile = new ZipFile(memoryStream, leaveOpen: true) { Password = password })
{
zipFile.BeginUpdate();
zipFile.Add(new StringMemoryDataSource(testData), "AdditionalEntry", CompressionMethod.Deflated);
zipFile.CommitUpdate();
}
}
// Test the updated archive
{
memoryStream.Seek(0, SeekOrigin.Begin);
using (var zipFile = new ZipFile(memoryStream, leaveOpen: true) { Password = password })
{
Assert.That(zipFile.Count, Is.EqualTo(2), "Incorrect entry count in updated archive");
// Disabled because of bug #317
// Assert.That(zipFile.TestArchive(true), Is.True);
// Check the original entry
{
var originalEntry = zipFile.GetEntry("test");
Assert.That(originalEntry.IsCrypted, Is.True);
Assert.That(originalEntry.AESKeySize, Is.EqualTo(keySize));
using (var zis = zipFile.GetInputStream(originalEntry))
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");
}
}
// Check the additional entry
// This should be encrypted, though currently only with ZipCrypto
{
var additionalEntry = zipFile.GetEntry("AdditionalEntry");
Assert.That(additionalEntry.IsCrypted, Is.True);
using (var zis = zipFile.GetInputStream(additionalEntry))
using (var sr = new StreamReader(zis, Encoding.UTF8))
{
var content = sr.ReadToEnd();
Assert.That(content, Is.EqualTo(testData), "Decompressed content does not match input data");
}
}
}
}
// As an extra test, verify the file with 7-zip
SevenZipHelper.VerifyZipWith7Zip(memoryStream, password);
}
}
/// <summary>
/// Test deleting files from an encrypted zip
/// </summary>
[Test]
[Category("Encryption")]
[Category("Zip")]
public void ZipFileAesDelete()
{
string password = "password";
int keySize = 256;
using (var memoryStream = new MemoryStream())
{
// Try to create a zip stream
WriteEncryptedZipToStream(memoryStream, 3, password, keySize, CompressionMethod.Deflated);
// reset
memoryStream.Seek(0, SeekOrigin.Begin);
// delete one of the entries from the file
{
using (var zipFile = new ZipFile(memoryStream, leaveOpen: true) { Password = password })
{
// Must have 3 entries to start with
Assert.That(zipFile.Count, Is.EqualTo(3), "Must have 3 entries to start with");
var entryToDelete = zipFile.GetEntry("test-1");
Assert.That(entryToDelete, Is.Not.Null, "the entry that we want to delete must exist");
zipFile.BeginUpdate();
zipFile.Delete(entryToDelete);
zipFile.CommitUpdate();
}
}
// Test the updated archive
{
memoryStream.Seek(0, SeekOrigin.Begin);
using (var zipFile = new ZipFile(memoryStream, leaveOpen: true) { Password = password })
{
// We should now only have 2 files
Assert.That(zipFile.Count, Is.EqualTo(2), "Incorrect entry count in updated archive");
// Disabled because of bug #317
// Assert.That(zipFile.TestArchive(true), Is.True);
// Check the first entry
{
var originalEntry = zipFile.GetEntry("test-0");
Assert.That(originalEntry.IsCrypted, Is.True);
Assert.That(originalEntry.AESKeySize, Is.EqualTo(keySize));
using (var zis = zipFile.GetInputStream(originalEntry))
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");
}
}
// Check the second entry
{
var originalEntry = zipFile.GetEntry("test-2");
Assert.That(originalEntry.IsCrypted, Is.True);
Assert.That(originalEntry.AESKeySize, Is.EqualTo(keySize));
using (var zis = zipFile.GetInputStream(originalEntry))
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");
}
}
}
}
// As an extra test, verify the file with 7-zip
SevenZipHelper.VerifyZipWith7Zip(memoryStream, password);
}
}
// This is a zip file with one AES encrypted entry, whose password in an empty string.
const string TestFileWithEmptyPassword = @"UEsDBDMACQBjACaj0FAyKbop//////////8EAB8AdGVzdAEAEAA4AAAA
AAAAAFIAAAAAAAAAAZkHAAIAQUUDCABADvo3YqmCtIE+lhw26kjbqkGsLEOk6bVA+FnSpVD4yGP4Mr66Hs14aTtsPUaANX2
Z6qZczEmwoaNQpNBnKl7p9YOG8GSHDfTCUU/AZvT4yGFhUEsHCDIpuilSAAAAAAAAADgAAAAAAAAAUEsBAjMAMwAJAGMAJq
PQUDIpuin//////////wQAHwAAAAAAAAAAAAAAAAAAAHRlc3QBABAAOAAAAAAAAABSAAAAAAAAAAGZBwACAEFFAwgAUEsFBgAAAAABAAEAUQAAAKsAAAAAAA==";
/// <summary>
/// Test reading an AES encrypted entry whose password is an empty string.
/// </summary>
/// <remarks>
/// Test added for https://github.com/icsharpcode/SharpZipLib/issues/471.
/// </remarks>
[Test]
[Category("Zip")]
public void ZipFileAESReadWithEmptyPassword()
{
var fileBytes = Convert.FromBase64String(TestFileWithEmptyPassword);
using (var ms = new MemoryStream(fileBytes))
using (var zipFile = new ZipFile(ms, leaveOpen: true))
{
zipFile.Password = string.Empty;
var entry = zipFile.FindEntry("test", true);
using (var inputStream = zipFile.GetInputStream(entry))
using (var sr = new StreamReader(inputStream, Encoding.UTF8))
{
var content = sr.ReadToEnd();
Assert.That(content, Is.EqualTo("Lorem ipsum dolor sit amet, consectetur adipiscing elit."), "Decompressed content does not match expected data");
}
}
}
/// <summary>
/// ZipInputStream can't decrypt AES encrypted entries, but it should report that to the caller
/// rather than just failing.
/// </summary>
[Test]
[Category("Zip")]
public void ZipinputStreamShouldGracefullyFailWithAESStreams()
{
string password = "password";
using (var memoryStream = new MemoryStream())
{
// Try to create a zip stream
WriteEncryptedZipToStream(memoryStream, password, 256);
// reset
memoryStream.Seek(0, SeekOrigin.Begin);
// Try to read
using (var inputStream = new ZipInputStream(memoryStream))
{
inputStream.Password = password;
var entry = inputStream.GetNextEntry();
Assert.That(entry.AESKeySize, Is.EqualTo(256), "Test entry should be AES256 encrypted.");
// CanDecompressEntry should be false.
Assert.That(inputStream.CanDecompressEntry, Is.False, "CanDecompressEntry should be false for AES encrypted entries");
// Should throw on read.
Assert.Throws<ZipException>(() => inputStream.ReadByte());
}
}
}
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.
AddEncrypedEntryToStream(zs, $"test", keySize, compressionMethod);
}
}
public void WriteEncryptedZipToStream(Stream stream, int entryCount, string password, int keySize, CompressionMethod compressionMethod)
{
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.
for (int i = 0; i < entryCount; i++)
{
AddEncrypedEntryToStream(zs, $"test-{i}", keySize, compressionMethod);
}
}
}
private void AddEncrypedEntryToStream(ZipOutputStream zipOutputStream, string entryName, int keySize, CompressionMethod compressionMethod)
{
ZipEntry zipEntry = new ZipEntry(entryName)
{
AESKeySize = keySize,
DateTime = DateTime.Now,
CompressionMethod = compressionMethod
};
zipOutputStream.PutNextEntry(zipEntry);
byte[] dummyData = Encoding.UTF8.GetBytes(DummyDataString);
using (var dummyStream = new MemoryStream(dummyData))
{
dummyStream.CopyTo(zipOutputStream);
}
zipOutputStream.CloseEntry();
}
public void CreateZipWithEncryptedEntries(string password, int keySize, CompressionMethod compressionMethod = CompressionMethod.Deflated)
{
using (var ms = new MemoryStream())
{
WriteEncryptedZipToStream(ms, password, keySize, compressionMethod);
SevenZipHelper.VerifyZipWith7Zip(ms, password);
}
}
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.";
}
}