-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathData.CrossZip.pas
More file actions
3229 lines (2744 loc) · 96.5 KB
/
Data.CrossZip.pas
File metadata and controls
3229 lines (2744 loc) · 96.5 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
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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{******************************************************************************}
{ }
{ Delphi&FPC cross platform zip library }
{ }
{ Copyright (c) 2025 WiNDDRiVER(soulawing@gmail.com) }
{ }
{ Homepage: https://github.com/winddriver/Delphi-Cross-Zip }
{ }
{******************************************************************************}
unit Data.CrossZip;
{$I zLib.inc}
//{$IFDEF FPC}
// {$MODE DELPHI}
// {$MODESWITCH UNICODESTRINGS}
//{$ENDIF}
{$DEFINE SUPPORT_ZLIB_WINDOWBITS}
// 密钥相关计算需要设置这两个编译开关, 否则会出现越界异常
{$R-}
{$Q-}
{$IFNDEF SUPPORT_ZLIB_WINDOWBITS}
// {$MESSAGE WARN 'NOT Compatable with WinZip/WinRAR etc.'}
{$ENDIF}
// 这个库参考了 CnVcl 组件库中的 CnZip.pas, 以及 Delphi RTL 中的 System.zip.pas
//
// 主要特性:
// 1. 支持 delphi + fpc, 跨平台
// 2. 支持 aes
// 3. 支持 zip64
// 4. 动态加密/解密, 处理超大文件也只需要很小的内存, 没有多余的内存复制, 极大提升性能
// 5. 读取数据的同时进行 crc32 计算, 极大提升性能
interface
uses
SysUtils,
Classes,
Math,
Generics.Collections,
ZLib,
CnAES,
CnNative,
Utils.Hash,
Utils.PBKDF2,
Utils.AES.CTR;
const
SIZE_LOCAL_HEADER = 26; // 本地文件头大小
SIZE_CENTRAL_HEADER = 42; // 中心目录文件头大小
SIZE_END_HEADER = 18; // 结束文件头大小
SIZE_ZIP_CRYPT_HEAD = 12; // 加密头大小
// 通用标志位(TZipHeader.Flag)
FLAG_PASSWORD = $0001; // 加密
FLAG_DATA_DESCRIPTOR = $0008; // 1 shl 3 使用数据描述符
FLAG_UTF8 = $0800; // 1 shl 11 文件名使用 UTF-8 编码
EXID_ZIP64 = $0001; // ZIP64 扩展字段标志
EXID_AES = $9901; // AES 扩展字段标志
PBKDF2_ITERATIONS = 1000; // AES 密钥迭代次数
MAX_UINT16 = High(UInt16);
MAX_UINT32 = High(UInt32);
MAX_COMMENT_SIZE = $FFFF; // 最大注释大小
BUF_SIZE = 64 * 1024; // 缓存大小
type
/// <summary>
/// Zip 相关异常
/// </summary>
EZipException = class(Exception);
/// <summary>
/// Zip 压缩类型
/// </summary>
TZipCompressionMethod = (
zcStored = 0,
zcShrunk,
zcReduce1,
zcReduce2,
zcReduce3,
zcReduce4,
zcImplode,
zcTokenize,
zcDeflate,
zcDeflate64,
zcPKImplode,
zcReserved11,
zcBZIP2,
zcReserved13,
zcLZMA,
zcReserved15,
zcReserved16,
zcReserved17,
zcTERSE,
zcLZ77,
zcWavePack = 97,
zcPPMdI1 = 98,
zcAES = 99
);
/// <summary>
/// Zip 文件头结构(中心目录文件头和本地文件头合一)
/// </summary>
TZipHeader = packed record
MadeByVersion: UInt16; // **中心目录文件头开始
RequiredVersion: UInt16; // **本地文件头开始
Flag: UInt16; // 通用标志位
CompressionMethod: UInt16; // 压缩方法
// 0 无压缩
// 8 Deflate最常用的压缩方法, 使用 LZ77 和 Huffman 编码进行压缩, 平衡了压缩率和速度.
// 99 AES加密
ModifiedDateTime: UInt32;
CRC32: UInt32;
_CompressedSize: UInt32;
_UncompressedSize: UInt32;
FileNameLength: UInt16;
ExtraFieldLength: UInt16; // **本地文件头结束(从 RequiredVersion 到 ExtraFieldLength 共 26 字节)
FileCommentLength: UInt16;
DiskNumberStart: UInt16;
InternalAttributes: UInt16;
ExternalAttributes: UInt32;
_LocalHeaderOffset: UInt32; // **中心目录文件头结束(从 MadeByVersion 到 LocalHeaderOffset 共 42 字节)
FileName: TBytes;
ExtraField: TBytes;
FileComment: TBytes;
function HasPassword: Boolean;
function HasDataDescriptor: Boolean;
function IsUtf8FileName: Boolean;
function IsDirectory: Boolean;
function GetCompressedSize64: UInt64;
function GetLocalHeaderOffset64: UInt64;
function GetUncompressedSize64: UInt64;
procedure SetCompressedSize64(const AValue: UInt64);
procedure SetLocalHeaderOffset64(const AValue: UInt64);
procedure SetUncompressedSize64(const AValue: UInt64);
property CompressedSize: UInt64 read GetCompressedSize64 write SetCompressedSize64;
property UncompressedSize: UInt64 read GetUncompressedSize64 write SetUncompressedSize64;
property LocalHeaderOffset: UInt64 read GetLocalHeaderOffset64 write SetLocalHeaderOffset64;
end;
PZipHeader = ^TZipHeader;
/// <summary>
/// Zip 中心目录结束头
/// </summary>
TZipEndOfCentralHeader = packed record
DiskNumber: UInt16; // 当前磁盘编号
CentralDirStartDisk: UInt16; // 中心目录起始所在的磁盘编号
NumEntriesThisDisk: UInt16; // 当前磁盘上的中心目录条目数
CentralDirEntries: UInt16; // 中心目录的总条目数(包括所有磁盘)
CentralDirSize: UInt32; // 中心目录的大小(以字节为单位)
CentralDirOffset: UInt32; // 中心目录相对于文件开头的偏移量
CommentLength: UInt16; // 注释字段的长度(以字节为单位), 如果为 0, 则表示没有附加注释
{Comment: RawByteString}
end;
/// <summary>
/// ZIP64 中心目录扩展头部
/// </summary>
TZip64Header = packed record
Signature: UInt32; // ZIP64 结束中心目录标志(固定为 $06064B50)
HeaderSize: Int64; // HeaderSize 表示从记录的 HeaderSize 字段之后到记录结束的字节数(不包括 Signature 和 HeaderSize 字段本身)
MadeByVersion: UInt16; // 创建 ZIP 文件的版本号
RequiredVersion: UInt16; // 解压此 ZIP 文件所需的最低版本号
NumberOfDisks: UInt32; // 当前磁盘的编号
CentralDirStartDisk: UInt32; // 中心目录起始所在磁盘的编号
NumEntriesThisDisk: UInt64; // 当前磁盘上的中心目录条目总数
CentralDirEntries: UInt64; // 中心目录的总条目数(包括所有磁盘)
CentralDirSize: UInt64; // 中心目录的大小(以字节为单位)
CentralDirOffset: UInt64; // 中心目录起始相对于起始磁盘编号的偏移量
//zip64 extensible data sector
end;
/// <summary>
/// ZIP64 中心目录定位器
/// </summary>
TZip64EndOfCentralHeader = packed record
Signature: UInt32; // ZIP64 中心目录定位器标志(固定为 $07064B50)
CentralDirStartDisk: UInt32; // 中心目录所在磁盘的编号
Zip64CentralDirOffset: UInt64; // ZIP64 中心目录记录相对于文件开头的偏移量
TotalNumberOfDisks: UInt32; // ZIP 文件中的磁盘总数
end;
/// <summary>
/// 扩展字段结构
/// </summary>
TZipExtraField = packed record
FieldId: Word;
FieldLen: Word;
// Data: Array[FieldLen] of Byte
end;
/// <summary>
/// ZIP64 扩展字段结构(FieldId = $0001)
/// </summary>
TZip64ExtraHeader = packed record
UncompressedSize: UInt64; // 未压缩数据的大小(单位:字节), 如果原始字段的值为 $FFFFFFFF, 则此字段有效
CompressedSize: UInt64; // 压缩数据的大小(可选, 单位:字节), 如果原始字段的值为 $FFFFFFFF, 则此字段有效
LocalHeaderOffset: UInt64; // 本地文件头的偏移量(可选, 相对于文件开头), 如果原始字段的值为 $FFFFFFFF, 则此字段有效
DiskNumberStart: UInt32; // 起始磁盘编号(可选), 如果原始字段的值为 $FFFFFFFF, 则此字段有效
end;
/// <summary>
/// AES 加密扩展字段结构(FieldId = $9901)
/// </summary>
TAESExtraField = packed record
Version: UInt16; // AES 加密版本号, 一般为 $0001
Vendor: UInt16; // AES 加密的供应商标识, 一般为"AE"(ASCII 编码, $4541)
EncryptionStrength: UInt8; // AES 密钥长度($01 表示 128 位, $02 表示 192 位, $03 表示 256 位)
CompressionMethod: UInt16; // 原始文件使用的压缩方法. 这一字段用于标明文件在加密前采用的压缩方法, 如 8 表示 Deflate
end;
/// <summary>
/// Zip 文件打开方式
/// </summary>
TZipMode = (zmRead, zmReadWrite, zmCreate);
/// <summary>
/// Zip 操作类
/// </summary>
TCrossZip = class
private const
SIGNATURE_END_HEADER: UInt32 = $06054B50; // 中心目录结束标志
SIGNATURE_CENTRAL_HEADER: UInt32 = $02014B50; // 中心目录文件头标志
SIGNATURE_LOCAL_HEADER: UInt32 = $04034B50; // 本地文件头标志
SIGNATURE_ZIP64_END_HEADER: UInt32 = $07064B50; // ZIP64 结束中心目录标志
SIGNATURE_ZIP64_CENTRAL_HEADER: UInt32 = $06064B50; // ZIP64 中心目录定位器标志
SIGNATURE_DESCRIPTOR: UInt32 = $08074B50; // 数据描述符标志
protected class threadvar
FBuffer: array [0..BUF_SIZE-1] of Byte;
private
FUtf8: Boolean;
FFileList: TList<PZipHeader>;
FComment: TBytes;
FPassword: TBytes;
FZipFileName: string;
FZipStream: TStream;
FOpenMode: TZipMode;
FOwnedStream, FChanged: Boolean;
FRemovePath: Boolean;
function GetComment: string;
function GetFileComment(Index: Integer): string;
function GetFileCount: Integer;
function GetFileInfo(Index: Integer): PZipHeader;
function GetFileName(Index: Integer): string;
procedure SetComment(const Value: string);
procedure SetFileComment(Index: Integer; const Value: string);
procedure SetUtf8(const Value: Boolean);
// 读取中心目录
procedure ReadCentralHeader;
// 定位中心目录结束头
function LocateEndOfCentralHeader(const AStream: TStream;
var AZipEndHeader: TZipEndOfCentralHeader): Boolean;
// 添加数据流
function AddStream(const AData: TStream; const ALocalHeader: PZipHeader;
const ACompressLevel: Integer = Z_DEFAULT_COMPRESSION;
const AStrategy: Integer = Z_DEFAULT_STRATEGY): Boolean;
procedure FreeOwnedStream;
// 保存 Zip 文件
procedure Save;
function GetUtf8: Boolean;
private
class procedure NewHeader(var AHeader: PZipHeader); static;
class procedure FreeHeader(const AHeader: PZipHeader); static;
protected
FStartFileData: Int64;
FEndFileData: Int64;
procedure ClearFiles;
function RawToString(const ARaw: TBytes): string;
function StringToRaw(const AStr: string): TBytes;
function GetHasPassword: Boolean; virtual;
function GetPassword: string;
procedure SetPassword(const Value: string); virtual;
public
constructor Create; virtual;
destructor Destroy; override;
/// <summary>
/// 打开 Zip 文件
/// </summary>
/// <param name="AZipFileStream">
/// zip文件数据流
/// </param>
/// <param name="AOpenMode">
/// 打开方式
/// </param>
procedure Open(const AZipFileName: string; const AOpenMode: TZipMode); overload;
/// <summary>
/// 打开 Zip 文件
/// </summary>
/// <param name="AZipFileName">
/// zip文件名
/// </param>
/// <param name="AOpenMode">
/// 打开方式
/// </param>
procedure Open(const AZipFileStream: TStream; const AOpenMode: TZipMode; const AOwned: Boolean); overload;
/// <summary>
/// 关闭 Zip 文件(同时会自动保存)
/// </summary>
procedure Close;
/// <summary>
/// 解压指定序号的单个文件至流
/// </summary>
/// <param name="AArchiveIndex">
/// 文件序号
/// </param>
/// <param name="ADstStream">
/// 用于保存数据的流
/// </param>
function ExtractToStream(const AArchiveIndex: Integer; const ADstStream: TStream): Boolean; overload;
/// <summary>
/// 解压指定名称的单个文件至流
/// </summary>
/// <param name="AArchiveName">
/// zip内部文件名
/// </param>
/// <param name="ADstStream">
/// 用于保存数据的流
/// </param>
function ExtractToStream(const AArchiveName: string; const ADstStream: TStream): Boolean; overload;
/// <summary>
/// 解压指定序号的单个文件至文件
/// </summary>
/// <param name="AArchiveIndex">
/// 文件序号
/// </param>
/// <param name="ADstStream">
/// 用于保存数据的流
/// </param>
function ExtractToFile(const AArchiveIndex: Integer; const ADstFileName: string): Boolean; overload;
/// <summary>
/// 解压指定名称的单个文件至文件
/// </summary>
/// <param name="AArchiveName">
/// zip内部文件名
/// </param>
/// <param name="ADstStream">
/// 用于保存数据的流
/// </param>
function ExtractToFile(const AArchiveName: string; const ADstFileName: string): Boolean; overload;
/// <summary>
/// 解压指定序号的单个文件至指定目录
/// </summary>
/// <param name="AArchiveIndex">
/// 文件序号
/// </param>
/// <param name="ADstPath">
/// 用于保存数据的目录
/// </param>
/// <param name="ACreateSubdirs">
/// 是否创建子目录
/// </param>
function ExtractToPath(const AArchiveIndex: Integer; const ADstPath: string; const ACreateSubdirs: Boolean = True): Boolean; overload;
/// <summary>
/// 解压指定名称的单个文件至指定目录
/// </summary>
/// <param name="AArchiveName">
/// zip内部文件名
/// </param>
/// <param name="ADstPath">
/// 用于保存数据的目录
/// </param>
/// <param name="ACreateSubdirs">
/// 是否创建子目录
/// </param>
function ExtractToPath(const AArchiveName: string; const ADstPath: string; const ACreateSubdirs: Boolean = True): Boolean; overload;
/// <summary>
/// 将打开的 Zip 文件全部解压至指定目录
/// </summary>
/// <param name="ADstPath">
/// 用于保存数据的目录
/// </param>
procedure ExtractAllToPath(const ADstPath: string);
/// <summary>
/// 向 Zip 中添加文件数据
/// </summary>
/// <param name="AFileStream">
/// 文件数据流
/// </param>
/// <param name="AFileDateTime">
/// 文件修改时间
/// </param>
/// <param name="AArchiveName">
/// zip内部文件名
/// </param>
/// <param name="ACompression">
/// 压缩方法
/// </param>
/// <param name="ACompressLevel">
/// 压缩级别(Deflate: 1-9, -1使用默认级别)
/// </param>
function AddFromStream(const AFileStream: TStream;
const AFileDateTime: TDateTime; const AArchiveName: string;
const ACompression: TZipCompressionMethod = zcDeflate;
const ACompressLevel: Integer = Z_DEFAULT_COMPRESSION;
const AStrategy: Integer = Z_DEFAULT_STRATEGY): Boolean; overload;
/// <summary>
/// 向 Zip 中添加文件数据
/// </summary>
/// <param name="AFileStream">
/// 文件数据流
/// </param>
/// <param name="AArchiveName">
/// zip内部文件名
/// </param>
/// <param name="ACompression">
/// 压缩方法
/// </param>
/// <param name="ACompressLevel">
/// 压缩级别(Deflate: 1-9, -1使用默认级别)
/// </param>
function AddFromStream(const AFileStream: TStream;
const AArchiveName: string;
const ACompression: TZipCompressionMethod = zcDeflate;
const ACompressLevel: Integer = Z_DEFAULT_COMPRESSION;
const AStrategy: Integer = Z_DEFAULT_STRATEGY): Boolean; overload;
/// <summary>
/// 向 Zip 中添加文件数据
/// </summary>
/// <param name="AFileName">
/// 文件名
/// </param>
/// <param name="AArchiveName">
/// zip内部文件名
/// </param>
/// <param name="ACompression">
/// 压缩方法
/// </param>
/// <param name="ACompressLevel">
/// 压缩级别(Deflate: 1-9, -1使用默认级别)
/// </param>
function AddFromFile(const AFileName: string;
const AArchiveName: string = '';
const ACompression: TZipCompressionMethod = zcDeflate;
const ACompressLevel: Integer = Z_DEFAULT_COMPRESSION;
const AStrategy: Integer = Z_DEFAULT_STRATEGY): Boolean; overload;
/// <summary>
/// 向 Zip 中添加空目录
/// </summary>
/// <param name="ADirName">
/// 目录名
/// </param>
function AddEmptyDir(const ADirName: string): Boolean;
/// <summary>
/// 从 Zip 文件内删除一个指定序号的文件
/// </summary>
/// <param name="AArchiveIndex">
/// 文件序号
/// </param>
function Delete(const AArchiveIndex: Integer): Boolean; overload;
/// <summary>
/// 从 Zip 文件内删除一个指定文件
/// </summary>
/// <param name="AArchiveName">
/// zip内部文件名
/// </param>
function Delete(const AArchiveName: string): Boolean; overload;
/// <summary>
/// 在该 Zip 文件中查找指定文件名, 返回其顺序索引
/// </summary>
function IndexOf(const AArchiveName: string): Integer;
/// <summary>
/// 该 Zip 文件包含的文件个数
/// </summary>
property FileCount: Integer read GetFileCount;
/// <summary>
/// 该 Zip 文件包含的文件名
/// </summary>
property FileName[Index: Integer]: string read GetFileName;
/// <summary>
/// 该 Zip 文件包含的文件信息, 从中央目录读出的
/// </summary>
property FileInfo[Index: Integer]: PZipHeader read GetFileInfo;
/// <summary>
/// 该 Zip 文件包含的文件注释
/// </summary>
property FileComment[Index: Integer]: string read GetFileComment write SetFileComment;
/// <summary>
/// 该 Zip 文件包含的注释
/// </summary>
property Comment: string read GetComment write SetComment;
/// <summary>
/// 该 Zip 文件是否支持 Utf8
/// </summary>
property Utf8: Boolean read GetUtf8 write SetUtf8;
/// <summary>
/// 该 Zip 文件的密码
/// </summary>
property Password: string read GetPassword write SetPassword;
/// <summary>
/// 该 Zip 文件是否有密码
/// </summary>
property HasPassword: Boolean read GetHasPassword;
/// <summary>
/// 是否去除每个文件的路径信息只留文件名信息
/// 只在 AddFromFile 中 ArchiveFileName 为空的情况下有效
/// </summary>
property RemovePath: Boolean read FRemovePath write FRemovePath;
end;
/// <summary>
/// 压缩类型的实现基类
/// </summary>
TZipCompressionHandlerBase = class abstract
public
class function CanHandleCompressionMethod(
const AMethod: TZipCompressionMethod): Boolean; virtual; abstract;
class function CreateCompressionStream(
const AMethod: TZipCompressionMethod; const AOutStream: TStream;
const AZipHeader: PZipHeader; const APassword: TBytes;
const ACompressLevel, AStrategy: Integer): TStream; virtual; abstract;
class function CreateDecompressionStream(
const AMethod: TZipCompressionMethod; const AInStream: TStream;
const AZipHeader: PZipHeader; const APassword: TBytes): TStream; virtual; abstract;
end;
TZipCompressionHandlerClass = class of TZipCompressionHandlerBase;
// 供外界提供对新的压缩方式的支持
procedure RegisterZipCompressionHandler(const AClass: TZipCompressionHandlerClass);
// 判断 Zip 文件是否合法
function ZipFileIsValid(const AFileName: string): Boolean;
// 将指定 Zip 文件解压缩到指定目录
function ZipExtractTo(const AFileName: string; const ADstDir: string;
const APassword: string = ''): Boolean;
implementation
resourcestring
SZipErrorRead = 'Error Reading Zip File';
SZipErrorWrite = 'Error Writing Zip File';
SZipInvalidZip = 'Invalid Zip File';
SZipInvalidMode = 'Invalid Zip Mode';
SZipInvalidLocalHeader = 'Invalid Zip Local Header';
SZipInvalidCentralHeader = 'Invalid Zip Central Header';
SFileNotFound = 'Error Finding File';
SZipNoWrite = 'File must be open for writing';
SZipNotSupport = 'Zip Compression Method NOT Support';
SZipInvalidPassword = 'Invalid Password';
SZipNotImplemented = 'Feature NOT Implemented';
SZipUtf8NotSupport = 'UTF8 NOT Support';
SZipInvalideModeSetProp = 'Only zmReadWrite and zmCreate mode can set prop';
SZipInvalidAESExtraField = 'Invalid AES extra field';
SZipDeflateCompressError = 'Deflate compress error: %d';
SZipDeflateDecompressError = 'Deflate decompress error: %d';
SZipCrcError = 'Zip crc error';
type
TZipCompressionHandlerList = TList<TZipCompressionHandlerClass>;
var
FZipCompressionHandlers: TZipCompressionHandlerList = nil;
type
// 默认压缩处理类
// 支持情况:
// 压缩方式: Stored, Deflate
// 加密方式: 传统加密(ZipCrypto), AES
TZipDefaultCompressionHandler = class(TZipCompressionHandlerBase)
public
// 是否支持特定的压缩方法
class function CanHandleCompressionMethod(
const AMethod: TZipCompressionMethod): Boolean; override;
// 创建针对特定输入流的压缩流. 压缩流的概念是, 压缩流有个输出流, 当朝压缩流写入数据时,
// 将自动把压缩后的数据写入输出流. 所以压缩流要实现 Write 方法写明文, 内部压缩加密后写输出流}
class function CreateCompressionStream(
const AMethod: TZipCompressionMethod; const AOutStream: TStream;
const AZipHeader: PZipHeader; const APassword: TBytes;
const ACompressLevel, AStrategy: Integer): TStream; override;
// 创建针对特定输入流的解压缩流. 解压缩流的概念是, 解压缩流有个输入流, 当从解压缩流读数据时,
// 将自动把解压缩后的数据提供出来到 Buffer. 所以解压缩流要实现 Read 方法返回明文, 内部从输入流读并解压缩解密之类的
class function CreateDecompressionStream(
const AMethod: TZipCompressionMethod; const AInStream: TStream;
const AZipHeader: PZipHeader; const APassword: TBytes): TStream; override;
end;
// 存储方式(不压缩)的压缩流与解压缩流
TStoredStream = class(TStream)
private
FOwner: Boolean;
FStream: TStream;
public
constructor Create(const AStream: TStream; const AOwner: Boolean);
destructor Destroy; override;
function Read(var Buffer; Count: Longint): Longint; override;
function Write(const Buffer; Count: Longint): Longint; override;
function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override;
end;
// Deflate压缩/解压流基础类
TCustomDeflateStream = class(TStream)
private
FOwner: Boolean;
FStream: TStream;
FStreamStartPos: Int64;
FStreamPos: Int64;
FZStream: TZStreamRec;
protected class threadvar
FBuffer: array [0..BUF_SIZE-1] of Byte;
public
constructor Create(const AStream: TStream; const AOwner: Boolean);
destructor Destroy; override;
end;
// Deflate压缩流
TDeflateCompressStream = class(TCustomDeflateStream)
public
constructor Create(const AStream: TStream; const AOwner: Boolean;
const ACompressLevel: Integer = Z_DEFAULT_COMPRESSION;
const AWindowBits: Integer = -15;
const AMemLevel: Integer = 8;
const AStrategy: Integer = Z_DEFAULT_STRATEGY);
destructor Destroy; override;
function Read(var Buffer; Count: Longint): Longint; override;
function Write(const Buffer; Count: Longint): Longint; override;
function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override;
end;
// Deflate解压流
TDeflateDecompressStream = class(TCustomDeflateStream)
public
constructor Create(const AStream: TStream; const AOwner: Boolean);
destructor Destroy; override;
function Read(var Buffer; Count: Longint): Longint; override;
function Write(const Buffer; Count: Longint): Longint; override;
function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override;
end;
// zip传统加密类
TZipCrypto = class
private const
// zip传统加密方式要用到的几个密钥
KEY0_INIT: UInt32 = 305419896;
KEY1_INIT: UInt32 = 591751049;
KEY2_INIT: UInt32 = 878082192;
KEY_UPDATE: UInt32 = 134775813;
private
FKey0, FKey1, FKey2: UInt32;
protected
function CalcDecryptByte: UInt8; inline;
public
procedure InitKeys(const APassword: TBytes);
procedure UpdateKeys(const C: UInt8); inline;
procedure DecryptByte(var Value: UInt8); inline;
procedure EncryptByte(var Value: UInt8); inline;
procedure Decrypt(AData: PByte; ASize: Integer);
procedure Encrypt(AData: PByte; ASize: Integer);
end;
// 传统方式解密流(动态解密)
TZipCryptoDecryptStream = class(TStream)
private
FZipStream: TStream;
FZipCrypto: TZipCrypto;
FPosStart, FSize: Int64;
public
constructor Create(const AInStream: TStream; const APassword: TBytes;
const AZipHeader: PZipHeader);
destructor Destroy; override;
function Read(var Buffer; Count: Integer): Integer; override;
function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override;
function Write(const Buffer; Count: Integer): Integer; override; // 可无需实现
end;
// 传统方式加密流(动态加密)
TZipCryptoEncryptStream = class(TStream)
private
FZipStream: TStream;
FZipCrypto: TZipCrypto;
public
constructor Create(const AOutStream: TStream; const APassword: TBytes;
const AZipHeader: PZipHeader);
destructor Destroy; override;
function Read(var Buffer; Count: Integer): Integer; override; // 可无需实现
function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override; // 可无需实现
function Write(const Buffer; Count: Integer): Integer; override;
end;
// aes解密流(动态解密)
TZipAESDecryptStream = class(TStream)
private
FZipStream: TStream;
FPosStart, FSize: Int64;
FCryptNonce: TCnAESBuffer;
FAESCTREncryptor: TAESCTREncryptor;
FSha1Hmac: THashBase;
procedure CheckHmac;
public
constructor Create(const AInStream: TStream; const APassword: TBytes;
const AZipHeader: PZipHeader; const AAESExtraField: TAESExtraField);
destructor Destroy; override;
function Read(var Buffer; Count: Integer): Integer; override;
function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override;
function Write(const Buffer; Count: Integer): Integer; override; // 可无需实现
end;
// aes加密流(动态加密)
TZipAESEncryptStream = class(TStream)
private
FZipStream: TStream;
FCryptNonce: TCnAESBuffer;
FAESCTREncryptor: TAESCTREncryptor;
FSha1Hmac: THashBase;
procedure WriteHmac;
public
constructor Create(const AOutStream: TStream; const APassword: TBytes;
const AZipHeader: PZipHeader; const AAESExtraField: TAESExtraField);
destructor Destroy; override;
function Read(var Buffer; Count: Integer): Integer; override; // 可无需实现
function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override; // 可无需实现
function Write(const Buffer; Count: Integer): Integer; override;
end;
// 计算 CRC32 值
function CRC32Calc(const AOrgCRC32: UInt32; const AData; const ADataSize: UInt32): UInt32; inline;
begin
Result := ZLib.crc32(AOrgCRC32, @AData, ADataSize);
end;
function CalcCRC32Byte(const AOrgCRC32: UInt32; const B: UInt8): UInt32; inline;
begin
Result := not ZLib.crc32(not AOrgCRC32, @B, 1);
end;
// 获取指定ID的扩展字段
function GetExtraField(const AExtraData: TBytes; AFieldId, AFieldLen: Word; AExtra: Pointer): Integer;
var
LOffset: Integer;
LField: ^TZipExtraField;
LCount: Integer;
begin
LOffset := 0;
LCount := Length(AExtraData);
while LOffset + SizeOf(TZipExtraField) <= LCount do
begin
LField := @AExtraData[LOffset];
if LField.FieldId = AFieldId then
begin
Result := LField.FieldLen;
if AExtra <> nil then
begin
if Result < AFieldLen then
AFieldLen := Result;
Move(AExtraData[LOffset + SizeOf(TZipExtraField)], AExtra^, AFieldLen);
end;
Exit;
end;
Inc(LOffset, SizeOf(TZipExtraField) + LField.FieldLen);
end;
Result := 0;
end;
// 删除指定ID的扩展字段
procedure DelExtraField(var AExtraData: TBytes; AFieldId: Word);
var
LOffset: Integer;
LField: ^TZipExtraField;
LCount: Integer;
begin
LOffset := 0;
LCount := Length(AExtraData);
while LOffset + SizeOf(TZipExtraField) <= LCount do
begin
LField := @AExtraData[LOffset];
if LField.FieldId = AFieldId then
begin
Delete(AExtraData, LOffset, SizeOf(TZipExtraField) + LField.FieldLen);
Exit;
end;
Inc(LOffset, SizeOf(TZipExtraField) + LField.FieldLen);
end;
end;
// 设置指定ID的扩展字段
procedure SetExtraField(var AExtraData: TBytes; AFieldId, AFieldLen: Word; AExtra: Pointer);
var
LOffset: Integer;
LField: ^TZipExtraField;
LCount: Integer;
LLen: Integer;
begin
if AFieldLen = 0 then
begin
DelExtraField(AExtraData, AFieldId);
Exit;
end;
LOffset := 0;
LCount := Length(AExtraData);
while LOffset + SizeOf(TZipExtraField) <= LCount do
begin
LField := @AExtraData[LOffset];
LLen := SizeOf(TZipExtraField) + LField.FieldLen;
if LOffset + LLen > LCount then
Exit;
if LField.FieldId = AFieldId then
begin
Inc(LOffset, SizeOf(TZipExtraField));
LLen := Integer(AFieldLen) - LField.FieldLen;
if LLen < 0 then
begin
LField.FieldLen := AFieldLen;
Delete(AExtraData, LOffset, -LLen);
end else
if LLen > 0 then
begin
LField.FieldLen := AFieldLen;
SetLength(AExtraData, Length(AExtraData) + LLen);
Move(AExtraData[LOffset], AExtraData[LOffset + LLen], Length(AExtraData) - LOffset - LLen);
end;
Move(AExtra^, AExtraData[LOffset], AFieldLen);
Exit;
end;
Inc(LOffset, LLen);
end;
LCount := Length(AExtraData);
SetLength(AExtraData, LCount + SizeOf(TZipExtraField) + AFieldLen);
LField := @AExtraData[LCount];
LField.FieldId := AFieldId;
LField.FieldLen := AFieldLen;
Inc(LCount, SizeOf(TZipExtraField));
Move(AExtra^, AExtraData[LCount], AFieldLen);
end;
procedure RegisterZipCompressionHandler(const AClass: TZipCompressionHandlerClass);
begin
if (FZipCompressionHandlers.IndexOf(AClass) < 0) then
FZipCompressionHandlers.Add(AClass);
end;
// 是否支持指定的压缩方式
function SupportCompressionMethod(const AMethod: TZipCompressionMethod): Boolean;
var
I: Integer;
AComp: TZipCompressionHandlerClass;
begin
Result := False;
for I := 0 to FZipCompressionHandlers.Count - 1 do
begin
AComp := TZipCompressionHandlerClass(FZipCompressionHandlers[I]);
if AComp <> nil then
begin
if AComp.CanHandleCompressionMethod(AMethod) then
begin
Result := True;
Exit;
end;
end;
end;
end;
function CreateCompressStreamFromHandler(const AMethod: TZipCompressionMethod;
AOutStream: TStream; const AZipHeader: PZipHeader; const APassword: TBytes;
const ACompressLevel, AStrategy: Integer): TStream;
var
I: Integer;
LComp: TZipCompressionHandlerClass;
begin
Result := nil;
for I := 0 to FZipCompressionHandlers.Count - 1 do
begin
LComp := TZipCompressionHandlerClass(FZipCompressionHandlers[I]);
if LComp <> nil then
begin
if LComp.CanHandleCompressionMethod(AMethod) then
begin
Result := LComp.CreateCompressionStream(
AMethod,
AOutStream,
AZipHeader,
APassword,
ACompressLevel,
AStrategy);
Exit;
end;
end;
end;
end;
function CreateDecompressStreamFromHandler(const AMethod: TZipCompressionMethod;
const AInStream: TStream; const AZipHeader: PZipHeader; const APassword: TBytes): TStream;
var
I: Integer;
LComp: TZipCompressionHandlerClass;
begin
Result := nil;
for I := 0 to FZipCompressionHandlers.Count - 1 do
begin
LComp := TZipCompressionHandlerClass(FZipCompressionHandlers[I]);
if LComp <> nil then
begin
if LComp.CanHandleCompressionMethod(AMethod) then
begin
Result := LComp.CreateDecompressionStream(
AMethod,
AInStream,
AZipHeader,
APassword);
Exit;
end;
end;
end;
end;
function ZipFileIsValid(const AFileName: string): Boolean;
var
LZipHeader: TCrossZip;
LZipStream: TStream;
LZipEndHeader: TZipEndOfCentralHeader;
begin
Result := False;
try
try
LZipHeader := TCrossZip.Create;
LZipStream := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite);
Result := LZipHeader.LocateEndOfCentralHeader(LZipStream, LZipEndHeader);
finally
FreeAndNil(LZipStream);
FreeAndNil(LZipHeader);
end;
except on E: EStreamError do
;
end;
end;
function ZipExtractTo(const AFileName, ADstDir, APassword: string): Boolean;
var
LZip: TCrossZip;
begin
Result := False;
if not FileExists(AFileName) then Exit;
LZip := TCrossZip.Create;
try