├── .gitignore
├── Podfile
├── Podfile.lock
├── README.md
├── Replica.xcodeproj
├── project.pbxproj
└── project.xcworkspace
│ └── contents.xcworkspacedata
├── Replica.xcworkspace
├── contents.xcworkspacedata
└── xcshareddata
│ └── IDEWorkspaceChecks.plist
├── Replica
├── AppDelegate.h
├── AppDelegate.m
├── Assets.xcassets
│ └── AppIcon.appiconset
│ │ ├── Contents.json
│ │ ├── Icon_128x128.png
│ │ ├── Icon_128x128@2x.png
│ │ ├── Icon_16x16.png
│ │ ├── Icon_16x16@2x.png
│ │ ├── Icon_256x256.png
│ │ ├── Icon_256x256@2x.png
│ │ ├── Icon_32x32.png
│ │ ├── Icon_32x32@2x.png
│ │ ├── Icon_512x512.png
│ │ └── Icon_512x512@2x.png
├── Base.lproj
│ └── MainMenu.xib
├── FindBinaryView.h
├── FindBinaryView.m
├── Info.plist
├── MachOUtils.h
├── MachOUtils.m
├── NSFileManager+Replica.h
├── NSFileManager+Replica.m
├── NSOpenPanel+Replica.h
├── NSOpenPanel+Replica.m
├── NSSavePanel+Replica.h
├── NSSavePanel+Replica.m
├── NSTask+Replica.h
├── NSTask+Replica.m
├── OCSP
│ ├── OCSPManager.h
│ ├── OCSPManager.m
│ ├── SecBase64.c
│ ├── SecBase64.h
│ ├── SecCFRelease.h
│ ├── SecDispatchRelease.h
│ ├── SecInternal.h
│ ├── SecOCSPRequest.c
│ ├── SecOCSPRequest.h
│ ├── SecOCSPResponse.c
│ ├── SecOCSPResponse.h
│ ├── asynchttp.c
│ ├── asynchttp.h
│ ├── nameTemplates.h
│ └── ocspTemplates.h
├── Provisioning.h
├── Provisioning.m
├── Replica-Prefix.pch
├── ResignView.h
├── ResignView.m
├── SSZipArchive
│ ├── SSZipArchive.h
│ ├── SSZipArchive.m
│ ├── SSZipCommon.h
│ ├── ZipArchive.h
│ └── minizip
│ │ ├── aes
│ │ ├── aes.h
│ │ ├── aes_ni.c
│ │ ├── aes_ni.h
│ │ ├── aescrypt.c
│ │ ├── aeskey.c
│ │ ├── aesopt.h
│ │ ├── aestab.c
│ │ ├── aestab.h
│ │ ├── brg_endian.h
│ │ ├── brg_types.h
│ │ ├── fileenc.c
│ │ ├── fileenc.h
│ │ ├── hmac.c
│ │ ├── hmac.h
│ │ ├── prng.c
│ │ ├── prng.h
│ │ ├── pwd2key.c
│ │ ├── pwd2key.h
│ │ ├── sha1.c
│ │ └── sha1.h
│ │ ├── crypt.c
│ │ ├── crypt.h
│ │ ├── ioapi.c
│ │ ├── ioapi.h
│ │ ├── ioapi_buf.c
│ │ ├── ioapi_buf.h
│ │ ├── ioapi_mem.c
│ │ ├── ioapi_mem.h
│ │ ├── minishared.c
│ │ ├── minishared.h
│ │ ├── unzip.c
│ │ ├── unzip.h
│ │ ├── zip.c
│ │ └── zip.h
├── ShellExecute.h
├── ShellExecute.m
├── SigningIdentity.h
├── SigningIdentity.m
├── Template.sh
├── VerifyCertView.h
├── VerifyCertView.m
├── en.lproj
│ └── MainMenu.strings
├── main.m
└── optool
│ ├── NSData+Reading.h
│ ├── NSData+Reading.m
│ ├── defines.h
│ ├── headers.h
│ ├── headers.m
│ ├── operations.h
│ └── operations.m
└── ScreenShot
├── QQ20190321-000789@2x.png
├── QQ20190321-000790@2x.png
└── QQ20190321-000792@2x.png
/.gitignore:
--------------------------------------------------------------------------------
1 | # Xcode
2 | .DS_Store
3 | */build/*
4 | *.pbxuser
5 | !default.pbxuser
6 | *.mode1v3
7 | !default.mode1v3
8 | *.mode2v3
9 | !default.mode2v3
10 | *.perspectivev3
11 | !default.perspectivev3
12 | xcuserdata
13 | profile
14 | *.moved-aside
15 | DerivedData
16 | .idea/
17 | *.hmap
18 | *.xccheckout
19 | product/
20 | !iTunesMetadata.plist
21 | !iTunesArtwork
22 | Build/
23 | build/
24 | Packages/
25 | Resources/
26 | LatestBuild/
27 | Pods/
--------------------------------------------------------------------------------
/Podfile:
--------------------------------------------------------------------------------
1 | target :Replica do
2 | pod 'CocoaLumberjack','~> 2.2.0'
3 | end
4 |
--------------------------------------------------------------------------------
/Podfile.lock:
--------------------------------------------------------------------------------
1 | PODS:
2 | - CocoaLumberjack (2.2.0):
3 | - CocoaLumberjack/Default (= 2.2.0)
4 | - CocoaLumberjack/Extensions (= 2.2.0)
5 | - CocoaLumberjack/Core (2.2.0)
6 | - CocoaLumberjack/Default (2.2.0):
7 | - CocoaLumberjack/Core
8 | - CocoaLumberjack/Extensions (2.2.0):
9 | - CocoaLumberjack/Default
10 |
11 | DEPENDENCIES:
12 | - CocoaLumberjack (~> 2.2.0)
13 |
14 | SPEC CHECKSUMS:
15 | CocoaLumberjack: 17fe8581f84914d5d7e6360f7c70022b173c3ae0
16 |
17 | PODFILE CHECKSUM: 717c1e8571afa6adf26d845ec74be126b3b7ab81
18 |
19 | COCOAPODS: 1.0.0
20 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## Replica
2 |
3 | Replica 是 macOS 上一款强大的 IPA 重签工具。
4 |
5 | 自用工具,开发年代久远,代码有点乱,暂时没有重构计划,能用先用。
6 |
7 | 依赖`XCODE`工具链,因为需要用到`codesign`命令行工具进行签名。
8 |
9 | 主要功能:
10 |
11 | * IPA重签名,支持批量处理,提高重签名效率。
12 | * 支持重签时进行越狱包检测,防止非越狱包重签后闪退。
13 | * 支持重签时禁用`ASLR`和移除`__RESTRICT`段。
14 | * 支持增强模式签名,可以对安装包内所有二进制文件签名。
15 | * 支持使用`shell`脚本来对签名过程做额外操作,比如注入动态库,修改资源等等。
16 | * 支持快速查找应用内所有二进制文件。
17 | * 支持快速查询应用签名证书的可用性。
18 |
19 | ## 截图
20 | 
21 | 
22 | 
23 |
24 | ## 感谢
25 | * [ios-app-signer](https://github.com/DanTheMan827/ios-app-signer)
26 | * [optool](https://github.com/alexzielenski/optool)
27 |
--------------------------------------------------------------------------------
/Replica.xcodeproj/project.xcworkspace/contents.xcworkspacedata:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Replica.xcworkspace/contents.xcworkspacedata:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/Replica.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | IDEDidComputeMac32BitWarning
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/Replica/AppDelegate.h:
--------------------------------------------------------------------------------
1 | //
2 | // AppDelegate.h
3 | // Replica
4 | //
5 | // Created by h4ck on 18/11/1.
6 | // Copyright © 2018年 字节时代(https://byteage.com) All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | @interface AppDelegate : NSObject
12 |
13 |
14 | @end
15 |
16 |
--------------------------------------------------------------------------------
/Replica/AppDelegate.m:
--------------------------------------------------------------------------------
1 | //
2 | // AppDelegate.m
3 | // Replica
4 | //
5 | // Created by h4ck on 18/11/1.
6 | // Copyright © 2018年 字节时代(https://byteage.com) All rights reserved.
7 | //
8 |
9 | #import "AppDelegate.h"
10 |
11 | @interface AppDelegate ()
12 |
13 | @property (weak) IBOutlet NSWindow *window;
14 | @end
15 |
16 | @implementation AppDelegate
17 |
18 | - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
19 | // Insert code here to initialize your application
20 | NSDictionary *info = [[NSBundle mainBundle]infoDictionary];
21 | NSString *title = [NSString stringWithFormat:@"Replica %@ (Build %@)",info[@"CFBundleShortVersionString"],info[@"CFBundleVersion"]];
22 | [self.window setTitle:title];
23 | }
24 |
25 | - (void)applicationWillTerminate:(NSNotification *)aNotification {
26 | // Insert code here to tear down your application
27 | }
28 |
29 | - (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender
30 | {
31 | return YES;
32 | }
33 |
34 | @end
35 |
--------------------------------------------------------------------------------
/Replica/Assets.xcassets/AppIcon.appiconset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "filename" : "Icon_16x16.png",
5 | "idiom" : "mac",
6 | "scale" : "1x",
7 | "size" : "16x16"
8 | },
9 | {
10 | "filename" : "Icon_16x16@2x.png",
11 | "idiom" : "mac",
12 | "scale" : "2x",
13 | "size" : "16x16"
14 | },
15 | {
16 | "filename" : "Icon_32x32.png",
17 | "idiom" : "mac",
18 | "scale" : "1x",
19 | "size" : "32x32"
20 | },
21 | {
22 | "filename" : "Icon_32x32@2x.png",
23 | "idiom" : "mac",
24 | "scale" : "2x",
25 | "size" : "32x32"
26 | },
27 | {
28 | "filename" : "Icon_128x128.png",
29 | "idiom" : "mac",
30 | "scale" : "1x",
31 | "size" : "128x128"
32 | },
33 | {
34 | "filename" : "Icon_128x128@2x.png",
35 | "idiom" : "mac",
36 | "scale" : "2x",
37 | "size" : "128x128"
38 | },
39 | {
40 | "filename" : "Icon_256x256.png",
41 | "idiom" : "mac",
42 | "scale" : "1x",
43 | "size" : "256x256"
44 | },
45 | {
46 | "filename" : "Icon_256x256@2x.png",
47 | "idiom" : "mac",
48 | "scale" : "2x",
49 | "size" : "256x256"
50 | },
51 | {
52 | "filename" : "Icon_512x512.png",
53 | "idiom" : "mac",
54 | "scale" : "1x",
55 | "size" : "512x512"
56 | },
57 | {
58 | "filename" : "Icon_512x512@2x.png",
59 | "idiom" : "mac",
60 | "scale" : "2x",
61 | "size" : "512x512"
62 | }
63 | ],
64 | "info" : {
65 | "author" : "xcode",
66 | "version" : 1
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/Replica/Assets.xcassets/AppIcon.appiconset/Icon_128x128.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lemon4ex/Replica/dfd190a3667a47e19b45da4d9492209114073de6/Replica/Assets.xcassets/AppIcon.appiconset/Icon_128x128.png
--------------------------------------------------------------------------------
/Replica/Assets.xcassets/AppIcon.appiconset/Icon_128x128@2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lemon4ex/Replica/dfd190a3667a47e19b45da4d9492209114073de6/Replica/Assets.xcassets/AppIcon.appiconset/Icon_128x128@2x.png
--------------------------------------------------------------------------------
/Replica/Assets.xcassets/AppIcon.appiconset/Icon_16x16.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lemon4ex/Replica/dfd190a3667a47e19b45da4d9492209114073de6/Replica/Assets.xcassets/AppIcon.appiconset/Icon_16x16.png
--------------------------------------------------------------------------------
/Replica/Assets.xcassets/AppIcon.appiconset/Icon_16x16@2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lemon4ex/Replica/dfd190a3667a47e19b45da4d9492209114073de6/Replica/Assets.xcassets/AppIcon.appiconset/Icon_16x16@2x.png
--------------------------------------------------------------------------------
/Replica/Assets.xcassets/AppIcon.appiconset/Icon_256x256.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lemon4ex/Replica/dfd190a3667a47e19b45da4d9492209114073de6/Replica/Assets.xcassets/AppIcon.appiconset/Icon_256x256.png
--------------------------------------------------------------------------------
/Replica/Assets.xcassets/AppIcon.appiconset/Icon_256x256@2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lemon4ex/Replica/dfd190a3667a47e19b45da4d9492209114073de6/Replica/Assets.xcassets/AppIcon.appiconset/Icon_256x256@2x.png
--------------------------------------------------------------------------------
/Replica/Assets.xcassets/AppIcon.appiconset/Icon_32x32.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lemon4ex/Replica/dfd190a3667a47e19b45da4d9492209114073de6/Replica/Assets.xcassets/AppIcon.appiconset/Icon_32x32.png
--------------------------------------------------------------------------------
/Replica/Assets.xcassets/AppIcon.appiconset/Icon_32x32@2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lemon4ex/Replica/dfd190a3667a47e19b45da4d9492209114073de6/Replica/Assets.xcassets/AppIcon.appiconset/Icon_32x32@2x.png
--------------------------------------------------------------------------------
/Replica/Assets.xcassets/AppIcon.appiconset/Icon_512x512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lemon4ex/Replica/dfd190a3667a47e19b45da4d9492209114073de6/Replica/Assets.xcassets/AppIcon.appiconset/Icon_512x512.png
--------------------------------------------------------------------------------
/Replica/Assets.xcassets/AppIcon.appiconset/Icon_512x512@2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lemon4ex/Replica/dfd190a3667a47e19b45da4d9492209114073de6/Replica/Assets.xcassets/AppIcon.appiconset/Icon_512x512@2x.png
--------------------------------------------------------------------------------
/Replica/FindBinaryView.h:
--------------------------------------------------------------------------------
1 | //
2 | // FindBinaryView.h
3 | // Replica
4 | //
5 | // Created by h4ck on 18/11/1.
6 | // Copyright © 2018年 字节时代(https://byteage.com) All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | @interface BinaryInfo : NSObject
12 | @property (nonatomic) NSString *path;
13 | @property (nonatomic) long long size;
14 | @property (nonatomic) BOOL isDecrypted;
15 | @end
16 |
17 | @interface FindBinaryView : NSView
18 |
19 | @end
20 |
--------------------------------------------------------------------------------
/Replica/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | zh_CN
7 | CFBundleExecutable
8 | $(EXECUTABLE_NAME)
9 | CFBundleIconFile
10 |
11 | CFBundleIdentifier
12 | $(PRODUCT_BUNDLE_IDENTIFIER)
13 | CFBundleInfoDictionaryVersion
14 | 6.0
15 | CFBundleName
16 | $(PRODUCT_NAME)
17 | CFBundlePackageType
18 | APPL
19 | CFBundleShortVersionString
20 | $(MARKETING_VERSION)
21 | CFBundleSignature
22 | ????
23 | CFBundleVersion
24 | 43
25 | LSApplicationCategoryType
26 | public.app-category.utilities
27 | LSMinimumSystemVersion
28 | $(MACOSX_DEPLOYMENT_TARGET)
29 | NSHumanReadableCopyright
30 | Copyright © 2018年 字节时代 (https://byteage.com). All rights reserved.
31 | NSMainNibFile
32 | MainMenu
33 | NSPrincipalClass
34 | NSApplication
35 |
36 |
37 |
--------------------------------------------------------------------------------
/Replica/MachOUtils.h:
--------------------------------------------------------------------------------
1 | //
2 | // MachOUtils.h
3 | // Replica
4 | //
5 | // Created by h4ck on 18/11/1.
6 | // Copyright © 2018年 字节时代(https://byteage.com) All rights reserved.
7 | //
8 |
9 | #ifndef MachOUtils_h
10 | #define MachOUtils_h
11 |
12 | #include
13 | #include
14 |
15 | bool isBinaryDecrypted(const char *path);
16 | bool isMachOBinary(const char *path);
17 |
18 | #endif /* MachOUtils_h */
19 |
--------------------------------------------------------------------------------
/Replica/MachOUtils.m:
--------------------------------------------------------------------------------
1 | //
2 | // MachOUtils.c
3 | // Replica
4 | //
5 | // Created by h4ck on 18/11/1.
6 | // Copyright © 2018年 字节时代(https://byteage.com) All rights reserved.
7 | //
8 |
9 | #include "MachOUtils.h"
10 | #include
11 | #include
12 | #include
13 | #include
14 | #include
15 | #include
16 | #include
17 | #include // 大小端交换函数在此
18 | #include // 获取区段相关数据的接口
19 | #include
20 | #include
21 | #include
22 | #include
23 |
24 | // 可以使用mach-o/swap.h里的函数替代
25 | static uint32_t swap32(uint32_t value,uint32_t magic)
26 | {
27 | if (magic == FAT_CIGAM || magic == MH_CIGAM || magic == MH_CIGAM_64) {
28 | return ((value & 0xFF000000) >> 24) | ((value & 0x00FF0000) >> 8) | ((value & 0x0000FF00) << 8) | ((value & 0x000000FF) << 24);
29 | }
30 | return value;
31 | }
32 |
33 | /**
34 | * 判断某个arch是否已经被破解(解密),已破解返回true,否则返回false
35 | */
36 | static bool isArchDecrypted(void *base_addr)
37 | {
38 | struct mach_header *mach_header = (struct mach_header *)base_addr;
39 | // 只处理MH_MAGIC_64类型,其他类型自行处理,注意数据大小端和32/64位程序的头结构体不同。如果是MH_CIGAM的格式,需要注意读取数据时,需将结构体头的数据进行转换(Swap32)才能使用
40 | // __PAGEZERO里的 vmaddr+vmsize = 虚拟地址的基址,其他地方的 虚拟地址 - 虚拟地址的基址 = 文件偏移
41 | if (mach_header->magic == MH_MAGIC_64 || mach_header->magic == MH_CIGAM_64) {
42 | struct mach_header_64 *mach_header_64 = (struct mach_header_64 *)mach_header;
43 | struct load_command *load_cmd = (struct load_command *)(mach_header_64 + 1);
44 | uint32_t ncmds = swap32(mach_header->ncmds,mach_header->magic);
45 | for (uint32_t i = 0; i < ncmds; ++i) {
46 | uint32_t cmd = swap32(load_cmd->cmd,mach_header->magic);
47 | if (cmd == LC_ENCRYPTION_INFO_64) {
48 | struct encryption_info_command_64 *encryption_info_64 = (struct encryption_info_command_64 *)load_cmd;
49 | uint32_t cryptid = swap32(encryption_info_64->cryptid,mach_header->magic);
50 | return cryptid == 0;
51 | }
52 | uint32_t cmd_size = swap32(load_cmd->cmdsize,mach_header->magic);
53 | load_cmd = (struct load_command *)((char *)load_cmd + cmd_size);
54 | }
55 | }
56 | else if(mach_header->magic == MH_MAGIC || mach_header->magic == MH_CIGAM)
57 | {
58 | struct load_command *load_cmd = (struct load_command *)(mach_header + 1);
59 | uint32_t ncmds = swap32(mach_header->ncmds,mach_header->magic);
60 |
61 | for (uint32_t i = 0; i < ncmds; ++i) {
62 | uint32_t cmd = swap32(load_cmd->cmd,mach_header->magic);
63 | if (cmd == LC_ENCRYPTION_INFO) {
64 | struct encryption_info_command *encryption_info_64 = (struct encryption_info_command *)load_cmd;
65 | uint32_t cryptid = swap32(encryption_info_64->cryptid,mach_header->magic);
66 | return cryptid == 0;
67 | }
68 | uint32_t cmd_size = swap32(load_cmd->cmdsize,mach_header->magic);
69 | load_cmd = (struct load_command *)((char *)load_cmd + cmd_size);
70 | }
71 | }
72 | return true;
73 | }
74 |
75 | bool isMachOBinary(const char *path)
76 | {
77 | int fd = open(path, O_RDWR);
78 | if (fd == -1) {
79 | return false;
80 | }
81 | bool isBin = false;
82 |
83 | do {
84 | struct stat stat;
85 | fstat(fd, &stat);
86 | if (stat.st_size < sizeof(uint32_t)) {
87 | break;
88 | }
89 |
90 | uint32_t magic;
91 | read(fd, &magic, sizeof(magic));
92 | if (magic == FAT_CIGAM || magic == MH_CIGAM || magic == MH_CIGAM_64||
93 | magic == FAT_MAGIC || magic == MH_MAGIC || magic == MH_MAGIC_64) {
94 | isBin = true;
95 | }
96 | } while (0);
97 | close(fd);
98 | return isBin;
99 | }
100 |
101 | /**
102 | * 判断二进制文件是否被破解(解密),已破解返回true,否则返回false
103 | */
104 | bool isBinaryDecrypted(const char *path)
105 | {
106 | int fd = open(path, O_RDWR);
107 | if (fd == -1) {
108 | return true;
109 | }
110 | bool isDecrypted = true;
111 | do {
112 | struct stat stat;
113 | fstat(fd, &stat);
114 | if (stat.st_size < sizeof(uint32_t)) {
115 | break;
116 | }
117 |
118 | uint32_t magic;
119 | read(fd, &magic, sizeof(magic));
120 | if (magic == FAT_CIGAM || magic == MH_CIGAM || magic == MH_CIGAM_64||
121 | magic == FAT_MAGIC || magic == MH_MAGIC || magic == MH_MAGIC_64) {
122 | void *base = mmap(0, stat.st_size, PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED, fd, 0);
123 | uint32_t magic = (*(uint32_t *)base);
124 | if(magic == FAT_MAGIC || magic == FAT_CIGAM)
125 | {
126 | struct fat_header *fat_header = (struct fat_header *)base;
127 | uint32_t archs = swap32(fat_header->nfat_arch,fat_header->magic);
128 | for (uint32_t i = 0; i < archs; ++i) {
129 | struct fat_arch *arch = (struct fat_arch *)((char *)base + sizeof(struct fat_header) + sizeof(struct fat_arch) * i);
130 | uint32_t offset = swap32(arch->offset,magic);
131 | isDecrypted = isArchDecrypted((char *)base + offset);
132 | if(!isDecrypted) break;
133 | }
134 | }
135 | else
136 | {
137 | isDecrypted = isArchDecrypted(base);
138 | }
139 | munmap(base, stat.st_size);
140 | }
141 | } while (0);
142 | close(fd);
143 |
144 | return isDecrypted;
145 | }
146 |
--------------------------------------------------------------------------------
/Replica/NSFileManager+Replica.h:
--------------------------------------------------------------------------------
1 | //
2 | // NSFileManager+Replica.h
3 | // Replica
4 | //
5 | // Created by h4ck on 18/11/1.
6 | // Copyright © 2018年 字节时代(https://byteage.com) All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | typedef BOOL (^FindRuleBlock)(NSString *path,BOOL isDirectory);
12 | typedef BOOL (^FoundFileBlock)(NSString *path,BOOL isDirectory);
13 |
14 | @interface NSFileManager (Replica)
15 | + (BOOL)recursiveDirectorySearch:(NSString *)path findRuleBlock:(FindRuleBlock)findRuleBlock foundFileBlock:(FoundFileBlock)foundFileBlock;
16 | + (BOOL)recursiveDirectorySearch:(NSString *)path extensions:(NSArray *)extensions specificFiles:(NSArray *)specificFiles foundFileBlock:(FoundFileBlock)foundFileBlock;
17 | @end
18 |
--------------------------------------------------------------------------------
/Replica/NSFileManager+Replica.m:
--------------------------------------------------------------------------------
1 | //
2 | // NSFileManager+Replica.m
3 | // Replica
4 | //
5 | // Created by h4ck on 18/11/1.
6 | // Copyright © 2018年 字节时代(https://byteage.com) All rights reserved.
7 | //
8 |
9 | #import "NSFileManager+Replica.h"
10 |
11 | @implementation NSFileManager (Replica)
12 |
13 | + (BOOL)recursiveDirectorySearch:(NSString *)path findRuleBlock:(FindRuleBlock)findRuleBlock foundFileBlock:(FoundFileBlock)foundFileBlock{
14 | NSFileManager *fileManager = [self defaultManager];
15 | NSArray *files = [fileManager contentsOfDirectoryAtPath:path error:nil];
16 | BOOL isDirectory = YES;
17 | for (NSString *file in files) {
18 | NSString *currentFile = [path stringByAppendingPathComponent:file];
19 | BOOL exist = [fileManager fileExistsAtPath:currentFile isDirectory:&isDirectory];
20 |
21 | if(!exist) continue;
22 |
23 | if (isDirectory) {
24 | if (![self recursiveDirectorySearch:currentFile findRuleBlock:findRuleBlock foundFileBlock:foundFileBlock]) {
25 | return NO;
26 | }
27 | }
28 |
29 | if (findRuleBlock && !findRuleBlock(currentFile, isDirectory)) {
30 | continue;
31 | }
32 |
33 | if(foundFileBlock && !foundFileBlock(currentFile, isDirectory))
34 | {
35 | return NO;
36 | }
37 | }
38 |
39 | return YES;
40 | }
41 |
42 | + (BOOL)recursiveDirectorySearch:(NSString *)path extensions:(NSArray *)extensions specificFiles:(NSArray *)specificFiles foundFileBlock:(FoundFileBlock)foundFileBlock{
43 | return [self recursiveDirectorySearch:path findRuleBlock:^BOOL(NSString *filePath, BOOL isDirectory) {
44 | NSString *fileName = filePath.lastPathComponent;
45 | if ([extensions containsObject:fileName.pathExtension] || [specificFiles containsObject:fileName])
46 | {
47 | return YES;
48 | }
49 | return NO;
50 | } foundFileBlock:foundFileBlock];
51 | }
52 | @end
53 |
--------------------------------------------------------------------------------
/Replica/NSOpenPanel+Replica.h:
--------------------------------------------------------------------------------
1 | //
2 | // NSOpenPanel+Replica.h
3 | // Replica
4 | //
5 | // Created by h4ck on 18/11/3.
6 | // Copyright © 2018年 字节时代(https://byteage.com) All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | @interface NSOpenPanel (Replica)
12 | + (void)showOpenPanelModal:(NSString *)directory message:(NSString *)message fileTypes:(NSArray *)fileTypes multipleSelection:(BOOL)multipleSelection canChooseDirectories:(BOOL)canChooseDirectories canChooseFiles:(BOOL)canChooseFiles canCreateDirectories:(BOOL)canCreateDirectories completionHandler:(void (^)(NSOpenPanel *panel,NSInteger result))completionHandler;
13 | @end
14 |
--------------------------------------------------------------------------------
/Replica/NSOpenPanel+Replica.m:
--------------------------------------------------------------------------------
1 | //
2 | // NSOpenPanel+Replica.m
3 | // Replica
4 | //
5 | // Created by h4ck on 18/11/3.
6 | // Copyright © 2018年 字节时代(https://byteage.com) All rights reserved.
7 | //
8 |
9 | #import "NSOpenPanel+Replica.h"
10 |
11 | @implementation NSOpenPanel (Replica)
12 | + (void)showOpenPanelModal:(NSString *)directory message:(NSString *)message fileTypes:(NSArray *)fileTypes multipleSelection:(BOOL)multipleSelection canChooseDirectories:(BOOL)canChooseDirectories canChooseFiles:(BOOL)canChooseFiles canCreateDirectories:(BOOL)canCreateDirectories completionHandler:(void (^)(NSOpenPanel *panel,NSInteger result))completionHandler
13 | {
14 | NSOpenPanel *panel = [NSOpenPanel openPanel];
15 | [panel setDirectory:directory];
16 | panel.message = message;
17 | [panel setAllowsMultipleSelection:multipleSelection];
18 | [panel setCanChooseDirectories:canChooseDirectories];
19 | [panel setCanChooseFiles:canChooseFiles];
20 | [panel setAllowedFileTypes:fileTypes];
21 | [panel setAllowsOtherFileTypes:NO];
22 | [panel setCanCreateDirectories:canCreateDirectories];
23 | NSInteger result = [panel runModal];
24 | completionHandler(panel,result);
25 | }
26 | @end
27 |
--------------------------------------------------------------------------------
/Replica/NSSavePanel+Replica.h:
--------------------------------------------------------------------------------
1 | //
2 | // NSSavePanel+Replica.h
3 | // Replica
4 | //
5 | // Created by h4ck on 18/11/3.
6 | // Copyright © 2018年 字节时代(https://byteage.com) All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | @interface NSSavePanel (Replica)
12 | + (void)showSavePanelModal:(NSString *)nameValue message:(NSString *)message fileTypes:(NSArray *)fileTypes canCreateDirectories:(BOOL)canCreateDirectories completionHandler:(void (^)(NSSavePanel *panel,NSInteger result))completionHandler;
13 | @end
14 |
--------------------------------------------------------------------------------
/Replica/NSSavePanel+Replica.m:
--------------------------------------------------------------------------------
1 | //
2 | // NSSavePanel+Replica.m
3 | // Replica
4 | //
5 | // Created by h4ck on 18/11/3.
6 | // Copyright © 2018年 字节时代(https://byteage.com) All rights reserved.
7 | //
8 |
9 | #import "NSSavePanel+Replica.h"
10 |
11 | @implementation NSSavePanel (Replica)
12 | + (void)showSavePanelModal:(NSString *)nameValue message:(NSString *)message fileTypes:(NSArray *)fileTypes canCreateDirectories:(BOOL)canCreateDirectories completionHandler:(void (^)(NSSavePanel *panel,NSInteger result))completionHandler
13 | {
14 | NSSavePanel *panel = [NSSavePanel savePanel];
15 | [panel setNameFieldStringValue:nameValue];
16 | [panel setMessage:message];
17 | [panel setAllowsOtherFileTypes:NO];
18 | [panel setAllowedFileTypes:fileTypes];
19 | [panel setExtensionHidden:NO];
20 | [panel setCanCreateDirectories:canCreateDirectories];
21 | NSInteger result = [panel runModal];
22 | completionHandler(panel,result);
23 | }
24 | @end
25 |
--------------------------------------------------------------------------------
/Replica/NSTask+Replica.h:
--------------------------------------------------------------------------------
1 | //
2 | // NSTask+Replica.h
3 | // Replica
4 | //
5 | // Created by h4ck on 18/11/1.
6 | // Copyright © 2018年 字节时代(https://byteage.com) All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | @interface RETaskOutput : NSObject
12 | @property (nonatomic) NSInteger status;
13 | @property (nonatomic) NSString *output;
14 | @end
15 |
16 | @interface NSTask (Replica)
17 | - (RETaskOutput *)launchSyncronous;
18 | + (RETaskOutput *)execute:(NSString *)launchPath workingDirectory:(NSString *)workingDirectory arguments:(NSArray *)arguments;
19 | @end
20 |
--------------------------------------------------------------------------------
/Replica/NSTask+Replica.m:
--------------------------------------------------------------------------------
1 | //
2 | // NSTask+Replica.m
3 | // Replica
4 | //
5 | // Created by h4ck on 18/11/1.
6 | // Copyright © 2018年 字节时代(https://byteage.com) All rights reserved.
7 | //
8 |
9 | #import "NSTask+Replica.h"
10 |
11 | @implementation RETaskOutput
12 |
13 |
14 | @end
15 |
16 | @implementation NSTask (Replica)
17 | - (RETaskOutput *)launchSyncronous {
18 | self.standardInput = [NSFileHandle fileHandleWithNullDevice];
19 | NSPipe *pipe = [NSPipe pipe];
20 | self.standardOutput = pipe;
21 | self.standardError = pipe;
22 | NSFileHandle *readingPipeFile = [pipe fileHandleForReading];
23 | [self launch];
24 |
25 | NSMutableData *data = [NSMutableData data];
26 | while([self isRunning]) {
27 | [data appendData:readingPipeFile.availableData];
28 | }
29 |
30 | [readingPipeFile closeFile];
31 | [self terminate];
32 | NSString *output = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
33 | NSInteger status = self.terminationStatus;
34 | RETaskOutput *taskOutput = [[RETaskOutput alloc]init];
35 | taskOutput.status = status;
36 | taskOutput.output = output;
37 | return taskOutput;
38 | }
39 |
40 | + (RETaskOutput *)execute:(NSString *)launchPath workingDirectory:(NSString *)workingDirectory arguments:(NSArray *)arguments{
41 | NSTask *task = [[NSTask alloc]init];
42 | task.launchPath = launchPath;
43 | if (arguments) {
44 | task.arguments = arguments;
45 | }
46 | if (workingDirectory) {
47 | task.currentDirectoryPath = workingDirectory;
48 | }
49 | return [task launchSyncronous];
50 | }
51 | @end
52 |
--------------------------------------------------------------------------------
/Replica/OCSP/OCSPManager.h:
--------------------------------------------------------------------------------
1 | //
2 | // OCSPManager.h
3 | // OCSPDemo
4 | //
5 | // Created by zeejun on 14-8-14.
6 | // Copyright (c) 2014年 zeejun. All rights reserved.
7 | //
8 |
9 | #import
10 | #include "ocspTemplates.h"
11 |
12 | @interface CertStatusItem : NSObject
13 |
14 | @property(nonatomic, strong) NSString *appName;
15 | @property(nonatomic, strong) NSString *certID;
16 | @property(nonatomic, strong) NSString *commonName;
17 | @property(nonatomic, assign) NSInteger certStatus;
18 | @property(nonatomic, strong) NSString *thisUpdate;
19 | @property(nonatomic, strong) NSString *revokedTime;
20 | @property(nonatomic, assign) NSInteger revocationReason;
21 |
22 | - (NSString *)certStatusToString;
23 | - (NSString *)revocationReasonToString;
24 |
25 | @end
26 |
27 | typedef void (^CertRevocationCompleteHandle)(CertStatusItem *statusItem,NSError *error);
28 |
29 | @interface OCSPManager : NSObject
30 |
31 | + (instancetype)share;
32 |
33 | - (NSDictionary *)mobileProvisionWithFile:(NSString *)file;
34 |
35 | - (void)checkRevocationWtihPath:(NSString *)filePath completeHandle:(CertRevocationCompleteHandle)completeHandle;
36 |
37 | - (void)sendCertStatusToServer:(CertStatusItem *)statusItem completionHandler:(void (^)(NSData *data, id info))handler;
38 |
39 | @end
40 |
--------------------------------------------------------------------------------
/Replica/OCSP/SecCFRelease.h:
--------------------------------------------------------------------------------
1 | //
2 | // SecCFRelease.h
3 | // utilities
4 | //
5 | // Created by Mitch Adler on 2/9/12.
6 | // Copyright (c) 2012 Apple Inc. All rights reserved.
7 | //
8 |
9 | #ifndef _SECCFRELEASE_H_
10 | #define _SECCFRELEASE_H_
11 |
12 | #include
13 |
14 | #define CFRetainSafe(CF) { \
15 | CFTypeRef _cf = (CF); \
16 | if (_cf) \
17 | CFRetain(_cf); \
18 | }
19 |
20 | #define CFReleaseSafe(CF) { \
21 | CFTypeRef _cf = (CF); \
22 | if (_cf) \
23 | CFRelease(_cf); \
24 | }
25 |
26 | #define CFReleaseNull(CF) { \
27 | CFTypeRef _cf = (CF); \
28 | if (_cf) { \
29 | (CF) = NULL; \
30 | CFRelease(_cf); \
31 | } \
32 | }
33 |
34 | #endif
35 |
--------------------------------------------------------------------------------
/Replica/OCSP/SecDispatchRelease.h:
--------------------------------------------------------------------------------
1 | //
2 | // SecDispatchRelease.h
3 | // utilities
4 | //
5 | // Created by Mitch Adler on 11/26/12.
6 | // Copyright (c) 2012 Apple Inc. All rights reserved.
7 | //
8 |
9 |
10 | #ifndef _SECDISPATCHRELEASE_H_
11 | #define _SECDISPATCHRELEASE_H_
12 |
13 | #include
14 | #include
15 |
16 | #define dispatch_retain_safe(DO) { \
17 | __typeof__(DO) _do = (DO); \
18 | if (_do) \
19 | dispatch_retain(_do); \
20 | }
21 |
22 | #define dispatch_release_safe(DO) { \
23 | __typeof__(DO) _do = (DO); \
24 | if (_do) \
25 | dispatch_release(_do); \
26 | }
27 |
28 | #define dispatch_release_null(DO) { \
29 | __typeof__(DO) _do = (DO); \
30 | if (_do) { \
31 | (DO) = NULL; \
32 | dispatch_release(_do); \
33 | } \
34 | }
35 |
36 |
37 | #define xpc_retain_safe(XO) { \
38 | __typeof__(XO) _xo = (XO); \
39 | if (_xo) \
40 | xpc_retain(_xo); \
41 | }
42 |
43 | #define xpc_release_safe(XO) { \
44 | __typeof__(XO) _xo = (XO); \
45 | if (_xo) \
46 | xpc_release(_xo); \
47 | }
48 |
49 | #define xpc_release_null(XO) { \
50 | __typeof__(XO) _xo = (XO); \
51 | if (_xo) { \
52 | (XO) = NULL; \
53 | xpc_release(_xo); \
54 | } \
55 | }
56 |
57 | #endif
58 |
59 |
--------------------------------------------------------------------------------
/Replica/OCSP/SecInternal.h:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2007,2009-2010 Apple Inc. All Rights Reserved.
3 | *
4 | * @APPLE_LICENSE_HEADER_START@
5 | *
6 | * This file contains Original Code and/or Modifications of Original Code
7 | * as defined in and that are subject to the Apple Public Source License
8 | * Version 2.0 (the 'License'). You may not use this file except in
9 | * compliance with the License. Please obtain a copy of the License at
10 | * http://www.opensource.apple.com/apsl/ and read it before using this
11 | * file.
12 | *
13 | * The Original Code and all software distributed under the License are
14 | * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 | * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 | * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 | * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 | * Please see the License for the specific language governing rights and
19 | * limitations under the License.
20 | *
21 | * @APPLE_LICENSE_HEADER_END@
22 | */
23 |
24 | /*!
25 | @header SecInternal
26 | SecInternal defines common internal constants macros and SPI functions.
27 | */
28 |
29 | #ifndef _SECURITY_SECINTERNAL_H_
30 | #define _SECURITY_SECINTERNAL_H_
31 |
32 | #include
33 | #include
34 | #include
35 |
36 | //#include "utilities/SecCFRelease.h"
37 |
38 |
39 | #define NULL_TIME 0.0
40 |
41 |
42 | static inline CFIndex getIntValue(CFTypeRef cf) {
43 | if (cf) {
44 | if (CFGetTypeID(cf) == CFNumberGetTypeID()) {
45 | CFIndex value;
46 | CFNumberGetValue(cf, kCFNumberCFIndexType, &value);
47 | return value;
48 | } else if (CFGetTypeID(cf) == CFStringGetTypeID()) {
49 | return CFStringGetIntValue(cf);
50 | }
51 | }
52 | return -1;
53 | }
54 |
55 | __END_DECLS
56 |
57 | #endif /* !_SECURITY_SECINTERNAL_H_ */
58 |
--------------------------------------------------------------------------------
/Replica/OCSP/SecOCSPRequest.c:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2008-2009 Apple Inc. All Rights Reserved.
3 | *
4 | * @APPLE_LICENSE_HEADER_START@
5 | *
6 | * This file contains Original Code and/or Modifications of Original Code
7 | * as defined in and that are subject to the Apple Public Source License
8 | * Version 2.0 (the 'License'). You may not use this file except in
9 | * compliance with the License. Please obtain a copy of the License at
10 | * http://www.opensource.apple.com/apsl/ and read it before using this
11 | * file.
12 | *
13 | * The Original Code and all software distributed under the License are
14 | * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 | * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 | * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 | * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 | * Please see the License for the specific language governing rights and
19 | * limitations under the License.
20 | *
21 | * @APPLE_LICENSE_HEADER_END@
22 | */
23 |
24 | /*
25 | * SecOCSPRequest.c - Trust policies dealing with certificate revocation.
26 | */
27 |
28 | #include "SecOCSPRequest.h"
29 | #include
30 |
31 | #include
32 |
33 | #include
34 | #include "SecInternal.h"
35 | #include "ocspTemplates.h"
36 | //#include
37 | #include
38 | #include "SecCFRelease.h"
39 |
40 | #define OID_OIW_LENGTH 2
41 | #define OID_OIW_SECSIG_LENGTH OID_OIW_LENGTH +1
42 |
43 |
44 | //static const uint8_t OID_OIW_SHA1[] = { OID_OIW_ALGORITHM, 26 };
45 | //static const uint8_t CSSMOID_SHA1 = {OID_OIW_ALGORITHM_LENGTH+1, (uint8_t *)OID_OIW_SHA1};
46 |
47 | //extern CFDataRef SecCertificateCopyPublicKeySHA1Digest(SecCertificateRef certificate);
48 | //extern CFDataRef SecCertificateCopyIssuerSHA1Digest(SecCertificateRef certificate);
49 | //
50 |
51 | /*
52 | OCSPRequest ::= SEQUENCE {
53 | tbsRequest TBSRequest,
54 | optionalSignature [0] EXPLICIT Signature OPTIONAL }
55 |
56 | TBSRequest ::= SEQUENCE {
57 | version [0] EXPLICIT Version DEFAULT v1,
58 | requestorName [1] EXPLICIT GeneralName OPTIONAL,
59 | requestList SEQUENCE OF Request,
60 | requestExtensions [2] EXPLICIT Extensions OPTIONAL }
61 |
62 | Signature ::= SEQUENCE {
63 | signatureAlgorithm AlgorithmIdentifier,
64 | signature BIT STRING,
65 | certs [0] EXPLICIT SEQUENCE OF Certificate
66 | OPTIONAL}
67 |
68 | Version ::= INTEGER { v1(0) }
69 |
70 | Request ::= SEQUENCE {
71 | reqCert CertID,
72 | singleRequestExtensions [0] EXPLICIT Extensions OPTIONAL }
73 |
74 | CertID ::= SEQUENCE {
75 | hashAlgorithm AlgorithmIdentifier,
76 | issuerNameHash OCTET STRING, -- Hash of Issuer's DN
77 | issuerKeyHash OCTET STRING, -- Hash of Issuers public key
78 | serialNumber CertificateSerialNumber }
79 | */
80 |
81 | static CFDataRef _SecOCSPRequestCopyDEREncoding(SecOCSPRequestRef this) {
82 | /* fields obtained from issuer */
83 | SecAsn1OCSPSignedRequest signedReq = {};
84 | SecAsn1OCSPTbsRequest *tbs = &signedReq.tbsRequest;
85 | SecAsn1OCSPRequest singleReq = {};
86 | SecAsn1OCSPCertID *certId = &singleReq.reqCert;
87 | SecAsn1OCSPRequest *reqArray[2] = { &singleReq, NULL };
88 | uint8_t version = 0;
89 | SecAsn1Item vers = {1, &version};
90 | CFDataRef der = NULL;
91 | SecAsn1CoderRef coder = NULL;
92 | CFDataRef issuerNameDigest;
93 | CFDataRef serial;
94 | CFDataRef issuerPubKeyDigest;
95 |
96 |
97 | /* algId refers to the hash we'll perform in issuer name and key */
98 | certId->algId.algorithm = CSSMOID_SHA1;
99 | /* preencoded DER NULL */
100 | static uint8_t nullParam[2] = {5, 0};
101 | certId->algId.parameters.Data = nullParam;
102 | certId->algId.parameters.Length = sizeof(nullParam);
103 |
104 | /* @@@ Change this from using SecCertificateCopyIssuerSHA1Digest() /
105 | SecCertificateCopyPublicKeySHA1Digest() to
106 | SecCertificateCopyIssuerSequence() / SecCertificateGetPublicKeyData()
107 | and call SecDigestCreate here instead. */
108 | // issuerNameDigest = SecCertificateCopyIssuerSHA1Digest(this->certificate);
109 | serial = SecCertificateCopySerialNumber(this->certificate,NULL);
110 | // issuerPubKeyDigest = SecCertificateCopyPublicKeySHA1Digest(this->issuer);
111 |
112 | /* build the CertID from those components */
113 | certId->issuerNameHash.Length = CC_SHA1_DIGEST_LENGTH;
114 | certId->issuerNameHash.Data = (uint8_t *)CFDataGetBytePtr(issuerNameDigest);
115 | certId->issuerPubKeyHash.Length = CC_SHA1_DIGEST_LENGTH;
116 | certId->issuerPubKeyHash.Data = (uint8_t *)CFDataGetBytePtr(issuerPubKeyDigest);
117 | certId->serialNumber.Length = CFDataGetLength(serial);
118 | certId->serialNumber.Data = (uint8_t *)CFDataGetBytePtr(serial);
119 |
120 | /* Build top level request with one entry in requestList, no signature,
121 | and no optional extensions. */
122 | tbs->version = &vers;
123 | tbs->requestList = reqArray;
124 |
125 | /* Encode the request. */
126 | SecAsn1CoderCreate(&coder);
127 | SecAsn1Item encoded;
128 | SecAsn1EncodeItem(coder, &signedReq,
129 | kSecAsn1OCSPSignedRequestTemplate, &encoded);
130 | der = CFDataCreate(kCFAllocatorDefault, encoded.Data,
131 | encoded.Length);
132 |
133 | errOut:
134 | if (coder)
135 | SecAsn1CoderRelease(coder);
136 | CFReleaseSafe(issuerNameDigest);
137 | CFReleaseSafe(serial);
138 | CFReleaseSafe(issuerPubKeyDigest);
139 |
140 | return der;
141 | }
142 |
143 | SecOCSPRequestRef SecOCSPRequestCreate(SecCertificateRef certificate,
144 | SecCertificateRef issuer) {
145 | SecOCSPRequestRef this;
146 | this = (SecOCSPRequestRef)calloc(1, sizeof(struct __SecOCSPRequest));
147 | this->certificate = certificate;
148 | this->issuer = issuer;
149 |
150 | return this;
151 | errOut:
152 | if (this) {
153 | SecOCSPRequestFinalize(this);
154 | }
155 | return NULL;
156 | }
157 |
158 | CFDataRef SecOCSPRequestGetDER(SecOCSPRequestRef this) {
159 | CFDataRef der = this->der;
160 | if (!der) {
161 | this->der = der = _SecOCSPRequestCopyDEREncoding(this);
162 | }
163 | return der;
164 | }
165 |
166 | void SecOCSPRequestFinalize(SecOCSPRequestRef this) {
167 | CFReleaseSafe(this->der);
168 | free(this);
169 | }
170 |
171 |
--------------------------------------------------------------------------------
/Replica/OCSP/SecOCSPRequest.h:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2009 Apple Inc. All Rights Reserved.
3 | *
4 | * @APPLE_LICENSE_HEADER_START@
5 | *
6 | * This file contains Original Code and/or Modifications of Original Code
7 | * as defined in and that are subject to the Apple Public Source License
8 | * Version 2.0 (the 'License'). You may not use this file except in
9 | * compliance with the License. Please obtain a copy of the License at
10 | * http://www.opensource.apple.com/apsl/ and read it before using this
11 | * file.
12 | *
13 | * The Original Code and all software distributed under the License are
14 | * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 | * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 | * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 | * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 | * Please see the License for the specific language governing rights and
19 | * limitations under the License.
20 | *
21 | * @APPLE_LICENSE_HEADER_END@
22 | */
23 |
24 | /*!
25 | @header SecOCSPRequest
26 | The functions and data types in SecOCSPRequest implement ocsp request
27 | creation.
28 | */
29 |
30 | #ifndef _SECURITY_SECOCSPREQUEST_H_
31 | #define _SECURITY_SECOCSPREQUEST_H_
32 |
33 | #include
34 | #include
35 |
36 | __BEGIN_DECLS
37 |
38 | /*!
39 | @typedef SecOCSPRequestRef
40 | @abstract Object used for ocsp response decoding.
41 | */
42 | typedef struct __SecOCSPRequest *SecOCSPRequestRef;
43 |
44 | struct __SecOCSPRequest {
45 | SecCertificateRef certificate; // Nonretained
46 | SecCertificateRef issuer; // Nonretained
47 | CFDataRef der;
48 | };
49 |
50 | /*!
51 | @function SecOCSPRequestCreate
52 | @abstract Returns a SecOCSPRequestRef from a BER encoded ocsp response.
53 | @param certificate The certificate for which we want a OCSP request created.
54 | @param issuer The parent of certificate.
55 | @result A SecOCSPRequestRef.
56 | */
57 | SecOCSPRequestRef SecOCSPRequestCreate(SecCertificateRef certificate,
58 | SecCertificateRef issuer);
59 |
60 | /*!
61 | @function SecOCSPRequestCopyDER
62 | @abstract Returns a DER encoded ocsp request.
63 | @param ocspRequest A SecOCSPRequestRef.
64 | @result DER encoded ocsp request.
65 | */
66 | CFDataRef SecOCSPRequestGetDER(SecOCSPRequestRef ocspRequest);
67 |
68 | /*!
69 | @function SecOCSPRequestFinalize
70 | @abstract Frees a SecOCSPRequestRef.
71 | @param ocspRequest A SecOCSPRequestRef.
72 | @result The passed in SecOCSPRequestRef is deallocated
73 | */
74 | void SecOCSPRequestFinalize(SecOCSPRequestRef ocspRequest);
75 |
76 | __END_DECLS
77 |
78 | #endif /* !_SECURITY_SECOCSPREQUEST_H_ */
79 |
--------------------------------------------------------------------------------
/Replica/OCSP/SecOCSPResponse.h:
--------------------------------------------------------------------------------
1 | //
2 | // SecOCSPSingleResponse.h
3 | // OCSPDemo
4 | //
5 | // Created by zeejun on 14-8-12.
6 | // Copyright (c) 2014年 zeejun. All rights reserved.
7 | //
8 |
9 | #ifndef OCSPDemo_SecOCSPSingleResponse_h
10 | #define OCSPDemo_SecOCSPSingleResponse_h
11 |
12 | #include
13 | #include
14 | #include
15 |
16 | #include "ocspTemplates.h"
17 |
18 | typedef enum {
19 | kSecOCSPBad = -2,
20 | kSecOCSPUnknown = -1,
21 | kSecOCSPSuccess = 0,
22 | kSecOCSPMalformedRequest = 1,
23 | kSecOCSPInternalError = 2,
24 | kSecOCSPTryLater = 3,
25 | kSecOCSPUnused = 4,
26 | kSecOCSPSigRequired = 5,
27 | kSecOCSPUnauthorized = 6
28 | } SecOCSPResponseStatus;
29 |
30 | enum {
31 | kSecRevocationReasonUnrevoked = -2,
32 | kSecRevocationReasonUndetermined = -1,
33 | kSecRevocationReasonUnspecified = 0,
34 | kSecRevocationReasonKeyCompromise = 1,
35 | kSecRevocationReasonCACompromise = 2,
36 | kSecRevocationReasonAffiliationChanged = 3,
37 | kSecRevocationReasonSuperseded = 4,
38 | kSecRevocationReasonCessationOfOperation = 5,
39 | kSecRevocationReasonCertificateHold = 6,
40 | /* -- value 7 is not used */
41 | kSecRevocationReasonRemoveFromCRL = 8,
42 | kSecRevocationReasonPrivilegeWithdrawn = 9,
43 | kSecRevocationReasonAACompromise = 10
44 | };
45 | typedef int32_t SecRevocationReason;
46 |
47 |
48 |
49 |
50 | /*!
51 | @typedef SecOCSPResponseRef
52 | @abstract Object used for ocsp response decoding.
53 | */
54 | typedef struct __SecOCSPResponse *SecOCSPResponseRef;
55 |
56 | struct __SecOCSPResponse {
57 | CFDataRef data;
58 | SecAsn1CoderRef coder;
59 | SecOCSPResponseStatus responseStatus;
60 | CFDataRef nonce;
61 | CFAbsoluteTime producedAt;
62 | CFAbsoluteTime latestNextUpdate;
63 | CFAbsoluteTime expireTime;
64 | CFAbsoluteTime verifyTime;
65 | SecAsn1OCSPBasicResponse basicResponse;
66 | SecAsn1OCSPResponseData responseData;
67 | SecAsn1OCSPResponderIDTag responderIdTag;
68 | SecAsn1OCSPResponderID responderID;
69 | };
70 |
71 |
72 | typedef struct __SecOCSPSingleResponse *SecOCSPSingleResponseRef;
73 |
74 | struct __SecOCSPSingleResponse {
75 | SecAsn1OCSPCertStatusTag certStatus;
76 | CFAbsoluteTime thisUpdate;
77 | CFAbsoluteTime nextUpdate; /* may be NULL_TIME */
78 | CFAbsoluteTime revokedTime; /* != NULL_TIME for certStatus == CS_Revoked */
79 | SecRevocationReason crlReason;
80 | //OCSPExtensions *extensions;
81 | };
82 |
83 |
84 | /*!
85 | @function SecOCSPResponseCreate
86 | @abstract Returns a SecOCSPResponseRef from a BER encoded ocsp response.
87 | @param berResponse The BER encoded ocsp response.
88 | @result A SecOCSPResponseRef.
89 | */
90 | SecOCSPResponseRef SecOCSPResponseCreate(CFDataRef ocspResponse,
91 | CFTimeInterval maxAge);
92 |
93 | CFDataRef SecOCSPResponseGetData(SecOCSPResponseRef this);
94 |
95 | SecOCSPResponseStatus SecOCSPGetResponseStatus(SecOCSPResponseRef ocspResponse);
96 |
97 | CFAbsoluteTime SecOCSPResponseGetExpirationTime(SecOCSPResponseRef ocspResponse);
98 |
99 | CFDataRef SecOCSPResponseGetNonce(SecOCSPResponseRef ocspResponse);
100 |
101 | CFAbsoluteTime SecOCSPResponseProducedAt(SecOCSPResponseRef ocspResponse);
102 |
103 | CFAbsoluteTime SecOCSPResponseVerifyTime(SecOCSPResponseRef ocspResponse);
104 |
105 | /*!
106 | @function SecOCSPResponseCopySigners
107 | @abstract Returns an array of signers.
108 | @param ocspResponse A SecOCSPResponseRef.
109 | @result The passed in SecOCSPResponseRef is deallocated
110 | */
111 | CFArrayRef SecOCSPResponseCopySigners(SecOCSPResponseRef ocsp);
112 |
113 | /*!
114 | @function SecOCSPResponseFinalize
115 | @abstract Frees a SecOCSPResponseRef.
116 | @param ocspResponse The BER encoded ocsp response.
117 | @result A SecOCSPResponseRef.
118 | */
119 | void SecOCSPResponseFinalize(SecOCSPResponseRef ocspResponse);
120 |
121 |
122 | SecOCSPSingleResponseRef SecOCSPSingleResponseCreate(
123 | SecAsn1OCSPSingleResponse *resp, SecAsn1CoderRef coder);
124 | #endif
125 |
--------------------------------------------------------------------------------
/Replica/OCSP/asynchttp.h:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2009-2010 Apple Inc. All Rights Reserved.
3 | *
4 | * @APPLE_LICENSE_HEADER_START@
5 | *
6 | * This file contains Original Code and/or Modifications of Original Code
7 | * as defined in and that are subject to the Apple Public Source License
8 | * Version 2.0 (the 'License'). You may not use this file except in
9 | * compliance with the License. Please obtain a copy of the License at
10 | * http://www.opensource.apple.com/apsl/ and read it before using this
11 | * file.
12 | *
13 | * The Original Code and all software distributed under the License are
14 | * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 | * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 | * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 | * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 | * Please see the License for the specific language governing rights and
19 | * limitations under the License.
20 | *
21 | * @APPLE_LICENSE_HEADER_END@
22 | */
23 |
24 | /*!
25 | @header asynchttp
26 | The functions provided in asynchttp.h provide an interface to
27 | an asynchronous http get/post engine.
28 | */
29 |
30 | #ifndef _SECURITYD_ASYNCHTTP_H_
31 | #define _SECURITYD_ASYNCHTTP_H_
32 |
33 | #include
34 | #include
35 | #include
36 | #include
37 | #include
38 | #include
39 | #include
40 |
41 | __BEGIN_DECLS
42 |
43 | typedef struct asynchttp_s {
44 | void(*completed)(struct asynchttp_s *http, CFTimeInterval maxAge);
45 | void *info;
46 | CFHTTPMessageRef request;
47 | CFHTTPMessageRef response;
48 | __unsafe_unretained dispatch_queue_t queue;
49 | /* The fields below should be considered private. */
50 | CFMutableDataRef data;
51 | CFReadStreamRef stream;
52 | __unsafe_unretained dispatch_source_t timer;
53 | } asynchttp_t;
54 |
55 | /* Return false if work was scheduled and the callback will be invoked,
56 | true if it wasn't or the callback was already called. */
57 | bool asyncHttpPost(CFURLRef cfUrl, CFDataRef postData, asynchttp_t *http);
58 |
59 | /* Caller owns struct pointed to by http, but is responsible for calling
60 | asynchttp_free() when it's done with it. */
61 | bool asynchttp_request(CFHTTPMessageRef request, asynchttp_t *http);
62 | void asynchttp_free(asynchttp_t *http);
63 |
64 | /* */
65 |
66 |
67 | __END_DECLS
68 |
69 | #endif /* !_SECURITYD_ASYNCHTTP_H_ */
70 |
--------------------------------------------------------------------------------
/Replica/OCSP/nameTemplates.h:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2003-2006,2008,2010 Apple Inc. All Rights Reserved.
3 | *
4 | * @APPLE_LICENSE_HEADER_START@
5 | *
6 | * This file contains Original Code and/or Modifications of Original Code
7 | * as defined in and that are subject to the Apple Public Source License
8 | * Version 2.0 (the 'License'). You may not use this file except in
9 | * compliance with the License. Please obtain a copy of the License at
10 | * http://www.opensource.apple.com/apsl/ and read it before using this
11 | * file.
12 | *
13 | * The Original Code and all software distributed under the License are
14 | * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 | * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 | * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 | * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 | * Please see the License for the specific language governing rights and
19 | * limitations under the License.
20 | *
21 | * @APPLE_LICENSE_HEADER_END@
22 | *
23 | * nameTemplates.h - ASN1 templates for X509 Name, GeneralName, etc.
24 | */
25 |
26 | #ifndef _NSS_NAME_TEMPLATES_H_
27 | #define _NSS_NAME_TEMPLATES_H_
28 |
29 | #include
30 |
31 | #ifdef __cplusplus
32 | extern "C" {
33 | #endif
34 |
35 | // MARK: ----- Generalized NSS_TaggedItem template chooser support -----
36 |
37 | /*
38 | * A tagged item for use with simple CHOICE types implemented
39 | * via SEC_ASN1_DYNAMIC.
40 | */
41 | typedef struct {
42 | SecAsn1Item item;
43 | unsigned char tag;
44 | } NSS_TaggedItem;
45 |
46 | /*
47 | * Type/template-specific SecAsn1TemplateChooser passes
48 | * an array of these, terminated by a NSS_TagChoice with
49 | * a NULL templ field, to SecAsn1TaggedTemplateChooser().
50 | */
51 | typedef struct {
52 | unsigned char tag;
53 | const SecAsn1Template *templ;
54 | } NSS_TagChoice;
55 |
56 | /*
57 | * Generalized Template chooser.
58 | */
59 | const SecAsn1Template * SecAsn1TaggedTemplateChooser(
60 | /* Four args passed to specific SecAsn1TemplateChooser */
61 | void *arg, // currently not used
62 | Boolean enc,
63 | const char *buf,
64 | void *dest,
65 | /* array of tag/template pairs */
66 | const NSS_TagChoice *chooser);
67 |
68 | // MARK: ----- X509 Name, RDN ------
69 |
70 | /*
71 | * ASN class : AttributeTypeAndValue
72 | * C struct : NSS_ATV
73 | * Roughly corresponds to a CSSM_X509_TYPE_VALUE_PAIR and used
74 | * in DirectoryString elements.
75 | */
76 |
77 | /*
78 | * This type and template process, via SEC_ASN1_DYNAMIC. the following
79 | * tagged types:
80 | *
81 | * SEC_ASN1_PRINTABLE_STRING
82 | * SEC_ASN1_TELETEX_STRING
83 | * SEC_ASN1_UNIVERSAL_STRING
84 | * SEC_ASN1_UTF8_STRING
85 | * SEC_ASN1_BMP_STRING
86 | * SEC_ASN1_IA5_STRING
87 | *
88 | * Note that SEC_ASN1_IA5_STRING is not a legal part of a
89 | * DirectoryString, but some certs (e.g. the Thawte serverbasic cert)
90 | * use this type.
91 | */
92 | typedef struct {
93 | SecAsn1Oid type;
94 | NSS_TaggedItem value;
95 | } NSS_ATV;
96 |
97 | /*
98 | * ASN class : RelativeDistinguishedName
99 | * C struct : NSS_RDN
100 | *
101 | * Corresponds to CSSM_X509_RDN.
102 | */
103 | typedef struct {
104 | NSS_ATV **atvs;
105 | } NSS_RDN;
106 |
107 | /*
108 | * ASN class : Name
109 | * C struct : NSS_Name
110 | *
111 | * Corresponds to CSSM_X509_NAME.
112 | */
113 | typedef struct {
114 | NSS_RDN **rdns;
115 | } NSS_Name;
116 |
117 | extern const SecAsn1Template kSecAsn1ATVTemplate[];
118 | extern const SecAsn1Template kSecAsn1RDNTemplate[];
119 | extern const SecAsn1Template kSecAsn1NameTemplate[];
120 |
121 | // MARK: ----- OtherName, GeneralizedName -----
122 |
123 | /*
124 | * ASN Class : OtherName
125 | * C struct : CE_OtherName
126 | *
127 | * CE_OtherName.value expressed as ASN_ANY, not en/decoded.
128 | */
129 | extern const SecAsn1Template kSecAsn1OtherNameTemplate[];
130 |
131 | /*
132 | * For decoding an OtherName when it's a context-specific CHOICE
133 | * of a GeneralName.
134 | */
135 | extern const SecAsn1Template kSecAsn1GenNameOtherNameTemplate[];
136 |
137 | /*
138 | * ASN Class : GeneralName
139 | * C struct : NSS_GeneralName, typedefd to an NSS_TaggedItem
140 | *
141 | * This roughly maps to a CE_GeneralName (from certextensions.h).
142 | * The NSS_TaggedItem mechanism is used to resolve choices down
143 | * to the SecAsn1Item level - i.e., at this level (prior to encoding
144 | * or after decoding), NSS_GeneralName.item either contains a simple
145 | * atomic type (IA5String, Octet string) or is raw, un{de,en}coded
146 | * ASN_ANY.
147 | */
148 | typedef NSS_TaggedItem NSS_GeneralName;
149 |
150 | /*
151 | * These context-specific tag definitions, for use in
152 | * NSS_GeneralName.tag, are from the ASN definition and map to
153 | * CE_GeneralNameType values from certextensions.h. The values
154 | * happen to be equivalent but apps should not count on that -
155 | * these NSS_GeneralNameTag values are explicitly assigned per
156 | * the ASN spec of a GeneralName.
157 | *
158 | * Shown with each tag is the simple type the tag maps to.
159 | */
160 | typedef enum {
161 | NGT_OtherName = 0, // ASN_ANY
162 | NGT_RFC822Name = 1, // IA5String
163 | NGT_DNSName = 2, // IA5String
164 | NGT_X400Address = 3, // ASY_ANY
165 | NGT_DirectoryName = 4, // ASN_ANY
166 | NGT_EdiPartyName = 5, // ASN_ANY
167 | NGT_URI = 6, // IA5String
168 | NGT_IPAddress = 7, // OCTET_STRING
169 | NGT_RegisteredID = 8 // OID
170 | } NSS_GeneralNameTag;
171 |
172 | extern const SecAsn1Template kSecAsn1GeneralNameTemplate[];
173 |
174 | /*
175 | * ASN Class : GeneralNames
176 | * C struct : NSS_GeneralNames
177 | *
178 | * Since the SEC_ANY_DYNAMIC mechanism doesn't work with POINTERs
179 | * or GROUPs (e.g., a sequence of NSS_GeneralName elements), decoding
180 | * an NSS_GeneralNames first requires a decode to an array of
181 | * ANY_ANY blobs as shown here. Use SEC_SequenceOfAnyTemplate for
182 | * that step. Each of the resulting elements is individually
183 | * decoded into an NSS_GeneralName.
184 | */
185 | typedef struct {
186 | SecAsn1Item **names; /* sequence */
187 | } NSS_GeneralNames;
188 |
189 | #define kSecAsn1GeneralNamesTemplate kSecAsn1SequenceOfAnyTemplate
190 |
191 | #ifdef __cplusplus
192 | }
193 | #endif
194 |
195 | #endif /* _NSS_NAME_TEMPLATES_H_ */
196 |
--------------------------------------------------------------------------------
/Replica/OCSP/ocspTemplates.h:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2003-2006,2008-2010 Apple Inc. All Rights Reserved.
3 | *
4 | * @APPLE_LICENSE_HEADER_START@
5 | *
6 | * This file contains Original Code and/or Modifications of Original Code
7 | * as defined in and that are subject to the Apple Public Source License
8 | * Version 2.0 (the 'License'). You may not use this file except in
9 | * compliance with the License. Please obtain a copy of the License at
10 | * http://www.opensource.apple.com/apsl/ and read it before using this
11 | * file.
12 | *
13 | * The Original Code and all software distributed under the License are
14 | * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 | * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 | * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 | * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 | * Please see the License for the specific language governing rights and
19 | * limitations under the License.
20 | *
21 | * @APPLE_LICENSE_HEADER_END@
22 | *
23 | * ocspTemplates.h - ASN1 templates OCSP requests and responses.
24 | */
25 |
26 | #ifndef _OCSP_TEMPLATES_H_
27 | #define _OCSP_TEMPLATES_H_
28 |
29 | #include "nameTemplates.h"
30 |
31 | #ifdef __cplusplus
32 | extern "C" {
33 | #endif
34 |
35 |
36 | /*
37 | * BasicOCSPResponse ::= SEQUENCE {
38 | * tbsResponseData ResponseData,
39 | * signatureAlgorithm AlgorithmIdentifier,
40 | * signature BIT STRING,
41 | * certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL }
42 | *
43 | * Since we ALWAYS encode the tbsResponseData in preparation for signing,
44 | * we declare it as a raw ASN_ANY in the BasicOCSPResponse.
45 | *
46 | * Certs are likewise ASN_ANY since we use the CL to parse and create them.
47 | */
48 | typedef struct {
49 | SecAsn1Item tbsResponseData;
50 | SecAsn1AlgId algId;
51 | SecAsn1Item sig; // length in BITS
52 | SecAsn1Item **certs; // optional
53 | } SecAsn1OCSPBasicResponse;
54 |
55 | /*
56 | * X509 cert extension
57 | * ASN Class : Extension
58 | * C struct : NSS_CertExtension
59 | *
60 | * With a nontrivial amount of extension-specific processing,
61 | * this maps to a CSSM_X509_EXTENSION.
62 | */
63 | typedef struct {
64 | SecAsn1Item extnId;
65 | SecAsn1Item critical; // optional, default = false
66 | SecAsn1Item value; // OCTET string whose decoded value is
67 | // an id-specific DER-encoded thing
68 | } NSS_CertExtension;
69 |
70 | /*
71 | * CertID ::= SEQUENCE {
72 | * hashAlgorithm AlgorithmIdentifier,
73 | * issuerNameHash OCTET STRING, -- Hash of Issuer's DN
74 | * issuerKeyHash OCTET STRING, -- Hash of Issuers public key
75 | * serialNumber CertificateSerialNumber } -- i.e., INTEGER
76 | */
77 | typedef struct {
78 | SecAsn1AlgId algId;
79 | SecAsn1Item issuerNameHash;
80 | SecAsn1Item issuerPubKeyHash;
81 | SecAsn1Item serialNumber;
82 | } SecAsn1OCSPCertID;
83 |
84 | /*
85 | * SingleResponse ::= SEQUENCE {
86 | * certID CertID,
87 | * certStatus CertStatus,
88 | * thisUpdate GeneralizedTime,
89 | * nextUpdate [0] EXPLICIT GeneralizedTime OPTIONAL,
90 | * singleExtensions [1] EXPLICIT Extensions OPTIONAL }
91 | */
92 | typedef struct {
93 | SecAsn1OCSPCertID certID;
94 | SecAsn1Item certStatus; // ASN_ANY here
95 | SecAsn1Item thisUpdate; // GeneralizedTime
96 | SecAsn1Item *nextUpdate; // GeneralizedTime, OPTIONAL
97 | NSS_CertExtension **singleExtensions; // OPTIONAL
98 | } SecAsn1OCSPSingleResponse;
99 |
100 | /*
101 | * ResponseData ::= SEQUENCE {
102 | * version [0] EXPLICIT Version DEFAULT v1,
103 | * responderID ResponderID,
104 | * producedAt GeneralizedTime,
105 | * responses SEQUENCE OF SingleResponse,
106 | * responseExtensions [1] EXPLICIT Extensions OPTIONAL }
107 | */
108 | typedef struct {
109 | SecAsn1Item *version; // OPTIONAL
110 | SecAsn1Item responderID; // ASN_ANY here, decode/encode separately
111 | SecAsn1Item producedAt; // GeneralizedTime
112 | SecAsn1OCSPSingleResponse **responses;
113 | NSS_CertExtension **responseExtensions; // OPTIONAL
114 | } SecAsn1OCSPResponseData;
115 |
116 |
117 | typedef enum {
118 | RIT_Name = 1,
119 | RIT_Key = 2
120 | } SecAsn1OCSPResponderIDTag;
121 |
122 |
123 | /*
124 | * ResponderID ::= CHOICE {
125 | * byName EXPLICIT [1] Name,
126 | * byKey EXPLICIT [2] KeyHash }
127 | *
128 | * Since our ASN.1 encoder/decoder can't handle CHOICEs very well, we encode
129 | * this separately using one of the following two templates. On encode the
130 | * result if this step of the encode goes into SecAsn1OCSPResponseData.responderID,
131 | * where it's treated as an ANY_ANY when encoding that struct. The reverse happens
132 | * on decode.
133 | */
134 | typedef union {
135 | SecAsn1Item byName;
136 | SecAsn1Item byKey; // key hash in OCTET STRING
137 | } SecAsn1OCSPResponderID;
138 |
139 |
140 | /////////////////////////// ocspTemplates.h ///////////////////
141 | /*
142 | * ResponseBytes ::= SEQUENCE {
143 | * responseType OBJECT IDENTIFIER,
144 | * response OCTET STRING }
145 | *
146 | * The contents of response are actually an encoded SecAsn1OCSPBasicResponse (at
147 | * least until another response type is defined).
148 | */
149 | typedef struct {
150 | SecAsn1Oid responseType;
151 | SecAsn1Item response;
152 | } SecAsn1OCSPResponseBytes;
153 |
154 | extern const SecAsn1Template kSecAsn1OCSPResponseBytesTemplate[];
155 |
156 |
157 | typedef enum {
158 | CS_Good = 0,
159 | CS_Revoked = 1,
160 | CS_Unknown = 2,
161 | CS_NotParsed = 0xff /* Not in protocol: means value not parsed or seen */
162 | } SecAsn1OCSPCertStatusTag;
163 |
164 | /*
165 | * OCSPResponse ::= SEQUENCE {
166 | * responseStatus OCSPResponseStatus, -- an ENUM
167 | * responseBytes [0] EXPLICIT ResponseBytes OPTIONAL }
168 | */
169 | typedef struct {
170 | SecAsn1Item responseStatus; // see enum below
171 | SecAsn1OCSPResponseBytes *responseBytes; // optional
172 | } SecAsn1OCSPResponse;
173 |
174 | /*
175 | * Request ::= SEQUENCE {
176 | * reqCert CertID,
177 | * singleRequestExtensions [0] EXPLICIT Extensions OPTIONAL }
178 | */
179 | typedef struct {
180 | SecAsn1OCSPCertID reqCert;
181 | NSS_CertExtension **extensions; // optional
182 | } SecAsn1OCSPRequest;
183 |
184 | /*
185 | * Signature ::= SEQUENCE {
186 | * signatureAlgorithm AlgorithmIdentifier,
187 | * signature BIT STRING,
188 | * certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL}
189 | *
190 | * Since we wish to avoid knowing anything about the details of the certs,
191 | * we declare them here as ASN_ANY, get/set as raw data, and leave it to
192 | * the CL to parse them.
193 | */
194 | typedef struct {
195 | SecAsn1AlgId algId;
196 | SecAsn1Item sig; // length in BITS
197 | SecAsn1Item **certs; // OPTIONAL
198 | } SecAsn1OCSPSignature;
199 |
200 |
201 | /*
202 | * TBSRequest ::= SEQUENCE {
203 | * version [0] EXPLICIT Version DEFAULT v1,
204 | * requestorName [1] EXPLICIT GeneralName OPTIONAL,
205 | * requestList SEQUENCE OF Request,
206 | * requestExtensions [2] EXPLICIT Extensions OPTIONAL }
207 | */
208 | typedef struct {
209 | SecAsn1Item *version; // OPTIONAL
210 | NSS_GeneralName *requestorName; // OPTIONAL
211 | SecAsn1OCSPRequest **requestList;
212 | NSS_CertExtension **requestExtensions; // OPTIONAL
213 | } SecAsn1OCSPTbsRequest;
214 |
215 | extern const SecAsn1Template kSecAsn1OCSPTbsRequestTemplate[];
216 |
217 | /*
218 | * OCSPRequest ::= SEQUENCE {
219 | * tbsRequest TBSRequest,
220 | * optionalSignature [0] EXPLICIT Signature OPTIONAL }
221 | */
222 | typedef struct {
223 | SecAsn1OCSPTbsRequest tbsRequest;
224 | SecAsn1OCSPSignature *signature; // OPTIONAL
225 | } SecAsn1OCSPSignedRequest;
226 |
227 | extern const SecAsn1Template kSecAsn1OCSPSignedRequestTemplate[];
228 |
229 | // MARK: ----- OCSP Response -----
230 |
231 | /*
232 | * CertStatus ::= CHOICE {
233 | * good [0] IMPLICIT NULL,
234 | * revoked [1] IMPLICIT RevokedInfo,
235 | * unknown [2] IMPLICIT UnknownInfo }
236 | *
237 | * RevokedInfo ::= SEQUENCE {
238 | * revocationTime GeneralizedTime,
239 | * revocationReason [0] EXPLICIT CRLReason OPTIONAL }
240 | *
241 | * UnknownInfo ::= NULL -- this can be replaced with an enumeration
242 | *
243 | * See for enum values of CE_CrlReason.
244 | */
245 | typedef struct {
246 | SecAsn1Item revocationTime;
247 | SecAsn1Item *revocationReason; // OPTIONAL, CE_CrlReason
248 | } SecAsn1OCSPRevokedInfo;
249 |
250 | typedef union {
251 | SecAsn1OCSPRevokedInfo *revokedInfo;
252 | SecAsn1Item *nullData;
253 | } SecAsn1OCSPCertStatus;
254 |
255 |
256 |
257 |
258 |
259 | #ifdef __cplusplus
260 | }
261 | #endif
262 |
263 | #endif /* _OCSP_TEMPLATES_H_ */
264 |
--------------------------------------------------------------------------------
/Replica/Provisioning.h:
--------------------------------------------------------------------------------
1 | //
2 | // Provisioning.h
3 | // IPAExporter
4 | //
5 | // Created by Tue Nguyen on 10/10/14.
6 | // Copyright (c) 2014 HOME. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | #import "SigningIdentity.h"
12 |
13 | @interface Provisioning : NSObject
14 |
15 | @property (nonatomic, strong) NSString *path;
16 | @property (nonatomic, strong) NSString *name;
17 | @property (nonatomic, strong) NSDate *creationDate;
18 | @property (nonatomic, strong) NSDate *expirationDate;
19 | @property (nonatomic, strong) NSString *applicationIdentifier;
20 | @property (nonatomic, strong) NSString *teamID;
21 | @property (nonatomic, strong) NSDictionary *entitlements;
22 | @property (nonatomic, strong) NSArray *provisionedDevices;
23 | @property (nonatomic, strong) NSArray *developerCertificates;
24 | @property (nonatomic, strong) NSArray *signingIdentities;
25 | @property (nonatomic, strong) NSDictionary *propertyList;
26 |
27 | @property (strong, nonatomic) NSString *status;
28 |
29 | - (instancetype)initWithPath:(NSString *)path;
30 | - (BOOL)isExpired;
31 | - (BOOL)containsSigningIdentity:(SigningIdentity *)signingIdentity;
32 | @end
33 |
--------------------------------------------------------------------------------
/Replica/Provisioning.m:
--------------------------------------------------------------------------------
1 | //
2 | // Provisioning.m
3 | // IPAExporter
4 | //
5 | // Created by Tue Nguyen on 10/10/14.
6 | // Copyright (c) 2014 HOME. All rights reserved.
7 | //
8 |
9 | #import "Provisioning.h"
10 | #import "SigningIdentity.h"
11 |
12 | @implementation Provisioning
13 | - (instancetype)initWithPath:(NSString *)path {
14 | self = [super init];
15 | if (self) {
16 | self.path = path;
17 | [self _readProvisioningData];
18 | }
19 | return self;
20 | }
21 |
22 | - (void)_readProvisioningData {
23 | NSData *fileData = [NSData dataWithContentsOfFile:self.path];
24 | if (!fileData) return;
25 |
26 | // Insert code here to initialize your application
27 | CMSDecoderRef decoder = NULL;
28 | CMSDecoderCreate(&decoder);
29 | CMSDecoderUpdateMessage(decoder, fileData.bytes, fileData.length);
30 | CMSDecoderFinalizeMessage(decoder);
31 |
32 | CFDataRef dataRef = NULL;
33 | CMSDecoderCopyContent(decoder, &dataRef);
34 | NSData *data = (__bridge_transfer NSData *)dataRef;
35 |
36 | NSDictionary *propertyList = [NSPropertyListSerialization propertyListWithData:data options:0 format:NULL error:NULL];
37 |
38 | self.name = propertyList[@"Name"];
39 | self.expirationDate = propertyList[@"ExpirationDate"];
40 | self.creationDate = propertyList[@"CreationDate"];
41 | self.provisionedDevices = propertyList[@"ProvisionedDevices"];
42 |
43 | self.entitlements = propertyList[@"Entitlements"];
44 | self.applicationIdentifier = self.entitlements[@"application-identifier"]?:self.entitlements[@"com.apple.application-identifier"];
45 | //Remove team id in app id
46 | self.teamID = [propertyList[@"ApplicationIdentifierPrefix"] firstObject];
47 | if ([self.applicationIdentifier hasPrefix:self.teamID]) {
48 | self.applicationIdentifier = [self.applicationIdentifier substringFromIndex:self.teamID.length + 1];
49 | }
50 | self.developerCertificates = propertyList[@"DeveloperCertificates"];
51 | self.propertyList = propertyList;
52 |
53 | if ([self.expirationDate timeIntervalSinceNow] > 0) {
54 | self.status = @"Valid";
55 | } else {
56 | self.status = @"Expired";
57 | }
58 |
59 | [self _loadSigningIdentities];
60 | }
61 |
62 | - (void)_loadSigningIdentities {
63 | NSMutableArray *result = [NSMutableArray array];
64 | for (NSData *certData in self.developerCertificates) {
65 | SigningIdentity *identity = [[SigningIdentity alloc] initWithCertificateData:certData];
66 | [result addObject:identity];
67 | }
68 | self.signingIdentities = result;
69 | }
70 |
71 | - (BOOL)isExpired {
72 | return [[NSDate date] compare:self.expirationDate] == NSOrderedDescending;
73 | }
74 |
75 | - (BOOL)containsSigningIdentity:(SigningIdentity *)signingIdentity {
76 | __block BOOL result = NO;
77 | [self.signingIdentities enumerateObjectsUsingBlock:^(SigningIdentity * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
78 | if ([obj isEqual:signingIdentity]) {
79 | result = YES;
80 | *stop = YES;
81 | }
82 | }];
83 | return result;
84 | }
85 |
86 | - (NSString *)description {
87 | return [NSString stringWithFormat:@"Provisioning(Name: %@, Create Date: %@, Expiration Date: %@, Path: %@)", self.name, self.creationDate, self.expirationDate, self.path];
88 | }
89 | @end
90 |
--------------------------------------------------------------------------------
/Replica/Replica-Prefix.pch:
--------------------------------------------------------------------------------
1 | //
2 | // Replica-Prefix.pch
3 | // Replica
4 | //
5 | // Created by h4ck on 18/11/1.
6 | // Copyright © 2018年 字节时代(https://byteage.com) All rights reserved.
7 | //
8 |
9 | #ifndef Replica_Prefix_pch
10 | #define Replica_Prefix_pch
11 |
12 | #ifdef __OBJC__
13 | #import
14 |
15 | #ifdef DEBUG
16 | static const DDLogLevel ddLogLevel = DDLogLevelVerbose;
17 | #else
18 | static const DDLogLevel ddLogLevel = DDLogLevelVerbose;
19 | #endif
20 |
21 | #endif
22 |
23 | #endif /* Replica_Prefix_pch */
24 |
--------------------------------------------------------------------------------
/Replica/ResignView.h:
--------------------------------------------------------------------------------
1 | //
2 | // ResignView.h
3 | // Replica
4 | //
5 | // Created by h4ck on 18/11/1.
6 | // Copyright © 2018年 字节时代(https://byteage.com) All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | @interface OutputInfo : NSObject
12 | @property (nonatomic) NSString *path;
13 | @property (nonatomic) BOOL isDirectory;
14 | @end
15 | @interface ResignView : NSView
16 |
17 | @end
18 |
--------------------------------------------------------------------------------
/Replica/SSZipArchive/SSZipArchive.h:
--------------------------------------------------------------------------------
1 | //
2 | // SSZipArchive.h
3 | // SSZipArchive
4 | //
5 | // Created by Sam Soffes on 7/21/10.
6 | // Copyright (c) Sam Soffes 2010-2015. All rights reserved.
7 | //
8 |
9 | #ifndef _SSZIPARCHIVE_H
10 | #define _SSZIPARCHIVE_H
11 |
12 | #import
13 | #include "SSZipCommon.h"
14 |
15 | NS_ASSUME_NONNULL_BEGIN
16 |
17 | extern NSString *const SSZipArchiveErrorDomain;
18 | typedef NS_ENUM(NSInteger, SSZipArchiveErrorCode) {
19 | SSZipArchiveErrorCodeFailedOpenZipFile = -1,
20 | SSZipArchiveErrorCodeFailedOpenFileInZip = -2,
21 | SSZipArchiveErrorCodeFileInfoNotLoadable = -3,
22 | SSZipArchiveErrorCodeFileContentNotReadable = -4,
23 | SSZipArchiveErrorCodeFailedToWriteFile = -5,
24 | SSZipArchiveErrorCodeInvalidArguments = -6,
25 | };
26 |
27 | @protocol SSZipArchiveDelegate;
28 |
29 | @interface SSZipArchive : NSObject
30 |
31 | // Password check
32 | + (BOOL)isFilePasswordProtectedAtPath:(NSString *)path;
33 | + (BOOL)isPasswordValidForArchiveAtPath:(NSString *)path password:(NSString *)pw error:(NSError * _Nullable * _Nullable)error NS_SWIFT_NOTHROW;
34 |
35 | // Unzip
36 | + (BOOL)unzipFileAtPath:(NSString *)path toDestination:(NSString *)destination;
37 | + (BOOL)unzipFileAtPath:(NSString *)path toDestination:(NSString *)destination delegate:(nullable id)delegate;
38 |
39 | + (BOOL)unzipFileAtPath:(NSString *)path
40 | toDestination:(NSString *)destination
41 | overwrite:(BOOL)overwrite
42 | password:(nullable NSString *)password
43 | error:(NSError * *)error;
44 |
45 | + (BOOL)unzipFileAtPath:(NSString *)path
46 | toDestination:(NSString *)destination
47 | overwrite:(BOOL)overwrite
48 | password:(nullable NSString *)password
49 | error:(NSError * *)error
50 | delegate:(nullable id)delegate NS_REFINED_FOR_SWIFT;
51 |
52 | + (BOOL)unzipFileAtPath:(NSString *)path
53 | toDestination:(NSString *)destination
54 | preserveAttributes:(BOOL)preserveAttributes
55 | overwrite:(BOOL)overwrite
56 | password:(nullable NSString *)password
57 | error:(NSError * *)error
58 | delegate:(nullable id)delegate;
59 |
60 | + (BOOL)unzipFileAtPath:(NSString *)path
61 | toDestination:(NSString *)destination
62 | progressHandler:(void (^_Nullable)(NSString *entry, unz_file_info zipInfo, long entryNumber, long total))progressHandler
63 | completionHandler:(void (^_Nullable)(NSString *path, BOOL succeeded, NSError * _Nullable error))completionHandler;
64 |
65 | + (BOOL)unzipFileAtPath:(NSString *)path
66 | toDestination:(NSString *)destination
67 | overwrite:(BOOL)overwrite
68 | password:(nullable NSString *)password
69 | progressHandler:(void (^_Nullable)(NSString *entry, unz_file_info zipInfo, long entryNumber, long total))progressHandler
70 | completionHandler:(void (^_Nullable)(NSString *path, BOOL succeeded, NSError * _Nullable error))completionHandler;
71 |
72 | + (BOOL)unzipFileAtPath:(NSString *)path
73 | toDestination:(NSString *)destination
74 | preserveAttributes:(BOOL)preserveAttributes
75 | overwrite:(BOOL)overwrite
76 | nestedZipLevel:(NSInteger)nestedZipLevel
77 | password:(nullable NSString *)password
78 | error:(NSError **)error
79 | delegate:(nullable id)delegate
80 | progressHandler:(void (^_Nullable)(NSString *entry, unz_file_info zipInfo, long entryNumber, long total))progressHandler
81 | completionHandler:(void (^_Nullable)(NSString *path, BOOL succeeded, NSError * _Nullable error))completionHandler;
82 |
83 | // Zip
84 | // default compression level is Z_DEFAULT_COMPRESSION (from "zlib.h")
85 |
86 | // without password
87 | + (BOOL)createZipFileAtPath:(NSString *)path withFilesAtPaths:(NSArray *)paths;
88 | + (BOOL)createZipFileAtPath:(NSString *)path withContentsOfDirectory:(NSString *)directoryPath;
89 |
90 | + (BOOL)createZipFileAtPath:(NSString *)path withContentsOfDirectory:(NSString *)directoryPath keepParentDirectory:(BOOL)keepParentDirectory;
91 |
92 | // with optional password, default encryption is AES
93 | // don't use AES if you need compatibility with native macOS unzip and Archive Utility
94 | + (BOOL)createZipFileAtPath:(NSString *)path withFilesAtPaths:(NSArray *)paths withPassword:(nullable NSString *)password;
95 | + (BOOL)createZipFileAtPath:(NSString *)path withContentsOfDirectory:(NSString *)directoryPath withPassword:(nullable NSString *)password;
96 | + (BOOL)createZipFileAtPath:(NSString *)path withContentsOfDirectory:(NSString *)directoryPath keepParentDirectory:(BOOL)keepParentDirectory withPassword:(nullable NSString *)password;
97 | + (BOOL)createZipFileAtPath:(NSString *)path
98 | withContentsOfDirectory:(NSString *)directoryPath
99 | keepParentDirectory:(BOOL)keepParentDirectory
100 | withPassword:(nullable NSString *)password
101 | andProgressHandler:(void(^ _Nullable)(NSUInteger entryNumber, NSUInteger total))progressHandler;
102 | + (BOOL)createZipFileAtPath:(NSString *)path
103 | withContentsOfDirectory:(NSString *)directoryPath
104 | keepParentDirectory:(BOOL)keepParentDirectory
105 | compressionLevel:(int)compressionLevel
106 | password:(nullable NSString *)password
107 | AES:(BOOL)aes
108 | progressHandler:(void(^ _Nullable)(NSUInteger entryNumber, NSUInteger total))progressHandler;
109 |
110 | - (instancetype)init NS_UNAVAILABLE;
111 | - (instancetype)initWithPath:(NSString *)path NS_DESIGNATED_INITIALIZER;
112 | - (BOOL)open;
113 |
114 | /// write empty folder
115 | - (BOOL)writeFolderAtPath:(NSString *)path withFolderName:(NSString *)folderName withPassword:(nullable NSString *)password;
116 | /// write file
117 | - (BOOL)writeFile:(NSString *)path withPassword:(nullable NSString *)password;
118 | - (BOOL)writeFileAtPath:(NSString *)path withFileName:(nullable NSString *)fileName withPassword:(nullable NSString *)password;
119 | - (BOOL)writeFileAtPath:(NSString *)path withFileName:(nullable NSString *)fileName compressionLevel:(int)compressionLevel password:(nullable NSString *)password AES:(BOOL)aes;
120 | /// write data
121 | - (BOOL)writeData:(NSData *)data filename:(nullable NSString *)filename withPassword:(nullable NSString *)password;
122 | - (BOOL)writeData:(NSData *)data filename:(nullable NSString *)filename compressionLevel:(int)compressionLevel password:(nullable NSString *)password AES:(BOOL)aes;
123 |
124 | - (BOOL)close;
125 |
126 | @end
127 |
128 | @protocol SSZipArchiveDelegate
129 |
130 | @optional
131 |
132 | - (void)zipArchiveWillUnzipArchiveAtPath:(NSString *)path zipInfo:(unz_global_info)zipInfo;
133 | - (void)zipArchiveDidUnzipArchiveAtPath:(NSString *)path zipInfo:(unz_global_info)zipInfo unzippedPath:(NSString *)unzippedPath;
134 |
135 | - (BOOL)zipArchiveShouldUnzipFileAtIndex:(NSInteger)fileIndex totalFiles:(NSInteger)totalFiles archivePath:(NSString *)archivePath fileInfo:(unz_file_info)fileInfo;
136 | - (void)zipArchiveWillUnzipFileAtIndex:(NSInteger)fileIndex totalFiles:(NSInteger)totalFiles archivePath:(NSString *)archivePath fileInfo:(unz_file_info)fileInfo;
137 | - (void)zipArchiveDidUnzipFileAtIndex:(NSInteger)fileIndex totalFiles:(NSInteger)totalFiles archivePath:(NSString *)archivePath fileInfo:(unz_file_info)fileInfo;
138 | - (void)zipArchiveDidUnzipFileAtIndex:(NSInteger)fileIndex totalFiles:(NSInteger)totalFiles archivePath:(NSString *)archivePath unzippedFilePath:(NSString *)unzippedFilePath;
139 |
140 | - (void)zipArchiveProgressEvent:(unsigned long long)loaded total:(unsigned long long)total;
141 |
142 | @end
143 |
144 | NS_ASSUME_NONNULL_END
145 |
146 | #endif /* _SSZIPARCHIVE_H */
147 |
--------------------------------------------------------------------------------
/Replica/SSZipArchive/SSZipCommon.h:
--------------------------------------------------------------------------------
1 | #ifndef SSZipCommon
2 | #define SSZipCommon
3 |
4 | /* unz_global_info structure contain global data about the ZIPfile
5 | These data comes from the end of central dir */
6 | typedef struct unz_global_info64_s
7 | {
8 | uint64_t number_entry; /* total number of entries in the central dir on this disk */
9 | uint32_t number_disk_with_CD; /* number the the disk with central dir, used for spanning ZIP*/
10 | uint16_t size_comment; /* size of the global comment of the zipfile */
11 | } unz_global_info64;
12 |
13 | typedef struct unz_global_info_s
14 | {
15 | uint32_t number_entry; /* total number of entries in the central dir on this disk */
16 | uint32_t number_disk_with_CD; /* number the the disk with central dir, used for spanning ZIP*/
17 | uint16_t size_comment; /* size of the global comment of the zipfile */
18 | } unz_global_info;
19 |
20 | /* unz_file_info contain information about a file in the zipfile */
21 | /* https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT */
22 | typedef struct unz_file_info64_s
23 | {
24 | uint16_t version; /* version made by 2 bytes */
25 | uint16_t version_needed; /* version needed to extract 2 bytes */
26 | uint16_t flag; /* general purpose bit flag 2 bytes */
27 | uint16_t compression_method; /* compression method 2 bytes */
28 | uint32_t dos_date; /* last mod file date in Dos fmt 4 bytes */
29 | uint32_t crc; /* crc-32 4 bytes */
30 | uint64_t compressed_size; /* compressed size 8 bytes */
31 | uint64_t uncompressed_size; /* uncompressed size 8 bytes */
32 | uint16_t size_filename; /* filename length 2 bytes */
33 | uint16_t size_file_extra; /* extra field length 2 bytes */
34 | uint16_t size_file_comment; /* file comment length 2 bytes */
35 |
36 | uint32_t disk_num_start; /* disk number start 4 bytes */
37 | uint16_t internal_fa; /* internal file attributes 2 bytes */
38 | uint32_t external_fa; /* external file attributes 4 bytes */
39 |
40 | uint64_t disk_offset;
41 |
42 | uint16_t size_file_extra_internal;
43 | } unz_file_info64;
44 |
45 | typedef struct unz_file_info_s
46 | {
47 | uint16_t version; /* version made by 2 bytes */
48 | uint16_t version_needed; /* version needed to extract 2 bytes */
49 | uint16_t flag; /* general purpose bit flag 2 bytes */
50 | uint16_t compression_method; /* compression method 2 bytes */
51 | uint32_t dos_date; /* last mod file date in Dos fmt 4 bytes */
52 | uint32_t crc; /* crc-32 4 bytes */
53 | uint32_t compressed_size; /* compressed size 4 bytes */
54 | uint32_t uncompressed_size; /* uncompressed size 4 bytes */
55 | uint16_t size_filename; /* filename length 2 bytes */
56 | uint16_t size_file_extra; /* extra field length 2 bytes */
57 | uint16_t size_file_comment; /* file comment length 2 bytes */
58 |
59 | uint16_t disk_num_start; /* disk number start 2 bytes */
60 | uint16_t internal_fa; /* internal file attributes 2 bytes */
61 | uint32_t external_fa; /* external file attributes 4 bytes */
62 |
63 | uint64_t disk_offset;
64 | } unz_file_info;
65 |
66 | #endif
67 |
--------------------------------------------------------------------------------
/Replica/SSZipArchive/ZipArchive.h:
--------------------------------------------------------------------------------
1 | //
2 | // ZipArchive.h
3 | // ZipArchive
4 | //
5 | // Created by Serhii Mumriak on 12/1/15.
6 | // Copyright © 2015 smumryak. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | //! Project version number for ZipArchive.
12 | FOUNDATION_EXPORT double ZipArchiveVersionNumber;
13 |
14 | //! Project version string for ZipArchive.
15 | FOUNDATION_EXPORT const unsigned char ZipArchiveVersionString[];
16 |
17 | // In this header, you should import all the public headers of your framework using statements like #import
18 |
19 | #import "SSZipArchive.h"
20 |
--------------------------------------------------------------------------------
/Replica/SSZipArchive/minizip/aes/aes.h:
--------------------------------------------------------------------------------
1 | /*
2 | ---------------------------------------------------------------------------
3 | Copyright (c) 1998-2013, Brian Gladman, Worcester, UK. All rights reserved.
4 |
5 | The redistribution and use of this software (with or without changes)
6 | is allowed without the payment of fees or royalties provided that:
7 |
8 | source code distributions include the above copyright notice, this
9 | list of conditions and the following disclaimer;
10 |
11 | binary distributions include the above copyright notice, this list
12 | of conditions and the following disclaimer in their documentation.
13 |
14 | This software is provided 'as is' with no explicit or implied warranties
15 | in respect of its operation, including, but not limited to, correctness
16 | and fitness for purpose.
17 | ---------------------------------------------------------------------------
18 | Issue Date: 20/12/2007
19 |
20 | This file contains the definitions required to use AES in C. See aesopt.h
21 | for optimisation details.
22 | */
23 |
24 | #ifndef _AES_H
25 | #define _AES_H
26 |
27 | #include
28 |
29 | /* This include is used to find 8 & 32 bit unsigned integer types */
30 | #include "brg_types.h"
31 |
32 | #if defined(__cplusplus)
33 | extern "C"
34 | {
35 | #endif
36 |
37 | #define AES_128 /* if a fast 128 bit key scheduler is needed */
38 | #define AES_192 /* if a fast 192 bit key scheduler is needed */
39 | #define AES_256 /* if a fast 256 bit key scheduler is needed */
40 | #define AES_VAR /* if variable key size scheduler is needed */
41 | #define AES_MODES /* if support is needed for modes */
42 |
43 | /* The following must also be set in assembler files if being used */
44 |
45 | #define AES_ENCRYPT /* if support for encryption is needed */
46 | #define AES_DECRYPT /* if support for decryption is needed */
47 |
48 | #define AES_BLOCK_SIZE 16 /* the AES block size in bytes */
49 | #define N_COLS 4 /* the number of columns in the state */
50 |
51 | /* The key schedule length is 11, 13 or 15 16-byte blocks for 128, */
52 | /* 192 or 256-bit keys respectively. That is 176, 208 or 240 bytes */
53 | /* or 44, 52 or 60 32-bit words. */
54 |
55 | #if defined( AES_VAR ) || defined( AES_256 )
56 | #define KS_LENGTH 60
57 | #elif defined( AES_192 )
58 | #define KS_LENGTH 52
59 | #else
60 | #define KS_LENGTH 44
61 | #endif
62 |
63 | #define AES_RETURN INT_RETURN
64 |
65 | /* the character array 'inf' in the following structures is used */
66 | /* to hold AES context information. This AES code uses cx->inf.b[0] */
67 | /* to hold the number of rounds multiplied by 16. The other three */
68 | /* elements can be used by code that implements additional modes */
69 |
70 | typedef union
71 | { uint32_t l;
72 | uint8_t b[4];
73 | } aes_inf;
74 |
75 | #ifdef _MSC_VER
76 | # pragma warning( disable : 4324 )
77 | #endif
78 |
79 | #if defined(_MSC_VER) && defined(_WIN64)
80 | #define ALIGNED_(x) __declspec(align(x))
81 | #elif defined(__GNUC__) && defined(__x86_64__)
82 | #define ALIGNED_(x) __attribute__ ((aligned(x)))
83 | #else
84 | #define ALIGNED_(x)
85 | #endif
86 |
87 | typedef struct ALIGNED_(16)
88 | { uint32_t ks[KS_LENGTH];
89 | aes_inf inf;
90 | } aes_encrypt_ctx;
91 |
92 | typedef struct ALIGNED_(16)
93 | { uint32_t ks[KS_LENGTH];
94 | aes_inf inf;
95 | } aes_decrypt_ctx;
96 |
97 | #ifdef _MSC_VER
98 | # pragma warning( default : 4324 )
99 | #endif
100 |
101 | /* This routine must be called before first use if non-static */
102 | /* tables are being used */
103 |
104 | AES_RETURN aes_init(void);
105 |
106 | /* Key lengths in the range 16 <= key_len <= 32 are given in bytes, */
107 | /* those in the range 128 <= key_len <= 256 are given in bits */
108 |
109 | #if defined( AES_ENCRYPT )
110 |
111 | #if defined( AES_128 ) || defined( AES_VAR)
112 | AES_RETURN aes_encrypt_key128(const unsigned char *key, aes_encrypt_ctx cx[1]);
113 | #endif
114 |
115 | #if defined( AES_192 ) || defined( AES_VAR)
116 | AES_RETURN aes_encrypt_key192(const unsigned char *key, aes_encrypt_ctx cx[1]);
117 | #endif
118 |
119 | #if defined( AES_256 ) || defined( AES_VAR)
120 | AES_RETURN aes_encrypt_key256(const unsigned char *key, aes_encrypt_ctx cx[1]);
121 | #endif
122 |
123 | #if defined( AES_VAR )
124 | AES_RETURN aes_encrypt_key(const unsigned char *key, int key_len, aes_encrypt_ctx cx[1]);
125 | #endif
126 |
127 | AES_RETURN aes_encrypt(const unsigned char *in, unsigned char *out, const aes_encrypt_ctx cx[1]);
128 |
129 | #endif
130 |
131 | #if defined( AES_DECRYPT )
132 |
133 | #if defined( AES_128 ) || defined( AES_VAR)
134 | AES_RETURN aes_decrypt_key128(const unsigned char *key, aes_decrypt_ctx cx[1]);
135 | #endif
136 |
137 | #if defined( AES_192 ) || defined( AES_VAR)
138 | AES_RETURN aes_decrypt_key192(const unsigned char *key, aes_decrypt_ctx cx[1]);
139 | #endif
140 |
141 | #if defined( AES_256 ) || defined( AES_VAR)
142 | AES_RETURN aes_decrypt_key256(const unsigned char *key, aes_decrypt_ctx cx[1]);
143 | #endif
144 |
145 | #if defined( AES_VAR )
146 | AES_RETURN aes_decrypt_key(const unsigned char *key, int key_len, aes_decrypt_ctx cx[1]);
147 | #endif
148 |
149 | AES_RETURN aes_decrypt(const unsigned char *in, unsigned char *out, const aes_decrypt_ctx cx[1]);
150 |
151 | #endif
152 |
153 | #if defined( AES_MODES )
154 |
155 | /* Multiple calls to the following subroutines for multiple block */
156 | /* ECB, CBC, CFB, OFB and CTR mode encryption can be used to handle */
157 | /* long messages incrementally provided that the context AND the iv */
158 | /* are preserved between all such calls. For the ECB and CBC modes */
159 | /* each individual call within a series of incremental calls must */
160 | /* process only full blocks (i.e. len must be a multiple of 16) but */
161 | /* the CFB, OFB and CTR mode calls can handle multiple incremental */
162 | /* calls of any length. Each mode is reset when a new AES key is */
163 | /* set but ECB needs no reset and CBC can be reset without setting */
164 | /* a new key by setting a new IV value. To reset CFB, OFB and CTR */
165 | /* without setting the key, aes_mode_reset() must be called and the */
166 | /* IV must be set. NOTE: All these calls update the IV on exit so */
167 | /* this has to be reset if a new operation with the same IV as the */
168 | /* previous one is required (or decryption follows encryption with */
169 | /* the same IV array). */
170 |
171 | AES_RETURN aes_test_alignment_detection(unsigned int n);
172 |
173 | AES_RETURN aes_ecb_encrypt(const unsigned char *ibuf, unsigned char *obuf,
174 | int len, const aes_encrypt_ctx cx[1]);
175 |
176 | AES_RETURN aes_ecb_decrypt(const unsigned char *ibuf, unsigned char *obuf,
177 | int len, const aes_decrypt_ctx cx[1]);
178 |
179 | AES_RETURN aes_cbc_encrypt(const unsigned char *ibuf, unsigned char *obuf,
180 | int len, unsigned char *iv, const aes_encrypt_ctx cx[1]);
181 |
182 | AES_RETURN aes_cbc_decrypt(const unsigned char *ibuf, unsigned char *obuf,
183 | int len, unsigned char *iv, const aes_decrypt_ctx cx[1]);
184 |
185 | AES_RETURN aes_mode_reset(aes_encrypt_ctx cx[1]);
186 |
187 | AES_RETURN aes_cfb_encrypt(const unsigned char *ibuf, unsigned char *obuf,
188 | int len, unsigned char *iv, aes_encrypt_ctx cx[1]);
189 |
190 | AES_RETURN aes_cfb_decrypt(const unsigned char *ibuf, unsigned char *obuf,
191 | int len, unsigned char *iv, aes_encrypt_ctx cx[1]);
192 |
193 | #define aes_ofb_encrypt aes_ofb_crypt
194 | #define aes_ofb_decrypt aes_ofb_crypt
195 |
196 | AES_RETURN aes_ofb_crypt(const unsigned char *ibuf, unsigned char *obuf,
197 | int len, unsigned char *iv, aes_encrypt_ctx cx[1]);
198 |
199 | typedef void cbuf_inc(unsigned char *cbuf);
200 |
201 | #define aes_ctr_encrypt aes_ctr_crypt
202 | #define aes_ctr_decrypt aes_ctr_crypt
203 |
204 | AES_RETURN aes_ctr_crypt(const unsigned char *ibuf, unsigned char *obuf,
205 | int len, unsigned char *cbuf, cbuf_inc ctr_inc, aes_encrypt_ctx cx[1]);
206 |
207 | #endif
208 |
209 | #if 0
210 | # define ADD_AESNI_MODE_CALLS
211 | #endif
212 |
213 | #if 0 && defined( ADD_AESNI_MODE_CALLS )
214 | # define USE_AES_CONTEXT
215 | #endif
216 |
217 | #ifdef ADD_AESNI_MODE_CALLS
218 | # ifdef USE_AES_CONTEXT
219 |
220 | AES_RETURN aes_CBC_encrypt(const unsigned char *in,
221 | unsigned char *out,
222 | unsigned char ivec[16],
223 | unsigned long length,
224 | const aes_encrypt_ctx cx[1]);
225 |
226 | AES_RETURN aes_CBC_decrypt(const unsigned char *in,
227 | unsigned char *out,
228 | unsigned char ivec[16],
229 | unsigned long length,
230 | const aes_decrypt_ctx cx[1]);
231 |
232 | AES_RETURN AES_CTR_encrypt(const unsigned char *in,
233 | unsigned char *out,
234 | const unsigned char ivec[8],
235 | const unsigned char nonce[4],
236 | unsigned long length,
237 | const aes_encrypt_ctx cx[1]);
238 |
239 | # else
240 |
241 | void aes_CBC_encrypt(const unsigned char *in,
242 | unsigned char *out,
243 | unsigned char ivec[16],
244 | unsigned long length,
245 | unsigned char *key,
246 | int number_of_rounds);
247 |
248 | void aes_CBC_decrypt(const unsigned char *in,
249 | unsigned char *out,
250 | unsigned char ivec[16],
251 | unsigned long length,
252 | unsigned char *key,
253 | int number_of_rounds);
254 |
255 | void AES_CTR_encrypt(const unsigned char *in,
256 | unsigned char *out,
257 | const unsigned char ivec[8],
258 | const unsigned char nonce[4],
259 | unsigned long length,
260 | const unsigned char *key,
261 | int number_of_rounds);
262 |
263 | # endif
264 | #endif
265 |
266 | #if defined(__cplusplus)
267 | }
268 | #endif
269 |
270 | #endif
271 |
--------------------------------------------------------------------------------
/Replica/SSZipArchive/minizip/aes/aes_ni.h:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright (c) 1998-2013, Brian Gladman, Worcester, UK. All rights reserved.
3 |
4 | The redistribution and use of this software (with or without changes)
5 | is allowed without the payment of fees or royalties provided that:
6 |
7 | source code distributions include the above copyright notice, this
8 | list of conditions and the following disclaimer;
9 |
10 | binary distributions include the above copyright notice, this list
11 | of conditions and the following disclaimer in their documentation.
12 |
13 | This software is provided 'as is' with no explicit or implied warranties
14 | in respect of its operation, including, but not limited to, correctness
15 | and fitness for purpose.
16 | ---------------------------------------------------------------------------
17 | Issue Date: 13/11/2013
18 | */
19 |
20 | #ifndef AES_NI_H
21 | #define AES_NI_H
22 |
23 | #define USE_AES_CONTEXT
24 |
25 | #include "aesopt.h"
26 |
27 | #if defined( USE_INTEL_AES_IF_PRESENT )
28 |
29 | /* map names in C code to make them internal ('name' -> 'aes_name_i') */
30 | #define aes_xi(x) aes_ ## x ## _i
31 |
32 | /* map names here to provide the external API ('name' -> 'aes_name') */
33 | #define aes_ni(x) aes_ ## x
34 |
35 | AES_RETURN aes_ni(encrypt_key128)(const unsigned char *key, aes_encrypt_ctx cx[1]);
36 | AES_RETURN aes_ni(encrypt_key192)(const unsigned char *key, aes_encrypt_ctx cx[1]);
37 | AES_RETURN aes_ni(encrypt_key256)(const unsigned char *key, aes_encrypt_ctx cx[1]);
38 |
39 | AES_RETURN aes_ni(decrypt_key128)(const unsigned char *key, aes_decrypt_ctx cx[1]);
40 | AES_RETURN aes_ni(decrypt_key192)(const unsigned char *key, aes_decrypt_ctx cx[1]);
41 | AES_RETURN aes_ni(decrypt_key256)(const unsigned char *key, aes_decrypt_ctx cx[1]);
42 |
43 | AES_RETURN aes_ni(encrypt)(const unsigned char *in, unsigned char *out, const aes_encrypt_ctx cx[1]);
44 | AES_RETURN aes_ni(decrypt)(const unsigned char *in, unsigned char *out, const aes_decrypt_ctx cx[1]);
45 |
46 | AES_RETURN aes_xi(encrypt_key128)(const unsigned char *key, aes_encrypt_ctx cx[1]);
47 | AES_RETURN aes_xi(encrypt_key192)(const unsigned char *key, aes_encrypt_ctx cx[1]);
48 | AES_RETURN aes_xi(encrypt_key256)(const unsigned char *key, aes_encrypt_ctx cx[1]);
49 |
50 | AES_RETURN aes_xi(decrypt_key128)(const unsigned char *key, aes_decrypt_ctx cx[1]);
51 | AES_RETURN aes_xi(decrypt_key192)(const unsigned char *key, aes_decrypt_ctx cx[1]);
52 | AES_RETURN aes_xi(decrypt_key256)(const unsigned char *key, aes_decrypt_ctx cx[1]);
53 |
54 | AES_RETURN aes_xi(encrypt)(const unsigned char *in, unsigned char *out, const aes_encrypt_ctx cx[1]);
55 | AES_RETURN aes_xi(decrypt)(const unsigned char *in, unsigned char *out, const aes_decrypt_ctx cx[1]);
56 |
57 | #endif
58 |
59 | #endif
60 |
--------------------------------------------------------------------------------
/Replica/SSZipArchive/minizip/aes/aestab.h:
--------------------------------------------------------------------------------
1 | /*
2 | ---------------------------------------------------------------------------
3 | Copyright (c) 1998-2013, Brian Gladman, Worcester, UK. All rights reserved.
4 |
5 | The redistribution and use of this software (with or without changes)
6 | is allowed without the payment of fees or royalties provided that:
7 |
8 | source code distributions include the above copyright notice, this
9 | list of conditions and the following disclaimer;
10 |
11 | binary distributions include the above copyright notice, this list
12 | of conditions and the following disclaimer in their documentation.
13 |
14 | This software is provided 'as is' with no explicit or implied warranties
15 | in respect of its operation, including, but not limited to, correctness
16 | and fitness for purpose.
17 | ---------------------------------------------------------------------------
18 | Issue Date: 20/12/2007
19 |
20 | This file contains the code for declaring the tables needed to implement
21 | AES. The file aesopt.h is assumed to be included before this header file.
22 | If there are no global variables, the definitions here can be used to put
23 | the AES tables in a structure so that a pointer can then be added to the
24 | AES context to pass them to the AES routines that need them. If this
25 | facility is used, the calling program has to ensure that this pointer is
26 | managed appropriately. In particular, the value of the t_dec(in,it) item
27 | in the table structure must be set to zero in order to ensure that the
28 | tables are initialised. In practice the three code sequences in aeskey.c
29 | that control the calls to aes_init() and the aes_init() routine itself will
30 | have to be changed for a specific implementation. If global variables are
31 | available it will generally be preferable to use them with the precomputed
32 | STATIC_TABLES option that uses static global tables.
33 |
34 | The following defines can be used to control the way the tables
35 | are defined, initialised and used in embedded environments that
36 | require special features for these purposes
37 |
38 | the 't_dec' construction is used to declare fixed table arrays
39 | the 't_set' construction is used to set fixed table values
40 | the 't_use' construction is used to access fixed table values
41 |
42 | 256 byte tables:
43 |
44 | t_xxx(s,box) => forward S box
45 | t_xxx(i,box) => inverse S box
46 |
47 | 256 32-bit word OR 4 x 256 32-bit word tables:
48 |
49 | t_xxx(f,n) => forward normal round
50 | t_xxx(f,l) => forward last round
51 | t_xxx(i,n) => inverse normal round
52 | t_xxx(i,l) => inverse last round
53 | t_xxx(l,s) => key schedule table
54 | t_xxx(i,m) => key schedule table
55 |
56 | Other variables and tables:
57 |
58 | t_xxx(r,c) => the rcon table
59 | */
60 |
61 | #if !defined( _AESTAB_H )
62 | #define _AESTAB_H
63 |
64 | #if defined(__cplusplus)
65 | extern "C" {
66 | #endif
67 |
68 | #define t_dec(m,n) t_##m##n
69 | #define t_set(m,n) t_##m##n
70 | #define t_use(m,n) t_##m##n
71 |
72 | #if defined(STATIC_TABLES)
73 | # if !defined( __GNUC__ ) && (defined( __MSDOS__ ) || defined( __WIN16__ ))
74 | /* make tables far data to avoid using too much DGROUP space (PG) */
75 | # define CONST const far
76 | # else
77 | # define CONST const
78 | # endif
79 | #else
80 | # define CONST
81 | #endif
82 |
83 | #if defined(DO_TABLES)
84 | # define EXTERN
85 | #else
86 | # define EXTERN extern
87 | #endif
88 |
89 | #if defined(_MSC_VER) && defined(TABLE_ALIGN)
90 | #define ALIGN __declspec(align(TABLE_ALIGN))
91 | #else
92 | #define ALIGN
93 | #endif
94 |
95 | #if defined( __WATCOMC__ ) && ( __WATCOMC__ >= 1100 )
96 | # define XP_DIR __cdecl
97 | #else
98 | # define XP_DIR
99 | #endif
100 |
101 | #if defined(DO_TABLES) && defined(STATIC_TABLES)
102 | #define d_1(t,n,b,e) EXTERN ALIGN CONST XP_DIR t n[256] = b(e)
103 | #define d_4(t,n,b,e,f,g,h) EXTERN ALIGN CONST XP_DIR t n[4][256] = { b(e), b(f), b(g), b(h) }
104 | EXTERN ALIGN CONST uint32_t t_dec(r,c)[RC_LENGTH] = rc_data(w0);
105 | #else
106 | #define d_1(t,n,b,e) EXTERN ALIGN CONST XP_DIR t n[256]
107 | #define d_4(t,n,b,e,f,g,h) EXTERN ALIGN CONST XP_DIR t n[4][256]
108 | EXTERN ALIGN CONST uint32_t t_dec(r,c)[RC_LENGTH];
109 | #endif
110 |
111 | #if defined( SBX_SET )
112 | d_1(uint8_t, t_dec(s,box), sb_data, h0);
113 | #endif
114 | #if defined( ISB_SET )
115 | d_1(uint8_t, t_dec(i,box), isb_data, h0);
116 | #endif
117 |
118 | #if defined( FT1_SET )
119 | d_1(uint32_t, t_dec(f,n), sb_data, u0);
120 | #endif
121 | #if defined( FT4_SET )
122 | d_4(uint32_t, t_dec(f,n), sb_data, u0, u1, u2, u3);
123 | #endif
124 |
125 | #if defined( FL1_SET )
126 | d_1(uint32_t, t_dec(f,l), sb_data, w0);
127 | #endif
128 | #if defined( FL4_SET )
129 | d_4(uint32_t, t_dec(f,l), sb_data, w0, w1, w2, w3);
130 | #endif
131 |
132 | #if defined( IT1_SET )
133 | d_1(uint32_t, t_dec(i,n), isb_data, v0);
134 | #endif
135 | #if defined( IT4_SET )
136 | d_4(uint32_t, t_dec(i,n), isb_data, v0, v1, v2, v3);
137 | #endif
138 |
139 | #if defined( IL1_SET )
140 | d_1(uint32_t, t_dec(i,l), isb_data, w0);
141 | #endif
142 | #if defined( IL4_SET )
143 | d_4(uint32_t, t_dec(i,l), isb_data, w0, w1, w2, w3);
144 | #endif
145 |
146 | #if defined( LS1_SET )
147 | #if defined( FL1_SET )
148 | #undef LS1_SET
149 | #else
150 | d_1(uint32_t, t_dec(l,s), sb_data, w0);
151 | #endif
152 | #endif
153 |
154 | #if defined( LS4_SET )
155 | #if defined( FL4_SET )
156 | #undef LS4_SET
157 | #else
158 | d_4(uint32_t, t_dec(l,s), sb_data, w0, w1, w2, w3);
159 | #endif
160 | #endif
161 |
162 | #if defined( IM1_SET )
163 | d_1(uint32_t, t_dec(i,m), mm_data, v0);
164 | #endif
165 | #if defined( IM4_SET )
166 | d_4(uint32_t, t_dec(i,m), mm_data, v0, v1, v2, v3);
167 | #endif
168 |
169 | #if defined(__cplusplus)
170 | }
171 | #endif
172 |
173 | #endif
174 |
--------------------------------------------------------------------------------
/Replica/SSZipArchive/minizip/aes/brg_endian.h:
--------------------------------------------------------------------------------
1 | /*
2 | ---------------------------------------------------------------------------
3 | Copyright (c) 1998-2013, Brian Gladman, Worcester, UK. All rights reserved.
4 |
5 | The redistribution and use of this software (with or without changes)
6 | is allowed without the payment of fees or royalties provided that:
7 |
8 | source code distributions include the above copyright notice, this
9 | list of conditions and the following disclaimer;
10 |
11 | binary distributions include the above copyright notice, this list
12 | of conditions and the following disclaimer in their documentation.
13 |
14 | This software is provided 'as is' with no explicit or implied warranties
15 | in respect of its operation, including, but not limited to, correctness
16 | and fitness for purpose.
17 | ---------------------------------------------------------------------------
18 | Issue Date: 20/12/2007
19 | */
20 |
21 | #ifndef _BRG_ENDIAN_H
22 | #define _BRG_ENDIAN_H
23 |
24 | #define IS_BIG_ENDIAN 4321 /* byte 0 is most significant (mc68k) */
25 | #define IS_LITTLE_ENDIAN 1234 /* byte 0 is least significant (i386) */
26 |
27 | /* Include files where endian defines and byteswap functions may reside */
28 | #if defined( __sun )
29 | # include
30 | #elif defined( __FreeBSD__ ) || defined( __OpenBSD__ ) || defined( __NetBSD__ )
31 | # include
32 | #elif defined( BSD ) && ( BSD >= 199103 ) || defined( __APPLE__ ) || \
33 | defined( __CYGWIN32__ ) || defined( __DJGPP__ ) || defined( __osf__ ) || \
34 | defined(__pnacl__)
35 | # include
36 | #elif defined( __linux__ ) || defined( __GNUC__ ) || defined( __GNU_LIBRARY__ )
37 | # if !defined( __MINGW32__ ) && !defined( _AIX )
38 | # include
39 | # if !defined( __BEOS__ )
40 | # include
41 | # endif
42 | # endif
43 | #endif
44 |
45 | /* Now attempt to set the define for platform byte order using any */
46 | /* of the four forms SYMBOL, _SYMBOL, __SYMBOL & __SYMBOL__, which */
47 | /* seem to encompass most endian symbol definitions */
48 |
49 | #if defined( BIG_ENDIAN ) && defined( LITTLE_ENDIAN )
50 | # if defined( BYTE_ORDER ) && BYTE_ORDER == BIG_ENDIAN
51 | # define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
52 | # elif defined( BYTE_ORDER ) && BYTE_ORDER == LITTLE_ENDIAN
53 | # define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
54 | # endif
55 | #elif defined( BIG_ENDIAN )
56 | # define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
57 | #elif defined( LITTLE_ENDIAN )
58 | # define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
59 | #endif
60 |
61 | #if defined( _BIG_ENDIAN ) && defined( _LITTLE_ENDIAN )
62 | # if defined( _BYTE_ORDER ) && _BYTE_ORDER == _BIG_ENDIAN
63 | # define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
64 | # elif defined( _BYTE_ORDER ) && _BYTE_ORDER == _LITTLE_ENDIAN
65 | # define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
66 | # endif
67 | #elif defined( _BIG_ENDIAN )
68 | # define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
69 | #elif defined( _LITTLE_ENDIAN )
70 | # define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
71 | #endif
72 |
73 | #if defined( __BIG_ENDIAN ) && defined( __LITTLE_ENDIAN )
74 | # if defined( __BYTE_ORDER ) && __BYTE_ORDER == __BIG_ENDIAN
75 | # define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
76 | # elif defined( __BYTE_ORDER ) && __BYTE_ORDER == __LITTLE_ENDIAN
77 | # define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
78 | # endif
79 | #elif defined( __BIG_ENDIAN )
80 | # define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
81 | #elif defined( __LITTLE_ENDIAN )
82 | # define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
83 | #endif
84 |
85 | #if defined( __BIG_ENDIAN__ ) && defined( __LITTLE_ENDIAN__ )
86 | # if defined( __BYTE_ORDER__ ) && __BYTE_ORDER__ == __BIG_ENDIAN__
87 | # define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
88 | # elif defined( __BYTE_ORDER__ ) && __BYTE_ORDER__ == __LITTLE_ENDIAN__
89 | # define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
90 | # endif
91 | #elif defined( __BIG_ENDIAN__ )
92 | # define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
93 | #elif defined( __LITTLE_ENDIAN__ )
94 | # define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
95 | #endif
96 |
97 | /* if the platform byte order could not be determined, then try to */
98 | /* set this define using common machine defines */
99 | #if !defined(PLATFORM_BYTE_ORDER)
100 |
101 | #if defined( __alpha__ ) || defined( __alpha ) || defined( i386 ) || \
102 | defined( __i386__ ) || defined( _M_I86 ) || defined( _M_IX86 ) || \
103 | defined( __OS2__ ) || defined( sun386 ) || defined( __TURBOC__ ) || \
104 | defined( vax ) || defined( vms ) || defined( VMS ) || \
105 | defined( __VMS ) || defined( _M_X64 )
106 | # define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
107 |
108 | #elif defined( AMIGA ) || defined( applec ) || defined( __AS400__ ) || \
109 | defined( _CRAY ) || defined( __hppa ) || defined( __hp9000 ) || \
110 | defined( ibm370 ) || defined( mc68000 ) || defined( m68k ) || \
111 | defined( __MRC__ ) || defined( __MVS__ ) || defined( __MWERKS__ ) || \
112 | defined( sparc ) || defined( __sparc) || defined( SYMANTEC_C ) || \
113 | defined( __VOS__ ) || defined( __TIGCC__ ) || defined( __TANDEM ) || \
114 | defined( THINK_C ) || defined( __VMCMS__ ) || defined( _AIX )
115 | # define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
116 |
117 | #elif 0 /* **** EDIT HERE IF NECESSARY **** */
118 | # define PLATFORM_BYTE_ORDER IS_LITTLE_ENDIAN
119 | #elif 0 /* **** EDIT HERE IF NECESSARY **** */
120 | # define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
121 | #else
122 | # error Please edit lines 126 or 128 in brg_endian.h to set the platform byte order
123 | #endif
124 |
125 | #endif
126 |
127 | #endif
128 |
--------------------------------------------------------------------------------
/Replica/SSZipArchive/minizip/aes/brg_types.h:
--------------------------------------------------------------------------------
1 | /*
2 | ---------------------------------------------------------------------------
3 | Copyright (c) 1998-2013, Brian Gladman, Worcester, UK. All rights reserved.
4 |
5 | The redistribution and use of this software (with or without changes)
6 | is allowed without the payment of fees or royalties provided that:
7 |
8 | source code distributions include the above copyright notice, this
9 | list of conditions and the following disclaimer;
10 |
11 | binary distributions include the above copyright notice, this list
12 | of conditions and the following disclaimer in their documentation.
13 |
14 | This software is provided 'as is' with no explicit or implied warranties
15 | in respect of its operation, including, but not limited to, correctness
16 | and fitness for purpose.
17 | ---------------------------------------------------------------------------
18 | Issue Date: 20/12/2007
19 |
20 | The unsigned integer types defined here are of the form uint_t where
21 | is the length of the type; for example, the unsigned 32-bit type is
22 | 'uint32_t'. These are NOT the same as the 'C99 integer types' that are
23 | defined in the inttypes.h and stdint.h headers since attempts to use these
24 | types have shown that support for them is still highly variable. However,
25 | since the latter are of the form uint_t, a regular expression search
26 | and replace (in VC++ search on 'uint_{:z}t' and replace with 'uint\1_t')
27 | can be used to convert the types used here to the C99 standard types.
28 | */
29 |
30 | #ifndef _BRG_TYPES_H
31 | #define _BRG_TYPES_H
32 |
33 | #if defined(__cplusplus)
34 | extern "C" {
35 | #endif
36 |
37 | #include
38 | #include
39 |
40 | #if defined( _MSC_VER ) && ( _MSC_VER >= 1300 )
41 | # include
42 | # define ptrint_t intptr_t
43 | #elif defined( __ECOS__ )
44 | # define intptr_t unsigned int
45 | # define ptrint_t intptr_t
46 | #elif defined( __GNUC__ ) && ( __GNUC__ >= 3 )
47 | # define ptrint_t intptr_t
48 | #else
49 | # define ptrint_t int
50 | #endif
51 |
52 | #ifndef BRG_UI32
53 | # define BRG_UI32
54 | # if UINT_MAX == 4294967295u
55 | # define li_32(h) 0x##h##u
56 | # elif ULONG_MAX == 4294967295u
57 | # define li_32(h) 0x##h##ul
58 | # elif defined( _CRAY )
59 | # error This code needs 32-bit data types, which Cray machines do not provide
60 | # else
61 | # error Please define uint32_t as a 32-bit unsigned integer type in brg_types.h
62 | # endif
63 | #endif
64 |
65 | #ifndef BRG_UI64
66 | # if defined( __BORLANDC__ ) && !defined( __MSDOS__ )
67 | # define BRG_UI64
68 | # define li_64(h) 0x##h##ui64
69 | # elif defined( _MSC_VER ) && ( _MSC_VER < 1300 ) /* 1300 == VC++ 7.0 */
70 | # define BRG_UI64
71 | # define li_64(h) 0x##h##ui64
72 | # elif defined( __sun ) && defined( ULONG_MAX ) && ULONG_MAX == 0xfffffffful
73 | # define BRG_UI64
74 | # define li_64(h) 0x##h##ull
75 | # elif defined( __MVS__ )
76 | # define BRG_UI64
77 | # define li_64(h) 0x##h##ull
78 | # elif defined( UINT_MAX ) && UINT_MAX > 4294967295u
79 | # if UINT_MAX == 18446744073709551615u
80 | # define BRG_UI64
81 | # define li_64(h) 0x##h##u
82 | # endif
83 | # elif defined( ULONG_MAX ) && ULONG_MAX > 4294967295u
84 | # if ULONG_MAX == 18446744073709551615ul
85 | # define BRG_UI64
86 | # define li_64(h) 0x##h##ul
87 | # endif
88 | # elif defined( ULLONG_MAX ) && ULLONG_MAX > 4294967295u
89 | # if ULLONG_MAX == 18446744073709551615ull
90 | # define BRG_UI64
91 | # define li_64(h) 0x##h##ull
92 | # endif
93 | # elif defined( ULONG_LONG_MAX ) && ULONG_LONG_MAX > 4294967295u
94 | # if ULONG_LONG_MAX == 18446744073709551615ull
95 | # define BRG_UI64
96 | # define li_64(h) 0x##h##ull
97 | # endif
98 | # endif
99 | #endif
100 |
101 | #if !defined( BRG_UI64 )
102 | # if defined( NEED_UINT_64T )
103 | # error Please define uint64_t as an unsigned 64 bit type in brg_types.h
104 | # endif
105 | #endif
106 |
107 | #ifndef RETURN_VALUES
108 | # define RETURN_VALUES
109 | # if defined( DLL_EXPORT )
110 | # if defined( _MSC_VER ) || defined ( __INTEL_COMPILER )
111 | # define VOID_RETURN __declspec( dllexport ) void __stdcall
112 | # define INT_RETURN __declspec( dllexport ) int __stdcall
113 | # elif defined( __GNUC__ )
114 | # define VOID_RETURN __declspec( __dllexport__ ) void
115 | # define INT_RETURN __declspec( __dllexport__ ) int
116 | # else
117 | # error Use of the DLL is only available on the Microsoft, Intel and GCC compilers
118 | # endif
119 | # elif defined( DLL_IMPORT )
120 | # if defined( _MSC_VER ) || defined ( __INTEL_COMPILER )
121 | # define VOID_RETURN __declspec( dllimport ) void __stdcall
122 | # define INT_RETURN __declspec( dllimport ) int __stdcall
123 | # elif defined( __GNUC__ )
124 | # define VOID_RETURN __declspec( __dllimport__ ) void
125 | # define INT_RETURN __declspec( __dllimport__ ) int
126 | # else
127 | # error Use of the DLL is only available on the Microsoft, Intel and GCC compilers
128 | # endif
129 | # elif defined( __WATCOMC__ )
130 | # define VOID_RETURN void __cdecl
131 | # define INT_RETURN int __cdecl
132 | # else
133 | # define VOID_RETURN void
134 | # define INT_RETURN int
135 | # endif
136 | #endif
137 |
138 | /* These defines are used to detect and set the memory alignment of pointers.
139 | Note that offsets are in bytes.
140 |
141 | ALIGN_OFFSET(x,n) return the positive or zero offset of
142 | the memory addressed by the pointer 'x'
143 | from an address that is aligned on an
144 | 'n' byte boundary ('n' is a power of 2)
145 |
146 | ALIGN_FLOOR(x,n) return a pointer that points to memory
147 | that is aligned on an 'n' byte boundary
148 | and is not higher than the memory address
149 | pointed to by 'x' ('n' is a power of 2)
150 |
151 | ALIGN_CEIL(x,n) return a pointer that points to memory
152 | that is aligned on an 'n' byte boundary
153 | and is not lower than the memory address
154 | pointed to by 'x' ('n' is a power of 2)
155 | */
156 |
157 | #define ALIGN_OFFSET(x,n) (((ptrint_t)(x)) & ((n) - 1))
158 | #define ALIGN_FLOOR(x,n) ((uint8_t*)(x) - ( ((ptrint_t)(x)) & ((n) - 1)))
159 | #define ALIGN_CEIL(x,n) ((uint8_t*)(x) + (-((ptrint_t)(x)) & ((n) - 1)))
160 |
161 | /* These defines are used to declare buffers in a way that allows
162 | faster operations on longer variables to be used. In all these
163 | defines 'size' must be a power of 2 and >= 8. NOTE that the
164 | buffer size is in bytes but the type length is in bits
165 |
166 | UNIT_TYPEDEF(x,size) declares a variable 'x' of length
167 | 'size' bits
168 |
169 | BUFR_TYPEDEF(x,size,bsize) declares a buffer 'x' of length 'bsize'
170 | bytes defined as an array of variables
171 | each of 'size' bits (bsize must be a
172 | multiple of size / 8)
173 |
174 | UNIT_CAST(x,size) casts a variable to a type of
175 | length 'size' bits
176 |
177 | UPTR_CAST(x,size) casts a pointer to a pointer to a
178 | varaiable of length 'size' bits
179 | */
180 |
181 | #define UI_TYPE(size) uint##size##_t
182 | #define UNIT_TYPEDEF(x,size) typedef UI_TYPE(size) x
183 | #define BUFR_TYPEDEF(x,size,bsize) typedef UI_TYPE(size) x[bsize / (size >> 3)]
184 | #define UNIT_CAST(x,size) ((UI_TYPE(size) )(x))
185 | #define UPTR_CAST(x,size) ((UI_TYPE(size)*)(x))
186 |
187 | #if defined(__cplusplus)
188 | }
189 | #endif
190 |
191 | #endif
192 |
--------------------------------------------------------------------------------
/Replica/SSZipArchive/minizip/aes/fileenc.c:
--------------------------------------------------------------------------------
1 | /*
2 | ---------------------------------------------------------------------------
3 | Copyright (c) 2002, Dr Brian Gladman < >, Worcester, UK.
4 | All rights reserved.
5 |
6 | LICENSE TERMS
7 |
8 | The free distribution and use of this software in both source and binary
9 | form is allowed (with or without changes) provided that:
10 |
11 | 1. distributions of this source code include the above copyright
12 | notice, this list of conditions and the following disclaimer;
13 |
14 | 2. distributions in binary form include the above copyright
15 | notice, this list of conditions and the following disclaimer
16 | in the documentation and/or other associated materials;
17 |
18 | 3. the copyright holder's name is not used to endorse products
19 | built using this software without specific written permission.
20 |
21 | ALTERNATIVELY, provided that this notice is retained in full, this product
22 | may be distributed under the terms of the GNU General Public License (GPL),
23 | in which case the provisions of the GPL apply INSTEAD OF those given above.
24 |
25 | DISCLAIMER
26 |
27 | This software is provided 'as is' with no explicit or implied warranties
28 | in respect of its properties, including, but not limited to, correctness
29 | and/or fitness for purpose.
30 | -------------------------------------------------------------------------
31 | Issue Date: 24/01/2003
32 |
33 | This file implements password based file encryption and authentication
34 | using AES in CTR mode, HMAC-SHA1 authentication and RFC2898 password
35 | based key derivation.
36 |
37 | */
38 |
39 | #include
40 |
41 | #include "fileenc.h"
42 |
43 | #if defined(__cplusplus)
44 | extern "C"
45 | {
46 | #endif
47 |
48 | /* subroutine for data encryption/decryption */
49 | /* this could be speeded up a lot by aligning */
50 | /* buffers and using 32 bit operations */
51 |
52 | static void encr_data(unsigned char data[], unsigned long d_len, fcrypt_ctx cx[1])
53 | {
54 | unsigned int i = 0, pos = cx->encr_pos;
55 |
56 | while (i < d_len)
57 | {
58 | if (pos == AES_BLOCK_SIZE)
59 | {
60 | unsigned int j = 0;
61 | /* increment encryption nonce */
62 | while (j < 8 && !++cx->nonce[j])
63 | ++j;
64 | /* encrypt the nonce to form next xor buffer */
65 | aes_encrypt(cx->nonce, cx->encr_bfr, cx->encr_ctx);
66 | pos = 0;
67 | }
68 |
69 | data[i++] ^= cx->encr_bfr[pos++];
70 | }
71 |
72 | cx->encr_pos = pos;
73 | }
74 |
75 | int fcrypt_init(
76 | int mode, /* the mode to be used (input) */
77 | const unsigned char pwd[], /* the user specified password (input) */
78 | unsigned int pwd_len, /* the length of the password (input) */
79 | const unsigned char salt[], /* the salt (input) */
80 | #ifdef PASSWORD_VERIFIER
81 | unsigned char pwd_ver[PWD_VER_LENGTH], /* 2 byte password verifier (output) */
82 | #endif
83 | fcrypt_ctx cx[1]) /* the file encryption context (output) */
84 | { unsigned char kbuf[2 * MAX_KEY_LENGTH + PWD_VER_LENGTH];
85 |
86 | if (pwd_len > MAX_PWD_LENGTH)
87 | return PASSWORD_TOO_LONG;
88 |
89 | if (mode < 1 || mode > 3)
90 | return BAD_MODE;
91 |
92 | cx->mode = mode;
93 | cx->pwd_len = pwd_len;
94 |
95 | /* derive the encryption and authentication keys and the password verifier */
96 | derive_key(pwd, pwd_len, salt, SALT_LENGTH(mode), KEYING_ITERATIONS,
97 | kbuf, 2 * KEY_LENGTH(mode) + PWD_VER_LENGTH);
98 |
99 | /* initialise the encryption nonce and buffer pos */
100 | cx->encr_pos = AES_BLOCK_SIZE;
101 | /* if we need a random component in the encryption */
102 | /* nonce, this is where it would have to be set */
103 | memset(cx->nonce, 0, AES_BLOCK_SIZE * sizeof(unsigned char));
104 |
105 | /* initialise for encryption using key 1 */
106 | aes_encrypt_key(kbuf, KEY_LENGTH(mode), cx->encr_ctx);
107 |
108 | /* initialise for authentication using key 2 */
109 | hmac_sha_begin(HMAC_SHA1, cx->auth_ctx);
110 | hmac_sha_key(kbuf + KEY_LENGTH(mode), KEY_LENGTH(mode), cx->auth_ctx);
111 |
112 | #ifdef PASSWORD_VERIFIER
113 | memcpy(pwd_ver, kbuf + 2 * KEY_LENGTH(mode), PWD_VER_LENGTH);
114 | #endif
115 |
116 | return GOOD_RETURN;
117 | }
118 |
119 | /* perform 'in place' encryption and authentication */
120 |
121 | void fcrypt_encrypt(unsigned char data[], unsigned int data_len, fcrypt_ctx cx[1])
122 | {
123 | encr_data(data, data_len, cx);
124 | hmac_sha_data(data, data_len, cx->auth_ctx);
125 | }
126 |
127 | /* perform 'in place' authentication and decryption */
128 |
129 | void fcrypt_decrypt(unsigned char data[], unsigned int data_len, fcrypt_ctx cx[1])
130 | {
131 | hmac_sha_data(data, data_len, cx->auth_ctx);
132 | encr_data(data, data_len, cx);
133 | }
134 |
135 | /* close encryption/decryption and return the MAC value */
136 |
137 | int fcrypt_end(unsigned char mac[], fcrypt_ctx cx[1])
138 | {
139 | hmac_sha_end(mac, MAC_LENGTH(cx->mode), cx->auth_ctx);
140 | return MAC_LENGTH(cx->mode); /* return MAC length in bytes */
141 | }
142 |
143 | #if defined(__cplusplus)
144 | }
145 | #endif
146 |
--------------------------------------------------------------------------------
/Replica/SSZipArchive/minizip/aes/fileenc.h:
--------------------------------------------------------------------------------
1 | /*
2 | ---------------------------------------------------------------------------
3 | Copyright (c) 2002, Dr Brian Gladman < >, Worcester, UK.
4 | All rights reserved.
5 |
6 | LICENSE TERMS
7 |
8 | The free distribution and use of this software in both source and binary
9 | form is allowed (with or without changes) provided that:
10 |
11 | 1. distributions of this source code include the above copyright
12 | notice, this list of conditions and the following disclaimer;
13 |
14 | 2. distributions in binary form include the above copyright
15 | notice, this list of conditions and the following disclaimer
16 | in the documentation and/or other associated materials;
17 |
18 | 3. the copyright holder's name is not used to endorse products
19 | built using this software without specific written permission.
20 |
21 | ALTERNATIVELY, provided that this notice is retained in full, this product
22 | may be distributed under the terms of the GNU General Public License (GPL),
23 | in which case the provisions of the GPL apply INSTEAD OF those given above.
24 |
25 | DISCLAIMER
26 |
27 | This software is provided 'as is' with no explicit or implied warranties
28 | in respect of its properties, including, but not limited to, correctness
29 | and/or fitness for purpose.
30 | ---------------------------------------------------------------------------
31 | Issue Date: 24/01/2003
32 |
33 | This file contains the header file for fileenc.c, which implements password
34 | based file encryption and authentication using AES in CTR mode, HMAC-SHA1
35 | authentication and RFC2898 password based key derivation.
36 | */
37 |
38 | #ifndef _FENC_H
39 | #define _FENC_H
40 |
41 | #include "aes.h"
42 | #include "hmac.h"
43 | #include "pwd2key.h"
44 |
45 | #define PASSWORD_VERIFIER
46 |
47 | #define MAX_KEY_LENGTH 32
48 | #define MAX_PWD_LENGTH 128
49 | #define MAX_SALT_LENGTH 16
50 | #define KEYING_ITERATIONS 1000
51 |
52 | #ifdef PASSWORD_VERIFIER
53 | #define PWD_VER_LENGTH 2
54 | #else
55 | #define PWD_VER_LENGTH 0
56 | #endif
57 |
58 | #define GOOD_RETURN 0
59 | #define PASSWORD_TOO_LONG -100
60 | #define BAD_MODE -101
61 |
62 | /*
63 | Field lengths (in bytes) versus File Encryption Mode (0 < mode < 4)
64 |
65 | Mode Key Salt MAC Overhead
66 | 1 16 8 10 18
67 | 2 24 12 10 22
68 | 3 32 16 10 26
69 |
70 | The following macros assume that the mode value is correct.
71 | */
72 |
73 | #define KEY_LENGTH(mode) (8 * (mode & 3) + 8)
74 | #define SALT_LENGTH(mode) (4 * (mode & 3) + 4)
75 | #define MAC_LENGTH(mode) (10)
76 |
77 | /* the context for file encryption */
78 |
79 | #if defined(__cplusplus)
80 | extern "C"
81 | {
82 | #endif
83 |
84 | typedef struct
85 | { unsigned char nonce[AES_BLOCK_SIZE]; /* the CTR nonce */
86 | unsigned char encr_bfr[AES_BLOCK_SIZE]; /* encrypt buffer */
87 | aes_encrypt_ctx encr_ctx[1]; /* encryption context */
88 | hmac_ctx auth_ctx[1]; /* authentication context */
89 | unsigned int encr_pos; /* block position (enc) */
90 | unsigned int pwd_len; /* password length */
91 | unsigned int mode; /* File encryption mode */
92 | } fcrypt_ctx;
93 |
94 | /* initialise file encryption or decryption */
95 |
96 | int fcrypt_init(
97 | int mode, /* the mode to be used (input) */
98 | const unsigned char pwd[], /* the user specified password (input) */
99 | unsigned int pwd_len, /* the length of the password (input) */
100 | const unsigned char salt[], /* the salt (input) */
101 | #ifdef PASSWORD_VERIFIER
102 | unsigned char pwd_ver[PWD_VER_LENGTH], /* 2 byte password verifier (output) */
103 | #endif
104 | fcrypt_ctx cx[1]); /* the file encryption context (output) */
105 |
106 | /* perform 'in place' encryption or decryption and authentication */
107 |
108 | void fcrypt_encrypt(unsigned char data[], unsigned int data_len, fcrypt_ctx cx[1]);
109 | void fcrypt_decrypt(unsigned char data[], unsigned int data_len, fcrypt_ctx cx[1]);
110 |
111 | /* close encryption/decryption and return the MAC value */
112 | /* the return value is the length of the MAC */
113 |
114 | int fcrypt_end(unsigned char mac[], /* the MAC value (output) */
115 | fcrypt_ctx cx[1]); /* the context (input) */
116 |
117 | #if defined(__cplusplus)
118 | }
119 | #endif
120 |
121 | #endif
122 |
--------------------------------------------------------------------------------
/Replica/SSZipArchive/minizip/aes/hmac.c:
--------------------------------------------------------------------------------
1 | /*
2 | ---------------------------------------------------------------------------
3 | Copyright (c) 1998-2010, Brian Gladman, Worcester, UK. All rights reserved.
4 |
5 | The redistribution and use of this software (with or without changes)
6 | is allowed without the payment of fees or royalties provided that:
7 |
8 | source code distributions include the above copyright notice, this
9 | list of conditions and the following disclaimer;
10 |
11 | binary distributions include the above copyright notice, this list
12 | of conditions and the following disclaimer in their documentation.
13 |
14 | This software is provided 'as is' with no explicit or implied warranties
15 | in respect of its operation, including, but not limited to, correctness
16 | and fitness for purpose.
17 | ---------------------------------------------------------------------------
18 | Issue Date: 20/12/2007
19 |
20 | This is an implementation of HMAC, the FIPS standard keyed hash function
21 | */
22 |
23 | #include "hmac.h"
24 |
25 | #if defined(__cplusplus)
26 | extern "C"
27 | {
28 | #endif
29 |
30 | /* initialise the HMAC context to zero */
31 | int hmac_sha_begin(enum hmac_hash hash, hmac_ctx cx[1])
32 | {
33 | memset(cx, 0, sizeof(hmac_ctx));
34 | switch(hash)
35 | {
36 | #ifdef SHA_1
37 | case HMAC_SHA1:
38 | cx->f_begin = (hf_begin *)sha1_begin;
39 | cx->f_hash = (hf_hash *)sha1_hash;
40 | cx->f_end = (hf_end *)sha1_end;
41 | cx->input_len = SHA1_BLOCK_SIZE;
42 | cx->output_len = SHA1_DIGEST_SIZE;
43 | break;
44 | #endif
45 | #ifdef SHA_224
46 | case HMAC_SHA224:
47 | cx->f_begin = (hf_begin *)sha224_begin;
48 | cx->f_hash = (hf_hash *)sha224_hash;
49 | cx->f_end = (hf_end *)sha224_end;
50 | cx->input_len = SHA224_BLOCK_SIZE;
51 | cx->output_len = SHA224_DIGEST_SIZE;
52 | break;
53 | #endif
54 | #ifdef SHA_256
55 | case HMAC_SHA256:
56 | cx->f_begin = (hf_begin *)sha256_begin;
57 | cx->f_hash = (hf_hash *)sha256_hash;
58 | cx->f_end = (hf_end *)sha256_end;
59 | cx->input_len = SHA256_BLOCK_SIZE;
60 | cx->output_len = SHA256_DIGEST_SIZE;
61 | break;
62 | #endif
63 | #ifdef SHA_384
64 | case HMAC_SHA384:
65 | cx->f_begin = (hf_begin *)sha384_begin;
66 | cx->f_hash = (hf_hash *)sha384_hash;
67 | cx->f_end = (hf_end *)sha384_end;
68 | cx->input_len = SHA384_BLOCK_SIZE;
69 | cx->output_len = SHA384_DIGEST_SIZE;
70 | break;
71 | #endif
72 | #ifdef SHA_512
73 | case HMAC_SHA512:
74 | cx->f_begin = (hf_begin *)sha512_begin;
75 | cx->f_hash = (hf_hash *)sha512_hash;
76 | cx->f_end = (hf_end *)sha512_end;
77 | cx->input_len = SHA512_BLOCK_SIZE;
78 | cx->output_len = SHA512_DIGEST_SIZE;
79 | break;
80 | case HMAC_SHA512_256:
81 | cx->f_begin = (hf_begin *)sha512_256_begin;
82 | cx->f_hash = (hf_hash *)sha512_256_hash;
83 | cx->f_end = (hf_end *)sha512_256_end;
84 | cx->input_len = SHA512_256_BLOCK_SIZE;
85 | cx->output_len = SHA512_256_DIGEST_SIZE;
86 | break;
87 | case HMAC_SHA512_224:
88 | cx->f_begin = (hf_begin *)sha512_224_begin;
89 | cx->f_hash = (hf_hash *)sha512_224_hash;
90 | cx->f_end = (hf_end *)sha512_224_end;
91 | cx->input_len = SHA512_224_BLOCK_SIZE;
92 | cx->output_len = SHA512_224_DIGEST_SIZE;
93 | break;
94 | case HMAC_SHA512_192:
95 | cx->f_begin = (hf_begin *)sha512_192_begin;
96 | cx->f_hash = (hf_hash *)sha512_192_hash;
97 | cx->f_end = (hf_end *)sha512_192_end;
98 | cx->input_len = SHA512_192_BLOCK_SIZE;
99 | cx->output_len = SHA512_192_DIGEST_SIZE;
100 | break;
101 | case HMAC_SHA512_128:
102 | cx->f_begin = (hf_begin *)sha512_128_begin;
103 | cx->f_hash = (hf_hash *)sha512_128_hash;
104 | cx->f_end = (hf_begin *)sha512_128_end;
105 | cx->input_len = SHA512_128_BLOCK_SIZE;
106 | cx->output_len = SHA512_128_DIGEST_SIZE;
107 | break;
108 | #endif
109 | }
110 | return (int)cx->output_len;
111 | }
112 |
113 | /* input the HMAC key (can be called multiple times) */
114 | int hmac_sha_key(const unsigned char key[], unsigned long key_len, hmac_ctx cx[1])
115 | {
116 | if(cx->klen == HMAC_IN_DATA) /* error if further key input */
117 | return EXIT_FAILURE; /* is attempted in data mode */
118 |
119 | if(cx->klen + key_len > cx->input_len) /* if the key has to be hashed */
120 | {
121 | if(cx->klen <= cx->input_len) /* if the hash has not yet been */
122 | { /* started, initialise it and */
123 | cx->f_begin(cx->sha_ctx); /* hash stored key characters */
124 | cx->f_hash(cx->key, cx->klen, cx->sha_ctx);
125 | }
126 |
127 | cx->f_hash(key, key_len, cx->sha_ctx); /* hash long key data into hash */
128 | }
129 | else /* otherwise store key data */
130 | memcpy(cx->key + cx->klen, key, key_len);
131 |
132 | cx->klen += key_len; /* update the key length count */
133 | return EXIT_SUCCESS;
134 | }
135 |
136 | /* input the HMAC data (can be called multiple times) - */
137 | /* note that this call terminates the key input phase */
138 | void hmac_sha_data(const unsigned char data[], unsigned long data_len, hmac_ctx cx[1])
139 | { unsigned int i;
140 |
141 | if(cx->klen != HMAC_IN_DATA) /* if not yet in data phase */
142 | {
143 | if(cx->klen > cx->input_len) /* if key is being hashed */
144 | { /* complete the hash and */
145 | cx->f_end(cx->key, cx->sha_ctx); /* store the result as the */
146 | cx->klen = cx->output_len; /* key and set new length */
147 | }
148 |
149 | /* pad the key if necessary */
150 | memset(cx->key + cx->klen, 0, cx->input_len - cx->klen);
151 |
152 | /* xor ipad into key value */
153 | for(i = 0; i < (cx->input_len >> 2); ++i)
154 | ((uint32_t*)cx->key)[i] ^= 0x36363636;
155 |
156 | /* and start hash operation */
157 | cx->f_begin(cx->sha_ctx);
158 | cx->f_hash(cx->key, cx->input_len, cx->sha_ctx);
159 |
160 | /* mark as now in data mode */
161 | cx->klen = HMAC_IN_DATA;
162 | }
163 |
164 | /* hash the data (if any) */
165 | if(data_len)
166 | cx->f_hash(data, data_len, cx->sha_ctx);
167 | }
168 |
169 | /* compute and output the MAC value */
170 | void hmac_sha_end(unsigned char mac[], unsigned long mac_len, hmac_ctx cx[1])
171 | { unsigned char dig[HMAC_MAX_OUTPUT_SIZE];
172 | unsigned int i;
173 |
174 | /* if no data has been entered perform a null data phase */
175 | if(cx->klen != HMAC_IN_DATA)
176 | hmac_sha_data((const unsigned char*)0, 0, cx);
177 |
178 | cx->f_end(dig, cx->sha_ctx); /* complete the inner hash */
179 |
180 | /* set outer key value using opad and removing ipad */
181 | for(i = 0; i < (cx->input_len >> 2); ++i)
182 | ((uint32_t*)cx->key)[i] ^= 0x36363636 ^ 0x5c5c5c5c;
183 |
184 | /* perform the outer hash operation */
185 | cx->f_begin(cx->sha_ctx);
186 | cx->f_hash(cx->key, cx->input_len, cx->sha_ctx);
187 | cx->f_hash(dig, cx->output_len, cx->sha_ctx);
188 | cx->f_end(dig, cx->sha_ctx);
189 |
190 | /* output the hash value */
191 | for(i = 0; i < mac_len; ++i)
192 | mac[i] = dig[i];
193 | }
194 |
195 | /* 'do it all in one go' subroutine */
196 | void hmac_sha(enum hmac_hash hash, const unsigned char key[], unsigned long key_len,
197 | const unsigned char data[], unsigned long data_len,
198 | unsigned char mac[], unsigned long mac_len)
199 | { hmac_ctx cx[1];
200 |
201 | hmac_sha_begin(hash, cx);
202 | hmac_sha_key(key, key_len, cx);
203 | hmac_sha_data(data, data_len, cx);
204 | hmac_sha_end(mac, mac_len, cx);
205 | }
206 |
207 | #if defined(__cplusplus)
208 | }
209 | #endif
210 |
--------------------------------------------------------------------------------
/Replica/SSZipArchive/minizip/aes/hmac.h:
--------------------------------------------------------------------------------
1 | /*
2 | ---------------------------------------------------------------------------
3 | Copyright (c) 1998-2010, Brian Gladman, Worcester, UK. All rights reserved.
4 |
5 | The redistribution and use of this software (with or without changes)
6 | is allowed without the payment of fees or royalties provided that:
7 |
8 | source code distributions include the above copyright notice, this
9 | list of conditions and the following disclaimer;
10 |
11 | binary distributions include the above copyright notice, this list
12 | of conditions and the following disclaimer in their documentation.
13 |
14 | This software is provided 'as is' with no explicit or implied warranties
15 | in respect of its operation, including, but not limited to, correctness
16 | and fitness for purpose.
17 | ---------------------------------------------------------------------------
18 | Issue Date: 20/12/2007
19 |
20 | This is an implementation of HMAC, the FIPS standard keyed hash function
21 | */
22 |
23 | #ifndef _HMAC2_H
24 | #define _HMAC2_H
25 |
26 | #include
27 | #include
28 |
29 | #if defined(__cplusplus)
30 | extern "C"
31 | {
32 | #endif
33 |
34 | #include "sha1.h"
35 |
36 | #if defined(SHA_224) || defined(SHA_256) || defined(SHA_384) || defined(SHA_512)
37 | #define HMAC_MAX_OUTPUT_SIZE SHA2_MAX_DIGEST_SIZE
38 | #define HMAC_MAX_BLOCK_SIZE SHA2_MAX_BLOCK_SIZE
39 | #else
40 | #define HMAC_MAX_OUTPUT_SIZE SHA1_DIGEST_SIZE
41 | #define HMAC_MAX_BLOCK_SIZE SHA1_BLOCK_SIZE
42 | #endif
43 |
44 | #define HMAC_IN_DATA 0xffffffff
45 |
46 | enum hmac_hash
47 | {
48 | #ifdef SHA_1
49 | HMAC_SHA1,
50 | #endif
51 | #ifdef SHA_224
52 | HMAC_SHA224,
53 | #endif
54 | #ifdef SHA_256
55 | HMAC_SHA256,
56 | #endif
57 | #ifdef SHA_384
58 | HMAC_SHA384,
59 | #endif
60 | #ifdef SHA_512
61 | HMAC_SHA512,
62 | HMAC_SHA512_256,
63 | HMAC_SHA512_224,
64 | HMAC_SHA512_192,
65 | HMAC_SHA512_128
66 | #endif
67 | };
68 |
69 | typedef VOID_RETURN hf_begin(void*);
70 | typedef VOID_RETURN hf_hash(const void*, unsigned long len, void*);
71 | typedef VOID_RETURN hf_end(void*, void*);
72 |
73 | typedef struct
74 | { hf_begin *f_begin;
75 | hf_hash *f_hash;
76 | hf_end *f_end;
77 | unsigned char key[HMAC_MAX_BLOCK_SIZE];
78 | union
79 | {
80 | #ifdef SHA_1
81 | sha1_ctx u_sha1;
82 | #endif
83 | #ifdef SHA_224
84 | sha224_ctx u_sha224;
85 | #endif
86 | #ifdef SHA_256
87 | sha256_ctx u_sha256;
88 | #endif
89 | #ifdef SHA_384
90 | sha384_ctx u_sha384;
91 | #endif
92 | #ifdef SHA_512
93 | sha512_ctx u_sha512;
94 | #endif
95 | } sha_ctx[1];
96 | unsigned long input_len;
97 | unsigned long output_len;
98 | unsigned long klen;
99 | } hmac_ctx;
100 |
101 | /* returns the length of hash digest for the hash used */
102 | /* mac_len must not be greater than this */
103 | int hmac_sha_begin(enum hmac_hash hash, hmac_ctx cx[1]);
104 |
105 | int hmac_sha_key(const unsigned char key[], unsigned long key_len, hmac_ctx cx[1]);
106 |
107 | void hmac_sha_data(const unsigned char data[], unsigned long data_len, hmac_ctx cx[1]);
108 |
109 | void hmac_sha_end(unsigned char mac[], unsigned long mac_len, hmac_ctx cx[1]);
110 |
111 | void hmac_sha(enum hmac_hash hash, const unsigned char key[], unsigned long key_len,
112 | const unsigned char data[], unsigned long data_len,
113 | unsigned char mac[], unsigned long mac_len);
114 |
115 | #if defined(__cplusplus)
116 | }
117 | #endif
118 |
119 | #endif
120 |
--------------------------------------------------------------------------------
/Replica/SSZipArchive/minizip/aes/prng.c:
--------------------------------------------------------------------------------
1 | /*
2 | ---------------------------------------------------------------------------
3 | Copyright (c) 2002, Dr Brian Gladman < >, Worcester, UK.
4 | All rights reserved.
5 |
6 | LICENSE TERMS
7 |
8 | The free distribution and use of this software in both source and binary
9 | form is allowed (with or without changes) provided that:
10 |
11 | 1. distributions of this source code include the above copyright
12 | notice, this list of conditions and the following disclaimer;
13 |
14 | 2. distributions in binary form include the above copyright
15 | notice, this list of conditions and the following disclaimer
16 | in the documentation and/or other associated materials;
17 |
18 | 3. the copyright holder's name is not used to endorse products
19 | built using this software without specific written permission.
20 |
21 | ALTERNATIVELY, provided that this notice is retained in full, this product
22 | may be distributed under the terms of the GNU General Public License (GPL),
23 | in which case the provisions of the GPL apply INSTEAD OF those given above.
24 |
25 | DISCLAIMER
26 |
27 | This software is provided 'as is' with no explicit or implied warranties
28 | in respect of its properties, including, but not limited to, correctness
29 | and/or fitness for purpose.
30 | ---------------------------------------------------------------------------
31 | Issue Date: 24/01/2003
32 |
33 | This file implements a random data pool based on the use of an external
34 | entropy function. It is based on the ideas advocated by Peter Gutmann in
35 | his work on pseudo random sequence generators. It is not a 'paranoid'
36 | random sequence generator and no attempt is made to protect the pool
37 | from prying eyes either by memory locking or by techniques to obscure
38 | its location in memory.
39 | */
40 |
41 | #include
42 | #include "prng.h"
43 |
44 | #if defined(__cplusplus)
45 | extern "C"
46 | {
47 | #endif
48 |
49 | /* mix a random data pool using the SHA1 compression function (as */
50 | /* suggested by Peter Gutmann in his paper on random pools) */
51 |
52 | static void prng_mix(unsigned char buf[])
53 | { unsigned int i, len;
54 | sha1_ctx ctx[1];
55 |
56 | /*lint -e{663} unusual array to pointer conversion */
57 | for(i = 0; i < PRNG_POOL_SIZE; i += SHA1_DIGEST_SIZE)
58 | {
59 | /* copy digest size pool block into SHA1 hash block */
60 | memcpy(ctx->hash, buf + (i ? i : PRNG_POOL_SIZE)
61 | - SHA1_DIGEST_SIZE, SHA1_DIGEST_SIZE);
62 |
63 | /* copy data from pool into the SHA1 data buffer */
64 | len = PRNG_POOL_SIZE - i;
65 | memcpy(ctx->wbuf, buf + i, (len > SHA1_BLOCK_SIZE ? SHA1_BLOCK_SIZE : len));
66 |
67 | if(len < SHA1_BLOCK_SIZE)
68 | memcpy(((char*)ctx->wbuf) + len, buf, SHA1_BLOCK_SIZE - len);
69 |
70 | /* compress using the SHA1 compression function */
71 | sha1_compile(ctx);
72 |
73 | /* put digest size block back into the random pool */
74 | memcpy(buf + i, ctx->hash, SHA1_DIGEST_SIZE);
75 | }
76 | }
77 |
78 | /* refresh the output buffer and update the random pool by adding */
79 | /* entropy and remixing */
80 |
81 | static void update_pool(prng_ctx ctx[1])
82 | { unsigned int i = 0;
83 |
84 | /* transfer random pool data to the output buffer */
85 | memcpy(ctx->obuf, ctx->rbuf, PRNG_POOL_SIZE);
86 |
87 | /* enter entropy data into the pool */
88 | while(i < PRNG_POOL_SIZE)
89 | i += ctx->entropy(ctx->rbuf + i, PRNG_POOL_SIZE - i);
90 |
91 | /* invert and xor the original pool data into the pool */
92 | for(i = 0; i < PRNG_POOL_SIZE; ++i)
93 | ctx->rbuf[i] ^= ~ctx->obuf[i];
94 |
95 | /* mix the pool and the output buffer */
96 | prng_mix(ctx->rbuf);
97 | prng_mix(ctx->obuf);
98 | }
99 |
100 | void prng_init(prng_entropy_fn fun, prng_ctx ctx[1])
101 | { int i;
102 |
103 | /* clear the buffers and the counter in the context */
104 | memset(ctx, 0, sizeof(prng_ctx));
105 |
106 | /* set the pointer to the entropy collection function */
107 | ctx->entropy = fun;
108 |
109 | /* initialise the random data pool */
110 | update_pool(ctx);
111 |
112 | /* mix the pool a minimum number of times */
113 | for(i = 0; i < PRNG_MIN_MIX; ++i)
114 | prng_mix(ctx->rbuf);
115 |
116 | /* update the pool to prime the pool output buffer */
117 | update_pool(ctx);
118 | }
119 |
120 | /* provide random bytes from the random data pool */
121 |
122 | void prng_rand(unsigned char data[], unsigned int data_len, prng_ctx ctx[1])
123 | { unsigned char *rp = data;
124 | unsigned int len, pos = ctx->pos;
125 |
126 | while(data_len)
127 | {
128 | /* transfer 'data_len' bytes (or the number of bytes remaining */
129 | /* the pool output buffer if less) into the output */
130 | len = (data_len < PRNG_POOL_SIZE - pos ? data_len : PRNG_POOL_SIZE - pos);
131 | memcpy(rp, ctx->obuf + pos, len);
132 | rp += len; /* update ouput buffer position pointer */
133 | pos += len; /* update pool output buffer pointer */
134 | data_len -= len; /* update the remaining data count */
135 |
136 | /* refresh the random pool if necessary */
137 | if(pos == PRNG_POOL_SIZE)
138 | {
139 | update_pool(ctx); pos = 0;
140 | }
141 | }
142 |
143 | ctx->pos = pos;
144 | }
145 |
146 | void prng_end(prng_ctx ctx[1])
147 | {
148 | /* ensure the data in the context is destroyed */
149 | memset(ctx, 0, sizeof(prng_ctx));
150 | }
151 |
152 | #if defined(__cplusplus)
153 | }
154 | #endif
155 |
156 |
--------------------------------------------------------------------------------
/Replica/SSZipArchive/minizip/aes/prng.h:
--------------------------------------------------------------------------------
1 | /*
2 | ---------------------------------------------------------------------------
3 | Copyright (c) 2002, Dr Brian Gladman < >, Worcester, UK.
4 | All rights reserved.
5 |
6 | LICENSE TERMS
7 |
8 | The free distribution and use of this software in both source and binary
9 | form is allowed (with or without changes) provided that:
10 |
11 | 1. distributions of this source code include the above copyright
12 | notice, this list of conditions and the following disclaimer;
13 |
14 | 2. distributions in binary form include the above copyright
15 | notice, this list of conditions and the following disclaimer
16 | in the documentation and/or other associated materials;
17 |
18 | 3. the copyright holder's name is not used to endorse products
19 | built using this software without specific written permission.
20 |
21 | ALTERNATIVELY, provided that this notice is retained in full, this product
22 | may be distributed under the terms of the GNU General Public License (GPL),
23 | in which case the provisions of the GPL apply INSTEAD OF those given above.
24 |
25 | DISCLAIMER
26 |
27 | This software is provided 'as is' with no explicit or implied warranties
28 | in respect of its properties, including, but not limited to, correctness
29 | and/or fitness for purpose.
30 | ---------------------------------------------------------------------------
31 | Issue Date: 24/01/2003
32 |
33 | This is the header file for an implementation of a random data pool based on
34 | the use of an external entropy function (inspired by Peter Gutmann's work).
35 | */
36 |
37 | #ifndef _PRNG_H
38 | #define _PRNG_H
39 |
40 | #include "sha1.h"
41 |
42 | #define PRNG_POOL_LEN 256 /* minimum random pool size */
43 | #define PRNG_MIN_MIX 20 /* min initial pool mixing iterations */
44 |
45 | /* ensure that pool length is a multiple of the SHA1 digest size */
46 |
47 | #define PRNG_POOL_SIZE (SHA1_DIGEST_SIZE * (1 + (PRNG_POOL_LEN - 1) / SHA1_DIGEST_SIZE))
48 |
49 | #if defined(__cplusplus)
50 | extern "C"
51 | {
52 | #endif
53 |
54 | /* A function for providing entropy is a parameter in the prng_init() */
55 | /* call. This function has the following form and returns a maximum */
56 | /* of 'len' bytes of pseudo random data in the buffer 'buf'. It can */
57 | /* return less than 'len' bytes but will be repeatedly called for more */
58 | /* data in this case. */
59 |
60 | typedef int (*prng_entropy_fn)(unsigned char buf[], unsigned int len);
61 |
62 | typedef struct
63 | { unsigned char rbuf[PRNG_POOL_SIZE]; /* the random pool */
64 | unsigned char obuf[PRNG_POOL_SIZE]; /* pool output buffer */
65 | unsigned int pos; /* output buffer position */
66 | prng_entropy_fn entropy; /* entropy function pointer */
67 | } prng_ctx;
68 |
69 | /* initialise the random stream generator */
70 | void prng_init(prng_entropy_fn fun, prng_ctx ctx[1]);
71 |
72 | /* obtain random bytes from the generator */
73 | void prng_rand(unsigned char data[], unsigned int data_len, prng_ctx ctx[1]);
74 |
75 | /* close the random stream generator */
76 | void prng_end(prng_ctx ctx[1]);
77 |
78 | #if defined(__cplusplus)
79 | }
80 | #endif
81 |
82 | #endif
83 |
--------------------------------------------------------------------------------
/Replica/SSZipArchive/minizip/aes/pwd2key.c:
--------------------------------------------------------------------------------
1 | /*
2 | ---------------------------------------------------------------------------
3 | Copyright (c) 1998-2010, Brian Gladman, Worcester, UK. All rights reserved.
4 |
5 | The redistribution and use of this software (with or without changes)
6 | is allowed without the payment of fees or royalties provided that:
7 |
8 | source code distributions include the above copyright notice, this
9 | list of conditions and the following disclaimer;
10 |
11 | binary distributions include the above copyright notice, this list
12 | of conditions and the following disclaimer in their documentation.
13 |
14 | This software is provided 'as is' with no explicit or implied warranties
15 | in respect of its operation, including, but not limited to, correctness
16 | and fitness for purpose.
17 | ---------------------------------------------------------------------------
18 | Issue Date: 20/12/2007
19 |
20 | This is an implementation of RFC2898, which specifies key derivation from
21 | a password and a salt value.
22 | */
23 |
24 | #include
25 | #include "hmac.h"
26 |
27 | #if defined(__cplusplus)
28 | extern "C"
29 | {
30 | #endif
31 |
32 | void derive_key(const unsigned char pwd[], /* the PASSWORD */
33 | unsigned int pwd_len, /* and its length */
34 | const unsigned char salt[], /* the SALT and its */
35 | unsigned int salt_len, /* length */
36 | unsigned int iter, /* the number of iterations */
37 | unsigned char key[], /* space for the output key */
38 | unsigned int key_len)/* and its required length */
39 | {
40 | unsigned int i, j, k, n_blk, h_size;
41 | unsigned char uu[HMAC_MAX_OUTPUT_SIZE], ux[HMAC_MAX_OUTPUT_SIZE];
42 | hmac_ctx c1[1], c2[1], c3[1];
43 |
44 | /* set HMAC context (c1) for password */
45 | h_size = hmac_sha_begin(HMAC_SHA1, c1);
46 | hmac_sha_key(pwd, pwd_len, c1);
47 |
48 | /* set HMAC context (c2) for password and salt */
49 | memcpy(c2, c1, sizeof(hmac_ctx));
50 | hmac_sha_data(salt, salt_len, c2);
51 |
52 | /* find the number of SHA blocks in the key */
53 | n_blk = 1 + (key_len - 1) / h_size;
54 |
55 | for(i = 0; i < n_blk; ++i) /* for each block in key */
56 | {
57 | /* ux[] holds the running xor value */
58 | memset(ux, 0, h_size);
59 |
60 | /* set HMAC context (c3) for password and salt */
61 | memcpy(c3, c2, sizeof(hmac_ctx));
62 |
63 | /* enter additional data for 1st block into uu */
64 | uu[0] = (unsigned char)((i + 1) >> 24);
65 | uu[1] = (unsigned char)((i + 1) >> 16);
66 | uu[2] = (unsigned char)((i + 1) >> 8);
67 | uu[3] = (unsigned char)(i + 1);
68 |
69 | /* this is the key mixing iteration */
70 | for(j = 0, k = 4; j < iter; ++j)
71 | {
72 | /* add previous round data to HMAC */
73 | hmac_sha_data(uu, k, c3);
74 |
75 | /* obtain HMAC for uu[] */
76 | hmac_sha_end(uu, h_size, c3);
77 |
78 | /* xor into the running xor block */
79 | for(k = 0; k < h_size; ++k)
80 | ux[k] ^= uu[k];
81 |
82 | /* set HMAC context (c3) for password */
83 | memcpy(c3, c1, sizeof(hmac_ctx));
84 | }
85 |
86 | /* compile key blocks into the key output */
87 | j = 0; k = i * h_size;
88 | while(j < h_size && k < key_len)
89 | key[k++] = ux[j++];
90 | }
91 | }
92 |
93 | #ifdef TEST
94 |
95 | #include
96 |
97 | struct
98 | { unsigned int pwd_len;
99 | unsigned int salt_len;
100 | unsigned int it_count;
101 | unsigned char *pwd;
102 | unsigned char salt[32];
103 | unsigned char key[32];
104 | } tests[] =
105 | {
106 | { 8, 4, 5, (unsigned char*)"password",
107 | {
108 | 0x12, 0x34, 0x56, 0x78
109 | },
110 | {
111 | 0x5c, 0x75, 0xce, 0xf0, 0x1a, 0x96, 0x0d, 0xf7,
112 | 0x4c, 0xb6, 0xb4, 0x9b, 0x9e, 0x38, 0xe6, 0xb5
113 | }
114 | },
115 | { 8, 8, 5, (unsigned char*)"password",
116 | {
117 | 0x12, 0x34, 0x56, 0x78, 0x78, 0x56, 0x34, 0x12
118 | },
119 | {
120 | 0xd1, 0xda, 0xa7, 0x86, 0x15, 0xf2, 0x87, 0xe6,
121 | 0xa1, 0xc8, 0xb1, 0x20, 0xd7, 0x06, 0x2a, 0x49
122 | }
123 | },
124 | { 8, 21, 1, (unsigned char*)"password",
125 | {
126 | "ATHENA.MIT.EDUraeburn"
127 | },
128 | {
129 | 0xcd, 0xed, 0xb5, 0x28, 0x1b, 0xb2, 0xf8, 0x01,
130 | 0x56, 0x5a, 0x11, 0x22, 0xb2, 0x56, 0x35, 0x15
131 | }
132 | },
133 | { 8, 21, 2, (unsigned char*)"password",
134 | {
135 | "ATHENA.MIT.EDUraeburn"
136 | },
137 | {
138 | 0x01, 0xdb, 0xee, 0x7f, 0x4a, 0x9e, 0x24, 0x3e,
139 | 0x98, 0x8b, 0x62, 0xc7, 0x3c, 0xda, 0x93, 0x5d
140 | }
141 | },
142 | { 8, 21, 1200, (unsigned char*)"password",
143 | {
144 | "ATHENA.MIT.EDUraeburn"
145 | },
146 | {
147 | 0x5c, 0x08, 0xeb, 0x61, 0xfd, 0xf7, 0x1e, 0x4e,
148 | 0x4e, 0xc3, 0xcf, 0x6b, 0xa1, 0xf5, 0x51, 0x2b
149 | }
150 | }
151 | };
152 |
153 | int main()
154 | { unsigned int i, j, key_len = 256;
155 | unsigned char key[256];
156 |
157 | printf("\nTest of RFC2898 Password Based Key Derivation");
158 | for(i = 0; i < 5; ++i)
159 | {
160 | derive_key(tests[i].pwd, tests[i].pwd_len, tests[i].salt,
161 | tests[i].salt_len, tests[i].it_count, key, key_len);
162 |
163 | printf("\ntest %i: ", i + 1);
164 | printf("key %s", memcmp(tests[i].key, key, 16) ? "is bad" : "is good");
165 | for(j = 0; j < key_len && j < 64; j += 4)
166 | {
167 | if(j % 16 == 0)
168 | printf("\n");
169 | printf("0x%02x%02x%02x%02x ", key[j], key[j + 1], key[j + 2], key[j + 3]);
170 | }
171 | printf(j < key_len ? " ... \n" : "\n");
172 | }
173 | printf("\n");
174 | return 0;
175 | }
176 |
177 | #if defined(__cplusplus)
178 | }
179 | #endif
180 |
181 | #endif
182 |
--------------------------------------------------------------------------------
/Replica/SSZipArchive/minizip/aes/pwd2key.h:
--------------------------------------------------------------------------------
1 | /*
2 | ---------------------------------------------------------------------------
3 | Copyright (c) 1998-2010, Brian Gladman, Worcester, UK. All rights reserved.
4 |
5 | The redistribution and use of this software (with or without changes)
6 | is allowed without the payment of fees or royalties provided that:
7 |
8 | source code distributions include the above copyright notice, this
9 | list of conditions and the following disclaimer;
10 |
11 | binary distributions include the above copyright notice, this list
12 | of conditions and the following disclaimer in their documentation.
13 |
14 | This software is provided 'as is' with no explicit or implied warranties
15 | in respect of its operation, including, but not limited to, correctness
16 | and fitness for purpose.
17 | ---------------------------------------------------------------------------
18 | Issue Date: 20/12/2007
19 |
20 | This is an implementation of RFC2898, which specifies key derivation from
21 | a password and a salt value.
22 | */
23 |
24 | #ifndef PWD2KEY_H
25 | #define PWD2KEY_H
26 |
27 | #if defined(__cplusplus)
28 | extern "C"
29 | {
30 | #endif
31 |
32 | void derive_key(
33 | const unsigned char pwd[], /* the PASSWORD, and */
34 | unsigned int pwd_len, /* its length */
35 | const unsigned char salt[], /* the SALT and its */
36 | unsigned int salt_len, /* length */
37 | unsigned int iter, /* the number of iterations */
38 | unsigned char key[], /* space for the output key */
39 | unsigned int key_len); /* and its required length */
40 |
41 | #if defined(__cplusplus)
42 | }
43 | #endif
44 |
45 | #endif
46 |
--------------------------------------------------------------------------------
/Replica/SSZipArchive/minizip/aes/sha1.h:
--------------------------------------------------------------------------------
1 | /*
2 | ---------------------------------------------------------------------------
3 | Copyright (c) 1998-2010, Brian Gladman, Worcester, UK. All rights reserved.
4 |
5 | The redistribution and use of this software (with or without changes)
6 | is allowed without the payment of fees or royalties provided that:
7 |
8 | source code distributions include the above copyright notice, this
9 | list of conditions and the following disclaimer;
10 |
11 | binary distributions include the above copyright notice, this list
12 | of conditions and the following disclaimer in their documentation.
13 |
14 | This software is provided 'as is' with no explicit or implied warranties
15 | in respect of its operation, including, but not limited to, correctness
16 | and fitness for purpose.
17 | ---------------------------------------------------------------------------
18 | Issue Date: 20/12/2007
19 | */
20 |
21 | #ifndef _SHA1_H
22 | #define _SHA1_H
23 |
24 | #define SHA_1
25 |
26 | /* define for bit or byte oriented SHA */
27 | #if 1
28 | # define SHA1_BITS 0 /* byte oriented */
29 | #else
30 | # define SHA1_BITS 1 /* bit oriented */
31 | #endif
32 |
33 | #include
34 | #include "brg_types.h"
35 |
36 | #define SHA1_BLOCK_SIZE 64
37 | #define SHA1_DIGEST_SIZE 20
38 |
39 | #if defined(__cplusplus)
40 | extern "C"
41 | {
42 | #endif
43 |
44 | /* type to hold the SHA256 context */
45 |
46 | typedef struct
47 | { uint32_t count[2];
48 | uint32_t hash[SHA1_DIGEST_SIZE >> 2];
49 | uint32_t wbuf[SHA1_BLOCK_SIZE >> 2];
50 | } sha1_ctx;
51 |
52 | /* Note that these prototypes are the same for both bit and */
53 | /* byte oriented implementations. However the length fields */
54 | /* are in bytes or bits as appropriate for the version used */
55 | /* and bit sequences are input as arrays of bytes in which */
56 | /* bit sequences run from the most to the least significant */
57 | /* end of each byte. The value 'len' in sha1_hash for the */
58 | /* byte oriented version of SHA1 is limited to 2^29 bytes, */
59 | /* but multiple calls will handle longer data blocks. */
60 |
61 | VOID_RETURN sha1_compile(sha1_ctx ctx[1]);
62 |
63 | VOID_RETURN sha1_begin(sha1_ctx ctx[1]);
64 | VOID_RETURN sha1_hash(const unsigned char data[], unsigned long len, sha1_ctx ctx[1]);
65 | VOID_RETURN sha1_end(unsigned char hval[], sha1_ctx ctx[1]);
66 | VOID_RETURN sha1(unsigned char hval[], const unsigned char data[], unsigned long len);
67 |
68 | #if defined(__cplusplus)
69 | }
70 | #endif
71 |
72 | #endif
73 |
--------------------------------------------------------------------------------
/Replica/SSZipArchive/minizip/crypt.c:
--------------------------------------------------------------------------------
1 | /* crypt.c -- base code for traditional PKWARE encryption
2 | Version 1.2.0, September 16th, 2017
3 |
4 | Copyright (C) 2012-2017 Nathan Moinvaziri
5 | https://github.com/nmoinvaz/minizip
6 | Copyright (C) 1998-2005 Gilles Vollant
7 | Modifications for Info-ZIP crypting
8 | http://www.winimage.com/zLibDll/minizip.html
9 | Copyright (C) 2003 Terry Thorsen
10 |
11 | This code is a modified version of crypting code in Info-ZIP distribution
12 |
13 | Copyright (C) 1990-2000 Info-ZIP. All rights reserved.
14 |
15 | This program is distributed under the terms of the same license as zlib.
16 | See the accompanying LICENSE file for the full text of the license.
17 |
18 | This encryption code is a direct transcription of the algorithm from
19 | Roger Schlafly, described by Phil Katz in the file appnote.txt. This
20 | file (appnote.txt) is distributed with the PKZIP program (even in the
21 | version without encryption capabilities).
22 |
23 | If you don't need crypting in your application, just define symbols
24 | NOCRYPT and NOUNCRYPT.
25 | */
26 |
27 | #include
28 | #include
29 | #include
30 | #include
31 |
32 | #ifdef _WIN32
33 | # include
34 | # include
35 | #else
36 | # include
37 | # include
38 | # include
39 | #endif
40 |
41 | #include "zlib.h"
42 |
43 | #include "crypt.h"
44 |
45 | /***************************************************************************/
46 |
47 | #define CRC32(c, b) ((*(pcrc_32_tab+(((uint32_t)(c) ^ (b)) & 0xff))) ^ ((c) >> 8))
48 |
49 | /***************************************************************************/
50 |
51 | uint8_t decrypt_byte(uint32_t *pkeys)
52 | {
53 | unsigned temp; /* POTENTIAL BUG: temp*(temp^1) may overflow in an
54 | * unpredictable manner on 16-bit systems; not a problem
55 | * with any known compiler so far, though */
56 |
57 | temp = ((uint32_t)(*(pkeys+2)) & 0xffff) | 2;
58 | return (uint8_t)(((temp * (temp ^ 1)) >> 8) & 0xff);
59 | }
60 |
61 | uint8_t update_keys(uint32_t *pkeys, const z_crc_t *pcrc_32_tab, int32_t c)
62 | {
63 | (*(pkeys+0)) = (uint32_t)CRC32((*(pkeys+0)), c);
64 | (*(pkeys+1)) += (*(pkeys+0)) & 0xff;
65 | (*(pkeys+1)) = (*(pkeys+1)) * 134775813L + 1;
66 | {
67 | register int32_t keyshift = (int32_t)((*(pkeys + 1)) >> 24);
68 | (*(pkeys+2)) = (uint32_t)CRC32((*(pkeys+2)), keyshift);
69 | }
70 | return c;
71 | }
72 |
73 | void init_keys(const char *passwd, uint32_t *pkeys, const z_crc_t *pcrc_32_tab)
74 | {
75 | *(pkeys+0) = 305419896L;
76 | *(pkeys+1) = 591751049L;
77 | *(pkeys+2) = 878082192L;
78 | while (*passwd != 0)
79 | {
80 | update_keys(pkeys, pcrc_32_tab, *passwd);
81 | passwd += 1;
82 | }
83 | }
84 |
85 | /***************************************************************************/
86 |
87 | #ifndef NOCRYPT
88 | int cryptrand(unsigned char *buf, unsigned int len)
89 | {
90 | #ifdef _WIN32
91 | HCRYPTPROV provider;
92 | unsigned __int64 pentium_tsc[1];
93 | int rlen = 0;
94 | int result = 0;
95 |
96 |
97 | if (CryptAcquireContext(&provider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT))
98 | {
99 | result = CryptGenRandom(provider, len, buf);
100 | CryptReleaseContext(provider, 0);
101 | if (result)
102 | return len;
103 | }
104 |
105 | for (rlen = 0; rlen < (int)len; ++rlen)
106 | {
107 | if (rlen % 8 == 0)
108 | QueryPerformanceCounter((LARGE_INTEGER *)pentium_tsc);
109 | buf[rlen] = ((unsigned char*)pentium_tsc)[rlen % 8];
110 | }
111 |
112 | return rlen;
113 | #else
114 | arc4random_buf(buf, len);
115 | return len;
116 | #endif
117 | }
118 |
119 | int crypthead(const char *passwd, uint8_t *buf, int buf_size, uint32_t *pkeys,
120 | const z_crc_t *pcrc_32_tab, uint8_t verify1, uint8_t verify2)
121 | {
122 | uint8_t n = 0; /* index in random header */
123 | uint8_t header[RAND_HEAD_LEN-2]; /* random header */
124 | uint16_t t = 0; /* temporary */
125 |
126 | if (buf_size < RAND_HEAD_LEN)
127 | return 0;
128 |
129 | init_keys(passwd, pkeys, pcrc_32_tab);
130 |
131 | /* First generate RAND_HEAD_LEN-2 random bytes. */
132 | cryptrand(header, RAND_HEAD_LEN-2);
133 |
134 | /* Encrypt random header (last two bytes is high word of crc) */
135 | init_keys(passwd, pkeys, pcrc_32_tab);
136 |
137 | for (n = 0; n < RAND_HEAD_LEN-2; n++)
138 | buf[n] = (uint8_t)zencode(pkeys, pcrc_32_tab, header[n], t);
139 |
140 | buf[n++] = (uint8_t)zencode(pkeys, pcrc_32_tab, verify1, t);
141 | buf[n++] = (uint8_t)zencode(pkeys, pcrc_32_tab, verify2, t);
142 | return n;
143 | }
144 | #endif
145 |
146 | /***************************************************************************/
147 |
--------------------------------------------------------------------------------
/Replica/SSZipArchive/minizip/crypt.h:
--------------------------------------------------------------------------------
1 | /* crypt.h -- base code for traditional PKWARE encryption
2 | Version 1.2.0, September 16th, 2017
3 |
4 | Copyright (C) 2012-2017 Nathan Moinvaziri
5 | https://github.com/nmoinvaz/minizip
6 | Copyright (C) 1998-2005 Gilles Vollant
7 | Modifications for Info-ZIP crypting
8 | http://www.winimage.com/zLibDll/minizip.html
9 | Copyright (C) 2003 Terry Thorsen
10 |
11 | This code is a modified version of crypting code in Info-ZIP distribution
12 |
13 | Copyright (C) 1990-2000 Info-ZIP. All rights reserved.
14 |
15 | This program is distributed under the terms of the same license as zlib.
16 | See the accompanying LICENSE file for the full text of the license.
17 | */
18 |
19 | #ifndef _MINICRYPT_H
20 | #define _MINICRYPT_H
21 |
22 | #if ZLIB_VERNUM < 0x1270
23 | typedef unsigned long z_crc_t;
24 | #endif
25 |
26 | #ifdef __cplusplus
27 | extern "C" {
28 | #endif
29 |
30 | #define RAND_HEAD_LEN 12
31 |
32 | /***************************************************************************/
33 |
34 | #define zdecode(pkeys,pcrc_32_tab,c) \
35 | (update_keys(pkeys,pcrc_32_tab, c ^= decrypt_byte(pkeys)))
36 |
37 | #define zencode(pkeys,pcrc_32_tab,c,t) \
38 | (t = decrypt_byte(pkeys), update_keys(pkeys,pcrc_32_tab,c), t^(c))
39 |
40 | /***************************************************************************/
41 |
42 | /* Return the next byte in the pseudo-random sequence */
43 | uint8_t decrypt_byte(uint32_t *pkeys);
44 |
45 | /* Update the encryption keys with the next byte of plain text */
46 | uint8_t update_keys(uint32_t *pkeys, const z_crc_t *pcrc_32_tab, int32_t c);
47 |
48 | /* Initialize the encryption keys and the random header according to the given password. */
49 | void init_keys(const char *passwd, uint32_t *pkeys, const z_crc_t *pcrc_32_tab);
50 |
51 | #ifndef NOCRYPT
52 | /* Generate cryptographically secure random numbers */
53 | int cryptrand(unsigned char *buf, unsigned int len);
54 |
55 | /* Create encryption header */
56 | int crypthead(const char *passwd, uint8_t *buf, int buf_size, uint32_t *pkeys,
57 | const z_crc_t *pcrc_32_tab, uint8_t verify1, uint8_t verify2);
58 | #endif
59 |
60 | /***************************************************************************/
61 |
62 | #ifdef __cplusplus
63 | }
64 | #endif
65 |
66 | #endif
67 |
--------------------------------------------------------------------------------
/Replica/SSZipArchive/minizip/ioapi.h:
--------------------------------------------------------------------------------
1 | /* ioapi.h -- IO base function header for compress/uncompress .zip
2 | part of the MiniZip project
3 |
4 | Copyright (C) 2012-2017 Nathan Moinvaziri
5 | https://github.com/nmoinvaz/minizip
6 | Copyright (C) 2009-2010 Mathias Svensson
7 | Modifications for Zip64 support
8 | http://result42.com
9 | Copyright (C) 1998-2010 Gilles Vollant
10 | http://www.winimage.com/zLibDll/minizip.html
11 |
12 | This program is distributed under the terms of the same license as zlib.
13 | See the accompanying LICENSE file for the full text of the license.
14 | */
15 |
16 | #ifndef _ZLIBIOAPI64_H
17 | #define _ZLIBIOAPI64_H
18 |
19 | #include
20 | #include
21 | #include
22 |
23 | #include "zlib.h"
24 |
25 | #ifdef __GNUC__
26 | # define ZIP_UNUSED __attribute__((__unused__))
27 | #else
28 | # define ZIP_UNUSED
29 | #endif
30 |
31 | #if defined(USE_FILE32API)
32 | # define fopen64 fopen
33 | # define ftello64 ftell
34 | # define fseeko64 fseek
35 | #else
36 | # if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__) || defined(__OpenBSD__) || defined(__APPLE__) || defined(__ANDROID__)
37 | # define fopen64 fopen
38 | # define ftello64 ftello
39 | # define fseeko64 fseeko
40 | # endif
41 | # ifdef _MSC_VER
42 | # define fopen64 fopen
43 | # if (_MSC_VER >= 1400) && (!(defined(NO_MSCVER_FILE64_FUNC)))
44 | # define ftello64 _ftelli64
45 | # define fseeko64 _fseeki64
46 | # else /* old MSC */
47 | # define ftello64 ftell
48 | # define fseeko64 fseek
49 | # endif
50 | # endif
51 | #endif
52 |
53 | #ifdef __cplusplus
54 | extern "C" {
55 | #endif
56 |
57 | #define ZLIB_FILEFUNC_SEEK_CUR (1)
58 | #define ZLIB_FILEFUNC_SEEK_END (2)
59 | #define ZLIB_FILEFUNC_SEEK_SET (0)
60 |
61 | #define ZLIB_FILEFUNC_MODE_READ (1)
62 | #define ZLIB_FILEFUNC_MODE_WRITE (2)
63 | #define ZLIB_FILEFUNC_MODE_READWRITEFILTER (3)
64 | #define ZLIB_FILEFUNC_MODE_EXISTING (4)
65 | #define ZLIB_FILEFUNC_MODE_CREATE (8)
66 |
67 | #ifndef ZCALLBACK
68 | # if (defined(WIN32) || defined(_WIN32) || defined (WINDOWS) || \
69 | defined (_WINDOWS)) && defined(CALLBACK) && defined (USEWINDOWS_CALLBACK)
70 | # define ZCALLBACK CALLBACK
71 | # else
72 | # define ZCALLBACK
73 | # endif
74 | #endif
75 |
76 | typedef voidpf (ZCALLBACK *open_file_func) (voidpf opaque, const char *filename, int mode);
77 | typedef voidpf (ZCALLBACK *opendisk_file_func) (voidpf opaque, voidpf stream, uint32_t number_disk, int mode);
78 | typedef uint32_t (ZCALLBACK *read_file_func) (voidpf opaque, voidpf stream, void* buf, uint32_t size);
79 | typedef uint32_t (ZCALLBACK *write_file_func) (voidpf opaque, voidpf stream, const void *buf, uint32_t size);
80 | typedef int (ZCALLBACK *close_file_func) (voidpf opaque, voidpf stream);
81 | typedef int (ZCALLBACK *error_file_func) (voidpf opaque, voidpf stream);
82 |
83 | typedef long (ZCALLBACK *tell_file_func) (voidpf opaque, voidpf stream);
84 | typedef long (ZCALLBACK *seek_file_func) (voidpf opaque, voidpf stream, uint32_t offset, int origin);
85 |
86 | /* here is the "old" 32 bits structure structure */
87 | typedef struct zlib_filefunc_def_s
88 | {
89 | open_file_func zopen_file;
90 | opendisk_file_func zopendisk_file;
91 | read_file_func zread_file;
92 | write_file_func zwrite_file;
93 | tell_file_func ztell_file;
94 | seek_file_func zseek_file;
95 | close_file_func zclose_file;
96 | error_file_func zerror_file;
97 | voidpf opaque;
98 | } zlib_filefunc_def;
99 |
100 | typedef uint64_t (ZCALLBACK *tell64_file_func) (voidpf opaque, voidpf stream);
101 | typedef long (ZCALLBACK *seek64_file_func) (voidpf opaque, voidpf stream, uint64_t offset, int origin);
102 | typedef voidpf (ZCALLBACK *open64_file_func) (voidpf opaque, const void *filename, int mode);
103 | typedef voidpf (ZCALLBACK *opendisk64_file_func)(voidpf opaque, voidpf stream, uint32_t number_disk, int mode);
104 |
105 | typedef struct zlib_filefunc64_def_s
106 | {
107 | open64_file_func zopen64_file;
108 | opendisk64_file_func zopendisk64_file;
109 | read_file_func zread_file;
110 | write_file_func zwrite_file;
111 | tell64_file_func ztell64_file;
112 | seek64_file_func zseek64_file;
113 | close_file_func zclose_file;
114 | error_file_func zerror_file;
115 | voidpf opaque;
116 | } zlib_filefunc64_def;
117 |
118 | void fill_fopen_filefunc(zlib_filefunc_def *pzlib_filefunc_def);
119 | void fill_fopen64_filefunc(zlib_filefunc64_def *pzlib_filefunc_def);
120 |
121 | /* now internal definition, only for zip.c and unzip.h */
122 | typedef struct zlib_filefunc64_32_def_s
123 | {
124 | zlib_filefunc64_def zfile_func64;
125 | open_file_func zopen32_file;
126 | opendisk_file_func zopendisk32_file;
127 | tell_file_func ztell32_file;
128 | seek_file_func zseek32_file;
129 | } zlib_filefunc64_32_def;
130 |
131 | #define ZREAD64(filefunc,filestream,buf,size) ((*((filefunc).zfile_func64.zread_file)) ((filefunc).zfile_func64.opaque,filestream,buf,size))
132 | #define ZWRITE64(filefunc,filestream,buf,size) ((*((filefunc).zfile_func64.zwrite_file)) ((filefunc).zfile_func64.opaque,filestream,buf,size))
133 | /*#define ZTELL64(filefunc,filestream) ((*((filefunc).ztell64_file)) ((filefunc).opaque,filestream))*/
134 | /*#define ZSEEK64(filefunc,filestream,pos,mode) ((*((filefunc).zseek64_file)) ((filefunc).opaque,filestream,pos,mode))*/
135 | #define ZCLOSE64(filefunc,filestream) ((*((filefunc).zfile_func64.zclose_file)) ((filefunc).zfile_func64.opaque,filestream))
136 | #define ZERROR64(filefunc,filestream) ((*((filefunc).zfile_func64.zerror_file)) ((filefunc).zfile_func64.opaque,filestream))
137 |
138 | voidpf call_zopen64(const zlib_filefunc64_32_def *pfilefunc,const void*filename, int mode);
139 | voidpf call_zopendisk64(const zlib_filefunc64_32_def *pfilefunc, voidpf filestream, uint32_t number_disk, int mode);
140 | long call_zseek64(const zlib_filefunc64_32_def *pfilefunc, voidpf filestream, uint64_t offset, int origin);
141 | uint64_t call_ztell64(const zlib_filefunc64_32_def *pfilefunc, voidpf filestream);
142 |
143 | void fill_zlib_filefunc64_32_def_from_filefunc32(zlib_filefunc64_32_def *p_filefunc64_32, const zlib_filefunc_def *p_filefunc32);
144 |
145 | #define ZOPEN64(filefunc,filename,mode) (call_zopen64((&(filefunc)),(filename),(mode)))
146 | #define ZOPENDISK64(filefunc,filestream,diskn,mode) (call_zopendisk64((&(filefunc)),(filestream),(diskn),(mode)))
147 | #define ZTELL64(filefunc,filestream) (call_ztell64((&(filefunc)),(filestream)))
148 | #define ZSEEK64(filefunc,filestream,pos,mode) (call_zseek64((&(filefunc)),(filestream),(pos),(mode)))
149 |
150 | #ifdef __cplusplus
151 | }
152 | #endif
153 |
154 | #endif
155 |
--------------------------------------------------------------------------------
/Replica/SSZipArchive/minizip/ioapi_buf.h:
--------------------------------------------------------------------------------
1 | /* ioapi_buf.h -- IO base function header for compress/uncompress .zip
2 | files using zlib + zip or unzip API
3 |
4 | This version of ioapi is designed to buffer IO.
5 |
6 | Copyright (C) 2012-2017 Nathan Moinvaziri
7 | https://github.com/nmoinvaz/minizip
8 |
9 | This program is distributed under the terms of the same license as zlib.
10 | See the accompanying LICENSE file for the full text of the license.
11 | */
12 |
13 | #ifndef _IOAPI_BUF_H
14 | #define _IOAPI_BUF_H
15 |
16 | #include
17 | #include
18 | #include
19 |
20 | #include "zlib.h"
21 | #include "ioapi.h"
22 |
23 | #ifdef __cplusplus
24 | extern "C" {
25 | #endif
26 |
27 | voidpf ZCALLBACK fopen_buf_func(voidpf opaque, const char* filename, int mode);
28 | voidpf ZCALLBACK fopen64_buf_func(voidpf opaque, const void* filename, int mode);
29 | voidpf ZCALLBACK fopendisk_buf_func(voidpf opaque, voidpf stream_cd, uint32_t number_disk, int mode);
30 | voidpf ZCALLBACK fopendisk64_buf_func(voidpf opaque, voidpf stream_cd, uint32_t number_disk, int mode);
31 | uint32_t ZCALLBACK fread_buf_func(voidpf opaque, voidpf stream, void* buf, uint32_t size);
32 | uint32_t ZCALLBACK fwrite_buf_func(voidpf opaque, voidpf stream, const void* buf, uint32_t size);
33 | long ZCALLBACK ftell_buf_func(voidpf opaque, voidpf stream);
34 | uint64_t ZCALLBACK ftell64_buf_func(voidpf opaque, voidpf stream);
35 | long ZCALLBACK fseek_buf_func(voidpf opaque, voidpf stream, uint32_t offset, int origin);
36 | long ZCALLBACK fseek64_buf_func(voidpf opaque, voidpf stream, uint64_t offset, int origin);
37 | int ZCALLBACK fclose_buf_func(voidpf opaque,voidpf stream);
38 | int ZCALLBACK ferror_buf_func(voidpf opaque,voidpf stream);
39 |
40 | typedef struct ourbuffer_s {
41 | zlib_filefunc_def filefunc;
42 | zlib_filefunc64_def filefunc64;
43 | } ourbuffer_t;
44 |
45 | void fill_buffer_filefunc(zlib_filefunc_def* pzlib_filefunc_def, ourbuffer_t *ourbuf);
46 | void fill_buffer_filefunc64(zlib_filefunc64_def* pzlib_filefunc_def, ourbuffer_t *ourbuf);
47 |
48 | #ifdef __cplusplus
49 | }
50 | #endif
51 |
52 | #endif
53 |
--------------------------------------------------------------------------------
/Replica/SSZipArchive/minizip/ioapi_mem.c:
--------------------------------------------------------------------------------
1 | /* ioapi_mem.c -- IO base function header for compress/uncompress .zip
2 | files using zlib + zip or unzip API
3 |
4 | This version of ioapi is designed to access memory rather than files.
5 | We do use a region of memory to put data in to and take it out of. We do
6 | not have auto-extending buffers and do not inform anyone else that the
7 | data has been written. It is really intended for accessing a zip archive
8 | embedded in an application such that I can write an installer with no
9 | external files. Creation of archives has not been attempted, although
10 | parts of the framework are present.
11 |
12 | Based on Unzip ioapi.c version 0.22, May 19th, 2003
13 |
14 | Copyright (C) 2012-2017 Nathan Moinvaziri
15 | https://github.com/nmoinvaz/minizip
16 | Copyright (C) 2003 Justin Fletcher
17 | Copyright (C) 1998-2003 Gilles Vollant
18 | http://www.winimage.com/zLibDll/minizip.html
19 |
20 | This file is under the same license as the Unzip tool it is distributed
21 | with.
22 | */
23 |
24 |
25 | #include
26 | #include
27 | #include
28 |
29 | #include "zlib.h"
30 | #include "ioapi.h"
31 |
32 | #include "ioapi_mem.h"
33 |
34 | #ifndef IOMEM_BUFFERSIZE
35 | # define IOMEM_BUFFERSIZE (UINT16_MAX)
36 | #endif
37 |
38 | voidpf ZCALLBACK fopen_mem_func(voidpf opaque, ZIP_UNUSED const char *filename, int mode)
39 | {
40 | ourmemory_t *mem = (ourmemory_t *)opaque;
41 | if (mem == NULL)
42 | return NULL; /* Mem structure passed in was null */
43 |
44 | if (mode & ZLIB_FILEFUNC_MODE_CREATE)
45 | {
46 | if (mem->grow)
47 | {
48 | mem->size = IOMEM_BUFFERSIZE;
49 | mem->base = (char *)malloc(mem->size);
50 | }
51 |
52 | mem->limit = 0; /* When writing we start with 0 bytes written */
53 | }
54 | else
55 | mem->limit = mem->size;
56 |
57 | mem->cur_offset = 0;
58 |
59 | return mem;
60 | }
61 |
62 | voidpf ZCALLBACK fopendisk_mem_func(ZIP_UNUSED voidpf opaque, ZIP_UNUSED voidpf stream, ZIP_UNUSED uint32_t number_disk, ZIP_UNUSED int mode)
63 | {
64 | /* Not used */
65 | return NULL;
66 | }
67 |
68 | uint32_t ZCALLBACK fread_mem_func(ZIP_UNUSED voidpf opaque, voidpf stream, void *buf, uint32_t size)
69 | {
70 | ourmemory_t *mem = (ourmemory_t *)stream;
71 |
72 | if (size > mem->size - mem->cur_offset)
73 | size = mem->size - mem->cur_offset;
74 |
75 | memcpy(buf, mem->base + mem->cur_offset, size);
76 | mem->cur_offset += size;
77 |
78 | return size;
79 | }
80 |
81 | uint32_t ZCALLBACK fwrite_mem_func(ZIP_UNUSED voidpf opaque, voidpf stream, const void *buf, uint32_t size)
82 | {
83 | ourmemory_t *mem = (ourmemory_t *)stream;
84 | uint32_t newmemsize = 0;
85 | char *newbase = NULL;
86 |
87 | if (size > mem->size - mem->cur_offset)
88 | {
89 | if (mem->grow)
90 | {
91 | newmemsize = mem->size;
92 | if (size < IOMEM_BUFFERSIZE)
93 | newmemsize += IOMEM_BUFFERSIZE;
94 | else
95 | newmemsize += size;
96 | newbase = (char *)malloc(newmemsize);
97 | memcpy(newbase, mem->base, mem->size);
98 | free(mem->base);
99 | mem->base = newbase;
100 | mem->size = newmemsize;
101 | }
102 | else
103 | size = mem->size - mem->cur_offset;
104 | }
105 | memcpy(mem->base + mem->cur_offset, buf, size);
106 | mem->cur_offset += size;
107 | if (mem->cur_offset > mem->limit)
108 | mem->limit = mem->cur_offset;
109 |
110 | return size;
111 | }
112 |
113 | long ZCALLBACK ftell_mem_func(ZIP_UNUSED voidpf opaque, voidpf stream)
114 | {
115 | ourmemory_t *mem = (ourmemory_t *)stream;
116 | return mem->cur_offset;
117 | }
118 |
119 | long ZCALLBACK fseek_mem_func(ZIP_UNUSED voidpf opaque, voidpf stream, uint32_t offset, int origin)
120 | {
121 | ourmemory_t *mem = (ourmemory_t *)stream;
122 | uint32_t new_pos = 0;
123 | switch (origin)
124 | {
125 | case ZLIB_FILEFUNC_SEEK_CUR:
126 | new_pos = mem->cur_offset + offset;
127 | break;
128 | case ZLIB_FILEFUNC_SEEK_END:
129 | new_pos = mem->limit + offset;
130 | break;
131 | case ZLIB_FILEFUNC_SEEK_SET:
132 | new_pos = offset;
133 | break;
134 | default:
135 | return -1;
136 | }
137 |
138 | if (new_pos > mem->size)
139 | return 1; /* Failed to seek that far */
140 | mem->cur_offset = new_pos;
141 | return 0;
142 | }
143 |
144 | int ZCALLBACK fclose_mem_func(ZIP_UNUSED voidpf opaque, ZIP_UNUSED voidpf stream)
145 | {
146 | /* Even with grow = 1, caller must always free() memory */
147 | return 0;
148 | }
149 |
150 | int ZCALLBACK ferror_mem_func(ZIP_UNUSED voidpf opaque, ZIP_UNUSED voidpf stream)
151 | {
152 | /* We never return errors */
153 | return 0;
154 | }
155 |
156 | void fill_memory_filefunc(zlib_filefunc_def *pzlib_filefunc_def, ourmemory_t *ourmem)
157 | {
158 | pzlib_filefunc_def->zopen_file = fopen_mem_func;
159 | pzlib_filefunc_def->zopendisk_file = fopendisk_mem_func;
160 | pzlib_filefunc_def->zread_file = fread_mem_func;
161 | pzlib_filefunc_def->zwrite_file = fwrite_mem_func;
162 | pzlib_filefunc_def->ztell_file = ftell_mem_func;
163 | pzlib_filefunc_def->zseek_file = fseek_mem_func;
164 | pzlib_filefunc_def->zclose_file = fclose_mem_func;
165 | pzlib_filefunc_def->zerror_file = ferror_mem_func;
166 | pzlib_filefunc_def->opaque = ourmem;
167 | }
168 |
--------------------------------------------------------------------------------
/Replica/SSZipArchive/minizip/ioapi_mem.h:
--------------------------------------------------------------------------------
1 | /* ioapi_mem.h -- IO base function header for compress/uncompress .zip
2 | files using zlib + zip or unzip API
3 |
4 | This version of ioapi is designed to access memory rather than files.
5 | We do use a region of memory to put data in to and take it out of.
6 |
7 | Copyright (C) 2012-2017 Nathan Moinvaziri (https://github.com/nmoinvaz/minizip)
8 | (C) 2003 Justin Fletcher
9 | (C) 1998-2003 Gilles Vollant
10 |
11 | This program is distributed under the terms of the same license as zlib.
12 | See the accompanying LICENSE file for the full text of the license.
13 | */
14 |
15 | #ifndef _IOAPI_MEM_H
16 | #define _IOAPI_MEM_H
17 |
18 | #include
19 | #include
20 | #include
21 |
22 | #include "zlib.h"
23 | #include "ioapi.h"
24 |
25 | #ifdef __cplusplus
26 | extern "C" {
27 | #endif
28 |
29 | voidpf ZCALLBACK fopen_mem_func(voidpf opaque, const char* filename, int mode);
30 | voidpf ZCALLBACK fopendisk_mem_func(voidpf opaque, voidpf stream, uint32_t number_disk, int mode);
31 | uint32_t ZCALLBACK fread_mem_func(voidpf opaque, voidpf stream, void* buf, uint32_t size);
32 | uint32_t ZCALLBACK fwrite_mem_func(voidpf opaque, voidpf stream, const void* buf, uint32_t size);
33 | long ZCALLBACK ftell_mem_func(voidpf opaque, voidpf stream);
34 | long ZCALLBACK fseek_mem_func(voidpf opaque, voidpf stream, uint32_t offset, int origin);
35 | int ZCALLBACK fclose_mem_func(voidpf opaque, voidpf stream);
36 | int ZCALLBACK ferror_mem_func(voidpf opaque, voidpf stream);
37 |
38 | typedef struct ourmemory_s {
39 | char *base; /* Base of the region of memory we're using */
40 | uint32_t size; /* Size of the region of memory we're using */
41 | uint32_t limit; /* Furthest we've written */
42 | uint32_t cur_offset; /* Current offset in the area */
43 | int grow; /* Growable memory buffer */
44 | } ourmemory_t;
45 |
46 | void fill_memory_filefunc(zlib_filefunc_def* pzlib_filefunc_def, ourmemory_t *ourmem);
47 |
48 | #ifdef __cplusplus
49 | }
50 | #endif
51 |
52 | #endif
53 |
--------------------------------------------------------------------------------
/Replica/SSZipArchive/minizip/minishared.c:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include
5 | #include
6 | #include
7 | #include
8 |
9 | #include "zlib.h"
10 | #include "ioapi.h"
11 |
12 | #ifdef _WIN32
13 | # include
14 | # include
15 | #else
16 | # include
17 | # include
18 | # include
19 | # include
20 | #endif
21 |
22 | #include "minishared.h"
23 |
24 | #ifdef _WIN32
25 | # define USEWIN32IOAPI
26 | # include "iowin32.h"
27 | #endif
28 |
29 | uint32_t get_file_date(const char *path, uint32_t *dos_date)
30 | {
31 | int ret = 0;
32 | #ifdef _WIN32
33 | FILETIME ftm_local;
34 | HANDLE find = NULL;
35 | WIN32_FIND_DATAA ff32;
36 |
37 | find = FindFirstFileA(path, &ff32);
38 | if (find != INVALID_HANDLE_VALUE)
39 | {
40 | FileTimeToLocalFileTime(&(ff32.ftLastWriteTime), &ftm_local);
41 | FileTimeToDosDateTime(&ftm_local, ((LPWORD)dos_date) + 1, ((LPWORD)dos_date) + 0);
42 | FindClose(find);
43 | ret = 1;
44 | }
45 | #else
46 | struct stat s;
47 | struct tm *filedate = NULL;
48 | time_t tm_t = 0;
49 |
50 | memset(&s, 0, sizeof(s));
51 |
52 | if (strcmp(path, "-") != 0)
53 | {
54 | size_t len = strlen(path);
55 | char *name = (char *)malloc(len + 1);
56 | strncpy(name, path, len + 1);
57 | name[len] = 0;
58 | if (name[len - 1] == '/')
59 | name[len - 1] = 0;
60 |
61 | /* Not all systems allow stat'ing a file with / appended */
62 | if (stat(name, &s) == 0)
63 | {
64 | tm_t = s.st_mtime;
65 | ret = 1;
66 | }
67 | free(name);
68 | }
69 |
70 | filedate = localtime(&tm_t);
71 | *dos_date = tm_to_dosdate(filedate);
72 | #endif
73 | return ret;
74 | }
75 |
76 | void change_file_date(const char *path, uint32_t dos_date)
77 | {
78 | #ifdef _WIN32
79 | HANDLE handle = NULL;
80 | FILETIME ftm, ftm_local, ftm_create, ftm_access, ftm_modified;
81 |
82 | handle = CreateFileA(path, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
83 | if (handle != INVALID_HANDLE_VALUE)
84 | {
85 | GetFileTime(handle, &ftm_create, &ftm_access, &ftm_modified);
86 | DosDateTimeToFileTime((WORD)(dos_date >> 16), (WORD)dos_date, &ftm_local);
87 | LocalFileTimeToFileTime(&ftm_local, &ftm);
88 | SetFileTime(handle, &ftm, &ftm_access, &ftm);
89 | CloseHandle(handle);
90 | }
91 | #else
92 | struct utimbuf ut;
93 | ut.actime = ut.modtime = dosdate_to_time_t(dos_date);
94 | utime(path, &ut);
95 | #endif
96 | }
97 |
98 | int invalid_date(const struct tm *ptm)
99 | {
100 | #define datevalue_in_range(min, max, value) ((min) <= (value) && (value) <= (max))
101 | return (!datevalue_in_range(0, 207, ptm->tm_year) ||
102 | !datevalue_in_range(0, 11, ptm->tm_mon) ||
103 | !datevalue_in_range(1, 31, ptm->tm_mday) ||
104 | !datevalue_in_range(0, 23, ptm->tm_hour) ||
105 | !datevalue_in_range(0, 59, ptm->tm_min) ||
106 | !datevalue_in_range(0, 59, ptm->tm_sec));
107 | #undef datevalue_in_range
108 | }
109 |
110 | // Conversion without validation
111 | void dosdate_to_raw_tm(uint64_t dos_date, struct tm *ptm)
112 | {
113 | uint64_t date = (uint64_t)(dos_date >> 16);
114 |
115 | ptm->tm_mday = (uint16_t)(date & 0x1f);
116 | ptm->tm_mon = (uint16_t)(((date & 0x1E0) / 0x20) - 1);
117 | ptm->tm_year = (uint16_t)(((date & 0x0FE00) / 0x0200) + 80);
118 | ptm->tm_hour = (uint16_t)((dos_date & 0xF800) / 0x800);
119 | ptm->tm_min = (uint16_t)((dos_date & 0x7E0) / 0x20);
120 | ptm->tm_sec = (uint16_t)(2 * (dos_date & 0x1f));
121 | ptm->tm_isdst = -1;
122 | }
123 |
124 | int dosdate_to_tm(uint64_t dos_date, struct tm *ptm)
125 | {
126 | dosdate_to_raw_tm(dos_date, ptm);
127 |
128 | if (invalid_date(ptm))
129 | {
130 | // Invalid date stored, so don't return it.
131 | memset(ptm, 0, sizeof(struct tm));
132 | return -1;
133 | }
134 | return 0;
135 | }
136 |
137 | time_t dosdate_to_time_t(uint64_t dos_date)
138 | {
139 | struct tm ptm;
140 | dosdate_to_raw_tm(dos_date, &ptm);
141 | return mktime(&ptm);
142 | }
143 |
144 | uint32_t tm_to_dosdate(const struct tm *ptm)
145 | {
146 | struct tm fixed_tm;
147 |
148 | /* Years supported:
149 | * [00, 79] (assumed to be between 2000 and 2079)
150 | * [80, 207] (assumed to be between 1980 and 2107, typical output of old
151 | software that does 'year-1900' to get a double digit year)
152 | * [1980, 2107] (due to the date format limitations, only years between 1980 and 2107 can be stored.)
153 | */
154 |
155 | memcpy(&fixed_tm, ptm, sizeof(struct tm));
156 | if (fixed_tm.tm_year >= 1980) /* range [1980, 2107] */
157 | fixed_tm.tm_year -= 1980;
158 | else if (fixed_tm.tm_year >= 80) /* range [80, 99] */
159 | fixed_tm.tm_year -= 80;
160 | else /* range [00, 79] */
161 | fixed_tm.tm_year += 20;
162 |
163 | if (invalid_date(ptm))
164 | return 0;
165 |
166 | return (uint32_t)(((fixed_tm.tm_mday) + (32 * (fixed_tm.tm_mon + 1)) + (512 * fixed_tm.tm_year)) << 16) |
167 | ((fixed_tm.tm_sec / 2) + (32 * fixed_tm.tm_min) + (2048 * (uint32_t)fixed_tm.tm_hour));
168 | }
169 |
170 | int makedir(const char *newdir)
171 | {
172 | char *buffer = NULL;
173 | char *p = NULL;
174 | int len = (int)strlen(newdir);
175 |
176 | if (len <= 0)
177 | return 0;
178 |
179 | buffer = (char*)malloc(len + 1);
180 | if (buffer == NULL)
181 | {
182 | printf("Error allocating memory\n");
183 | return -1;
184 | }
185 |
186 | strcpy(buffer, newdir);
187 |
188 | if (buffer[len - 1] == '/')
189 | buffer[len - 1] = 0;
190 |
191 | if (MKDIR(buffer) == 0)
192 | {
193 | free(buffer);
194 | return 1;
195 | }
196 |
197 | p = buffer + 1;
198 | while (1)
199 | {
200 | char hold;
201 | while (*p && *p != '\\' && *p != '/')
202 | p++;
203 | hold = *p;
204 | *p = 0;
205 |
206 | if ((MKDIR(buffer) == -1) && (errno == ENOENT))
207 | {
208 | printf("couldn't create directory %s (%d)\n", buffer, errno);
209 | free(buffer);
210 | return 0;
211 | }
212 |
213 | if (hold == 0)
214 | break;
215 |
216 | *p++ = hold;
217 | }
218 |
219 | free(buffer);
220 | return 1;
221 | }
222 |
223 | FILE *get_file_handle(const char *path)
224 | {
225 | FILE *handle = NULL;
226 | #if defined(WIN32)
227 | wchar_t *pathWide = NULL;
228 | int pathLength = 0;
229 |
230 | pathLength = MultiByteToWideChar(CP_UTF8, 0, path, -1, NULL, 0) + 1;
231 | pathWide = (wchar_t*)calloc(pathLength, sizeof(wchar_t));
232 | MultiByteToWideChar(CP_UTF8, 0, path, -1, pathWide, pathLength);
233 | handle = _wfopen((const wchar_t*)pathWide, L"rb");
234 | free(pathWide);
235 | #else
236 | handle = fopen64(path, "rb");
237 | #endif
238 |
239 | return handle;
240 | }
241 |
242 | int check_file_exists(const char *path)
243 | {
244 | FILE *handle = get_file_handle(path);
245 | if (handle == NULL)
246 | return 0;
247 | fclose(handle);
248 | return 1;
249 | }
250 |
251 | int is_large_file(const char *path)
252 | {
253 | FILE* handle = NULL;
254 | uint64_t pos = 0;
255 |
256 | handle = get_file_handle(path);
257 | if (handle == NULL)
258 | return 0;
259 |
260 | fseeko64(handle, 0, SEEK_END);
261 | pos = ftello64(handle);
262 | fclose(handle);
263 |
264 | printf("file : %s is %lld bytes\n", path, pos);
265 |
266 | return (pos >= UINT32_MAX);
267 | }
268 |
269 | void display_zpos64(uint64_t n, int size_char)
270 | {
271 | /* To avoid compatibility problem we do here the conversion */
272 | char number[21] = { 0 };
273 | int offset = 19;
274 | int pos_string = 19;
275 | int size_display_string = 19;
276 |
277 | while (1)
278 | {
279 | number[offset] = (char)((n % 10) + '0');
280 | if (number[offset] != '0')
281 | pos_string = offset;
282 | n /= 10;
283 | if (offset == 0)
284 | break;
285 | offset--;
286 | }
287 |
288 | size_display_string -= pos_string;
289 | while (size_char-- > size_display_string)
290 | printf(" ");
291 | printf("%s", &number[pos_string]);
292 | }
293 |
--------------------------------------------------------------------------------
/Replica/SSZipArchive/minizip/minishared.h:
--------------------------------------------------------------------------------
1 | #ifndef _MINISHARED_H
2 | #define _MINISHARED_H
3 |
4 | #ifdef __cplusplus
5 | extern "C" {
6 | #endif
7 |
8 | #ifdef _WIN32
9 | # define MKDIR(d) _mkdir(d)
10 | # define CHDIR(d) _chdir(d)
11 | #else
12 | # define MKDIR(d) mkdir(d, 0775)
13 | # define CHDIR(d) chdir(d)
14 | #endif
15 |
16 | /***************************************************************************/
17 |
18 | /* Get a file's date and time in dos format */
19 | uint32_t get_file_date(const char *path, uint32_t *dos_date);
20 |
21 | /* Sets a file's date and time in dos format */
22 | void change_file_date(const char *path, uint32_t dos_date);
23 |
24 | /* Convert dos date/time format to struct tm */
25 | int dosdate_to_tm(uint64_t dos_date, struct tm *ptm);
26 |
27 | /* Convert dos date/time format to time_t */
28 | time_t dosdate_to_time_t(uint64_t dos_date);
29 |
30 | /* Convert struct tm to dos date/time format */
31 | uint32_t tm_to_dosdate(const struct tm *ptm);
32 |
33 | /* Create a directory and all subdirectories */
34 | int makedir(const char *newdir);
35 |
36 | /* Check to see if a file exists */
37 | int check_file_exists(const char *path);
38 |
39 | /* Check to see if a file is over 4GB and needs ZIP64 extension */
40 | int is_large_file(const char *path);
41 |
42 | /* Print a 64-bit number for compatibility */
43 | void display_zpos64(uint64_t n, int size_char);
44 |
45 | /***************************************************************************/
46 |
47 | #ifdef __cplusplus
48 | }
49 | #endif
50 |
51 | #endif /* _MINISHARED_H */
--------------------------------------------------------------------------------
/Replica/ShellExecute.h:
--------------------------------------------------------------------------------
1 | //
2 | // ShellExecute.h
3 | // Replica
4 | //
5 | // Created by h4ck on 18/11/3.
6 | // Copyright © 2018年 字节时代(https://byteage.com) All rights reserved.
7 | //
8 |
9 | #import
10 | #import "NSTask+Replica.h"
11 |
12 | @interface ShellExecute : NSObject
13 | + (RETaskOutput *)installXcodeCLI;
14 | + (BOOL)checkXcodeCLI;
15 | + (NSString *)makeTempFolder;
16 | + (BOOL)codesign:(NSString *)file certificate:(NSString *)certificate entitlements:(NSString *)entitlements beforeBlock:(BOOL(^)(NSString *file,NSString *certificate,NSString *entitlements))beforeBlock afterBlock:(BOOL(^)(NSString *file,NSString *certificate,NSString *entitlements,RETaskOutput *taskOutput))afterBlock;
17 | @end
18 |
--------------------------------------------------------------------------------
/Replica/ShellExecute.m:
--------------------------------------------------------------------------------
1 | //
2 | // ShellExecute.m
3 | // Replica
4 | //
5 | // Created by h4ck on 18/11/3.
6 | // Copyright © 2018年 字节时代(https://byteage.com) All rights reserved.
7 | //
8 |
9 | #import "ShellExecute.h"
10 |
11 | @implementation ShellExecute
12 | + (RETaskOutput *)installXcodeCLI{
13 | return [NSTask execute:@"/usr/bin/xcode-select" workingDirectory:nil arguments:@[@"--install"]];
14 | }
15 |
16 | + (BOOL)checkXcodeCLI {
17 | if ([NSTask execute:@"/usr/bin/xcode-select" workingDirectory:nil arguments:@[@"-p"]].status != 0) {
18 | return NO;
19 | }
20 |
21 | return YES;
22 | }
23 |
24 | + (NSString *)makeTempFolder{
25 | RETaskOutput *tempTask = [NSTask execute:@"/usr/bin/mktemp" workingDirectory:nil arguments:@[@"-d",@"-t",[NSBundle mainBundle].bundleIdentifier]];
26 | if(tempTask.status != 0) {
27 | return nil;
28 | }
29 | return [tempTask.output stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
30 | }
31 |
32 | + (BOOL)codesign:(NSString *)file certificate:(NSString *)certificate entitlements:(NSString *)entitlements beforeBlock:(BOOL(^)(NSString *file,NSString *certificate,NSString *entitlements))beforeBlock afterBlock:(BOOL(^)(NSString *file,NSString *certificate,NSString *entitlements,RETaskOutput *taskOutput))afterBlock
33 | {
34 | if (beforeBlock && !beforeBlock(file,certificate,entitlements)) {
35 | return NO;
36 | }
37 | NSMutableArray *arguments = [NSMutableArray arrayWithArray:@[@"-vvv",@"-fs",certificate,@"--no-strict"]];
38 | if([[NSFileManager defaultManager]fileExistsAtPath:entitlements]) {
39 | [arguments addObject:[NSString stringWithFormat:@"--entitlements=%@",entitlements]];
40 | }
41 | [arguments addObject:file];
42 | RETaskOutput *output = [NSTask execute:@"/usr/bin/codesign" workingDirectory:nil arguments:arguments];
43 | if (afterBlock) {
44 | return afterBlock(file,certificate,entitlements,output);
45 | }
46 |
47 | return (output.status == 0);
48 | }
49 | @end
50 |
--------------------------------------------------------------------------------
/Replica/SigningIdentity.h:
--------------------------------------------------------------------------------
1 | //
2 | // SigningIdentity.h
3 | // IPAExporter
4 | //
5 | // Created by Tue Nguyen on 10/11/14.
6 | // Copyright (c) 2014 HOME. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | @class Provisioning;
12 | @interface SigningIdentity : NSObject
13 | @property (nonatomic, strong) NSString *commonName;
14 | @property (nonatomic, strong) NSString *sha1;
15 | @property (nonatomic, strong) NSString *md5;
16 | @property (nonatomic, strong) NSString *serial;
17 | @property (nonatomic, strong, readonly) NSData *certificateData;
18 | - (instancetype)initWithCertificateData:(NSData *)certificateData;
19 | + (NSArray *)keychainsIdenities;
20 | @end
21 |
--------------------------------------------------------------------------------
/Replica/SigningIdentity.m:
--------------------------------------------------------------------------------
1 | //
2 | // SigningIdentity.m
3 | // IPAExporter
4 | //
5 | // Created by Tue Nguyen on 10/11/14.
6 | // Copyright (c) 2014 HOME. All rights reserved.
7 | //
8 |
9 | #import "SigningIdentity.h"
10 | #import "Provisioning.h"
11 | #import
12 | #import
13 |
14 | @interface SigningIdentity()
15 |
16 | @end
17 | @implementation SigningIdentity
18 | - (instancetype)initWithCertificateData:(NSData *)certificateData {
19 | self = [super init];
20 | if (self) {
21 | _certificateData = certificateData;
22 | [self _loadCertData];
23 | }
24 | return self;
25 | }
26 |
27 | - (NSString *)dataToHexString:(NSData *)data {
28 | uint8_t *bytes = (uint8_t *)[data bytes];
29 | NSMutableString *hexStr = [NSMutableString string];
30 | for(int i = 0; i < [data length]; i++) {
31 | uint8_t byte1 = bytes[i] >> 4;
32 | uint8_t byte2 = bytes[i] & 0xf;
33 | [hexStr appendFormat:@"%x",byte1];
34 | [hexStr appendFormat:@"%x",byte2];
35 | }
36 | return [hexStr uppercaseString];
37 | }
38 |
39 | - (void)_loadCertData {
40 | SecCertificateRef certRef = SecCertificateCreateWithData(kCFAllocatorDefault, (__bridge CFDataRef)(self.certificateData));
41 | CFStringRef commonName;
42 | SecCertificateCopyCommonName(certRef, &commonName);
43 | self.commonName = CFBridgingRelease(commonName);
44 |
45 | unsigned char sha1[CC_SHA1_DIGEST_LENGTH];
46 | CC_SHA1((const void *)self.certificateData.bytes, (CC_LONG)self.certificateData.length, sha1);
47 | self.sha1 = [self dataToHexString:[NSData dataWithBytes:sha1 length:CC_SHA1_DIGEST_LENGTH]];
48 |
49 | unsigned char md5[CC_MD5_DIGEST_LENGTH];
50 | CC_MD5((const void *)self.certificateData.bytes, (CC_LONG)self.certificateData.length, md5);
51 | self.md5 = [self dataToHexString:[NSData dataWithBytes:md5 length:CC_MD5_DIGEST_LENGTH]];
52 |
53 | NSData *serial = (__bridge_transfer NSData *)SecCertificateCopySerialNumber(certRef, NULL);
54 | self.serial = [self dataToHexString:serial];
55 | CFRelease(certRef);
56 | }
57 |
58 | + (NSArray *)keychainsIdenities {
59 | NSMutableArray *keychainsIdentities = [NSMutableArray array];
60 |
61 | NSMutableDictionary *query = [NSMutableDictionary dictionaryWithObjectsAndKeys:
62 | (__bridge id)kCFBooleanTrue, (__bridge id)kSecReturnRef,
63 | (__bridge id)kSecMatchLimitAll, (__bridge id)kSecMatchLimit,
64 | kCFNull, kSecMatchValidOnDate,
65 | nil];
66 |
67 | NSArray *secItemClasses = [NSArray arrayWithObjects:
68 | (__bridge id)kSecClassIdentity,
69 | nil];
70 |
71 | for (id secItemClass in secItemClasses) {
72 | [query setObject:secItemClass forKey:(__bridge id)kSecClass];
73 |
74 | CFTypeRef result = NULL;
75 | SecItemCopyMatching((__bridge CFDictionaryRef)query, &result);
76 |
77 | if (!result) {
78 | continue;
79 | }
80 |
81 | NSArray *identityArray = (__bridge NSArray *)(result);
82 | for (id obj in identityArray) {
83 | SecIdentityRef identityRef = (__bridge SecIdentityRef)(obj);
84 | SecCertificateRef certKeychains = NULL;
85 | SecIdentityCopyCertificate(identityRef, &certKeychains);
86 | if (certKeychains != NULL) {
87 | NSData *keychainCertData = (NSData *)CFBridgingRelease(SecCertificateCopyData(certKeychains));
88 | SigningIdentity *si = [[SigningIdentity alloc] initWithCertificateData:keychainCertData];
89 | [keychainsIdentities addObject:si];
90 | CFRelease(certKeychains);
91 | }
92 | }
93 | CFRelease(result);
94 | }
95 | return keychainsIdentities;
96 | }
97 |
98 | - (BOOL)isEqual:(SigningIdentity *)object {
99 | if (self == object) {
100 | return YES;
101 | }
102 | if ([self class] != [object class]) {
103 | return NO;
104 | }
105 | return [self.serial isEqualToString:object.serial];
106 | }
107 |
108 | - (NSUInteger)hash {
109 | return self.serial.hash;
110 | }
111 | @end
112 |
--------------------------------------------------------------------------------
/Replica/Template.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # -----------------------------------------------------------------------
4 | # Replica -- iOS Resign Tool
5 | # Copyright (C) 2017-2018 字节时代 (https://byteage.com)
6 | # -----------------------------------------------------------------------
7 |
8 | # 此函数请勿修改
9 | function panic() # args: exitCode, message...
10 | {
11 | local exitCode=$1
12 | set +e
13 |
14 | shift
15 | [[ "$@" == "" ]] || \
16 | echo "$@" >&2
17 |
18 | exit $exitCode
19 | }
20 |
21 | # -------------------------
22 | # 重签之前调用此函数,可在此函数中拷贝需要的文件到应用包内,注入动态库到指定可执行文件等
23 | # 参数如下:
24 | # $1: 原文件输入路径,如:/Users/h4ck/Downloads/Payload.ipa
25 | # $2: 重签前.app目录路径,如:/var/folders/mq/378q436x625125_n02xbzc340000gn/T/net.ymlab.dev.Replica.AyoxrFq8/out/Payload/WeChat.app,通常使用此路径进行操作
26 | #
27 | # 请在此函数内编写自定义的脚本代码
28 | function before()
29 | {
30 | ## 一个栗子
31 | ## 获取当前脚本所在目录路径
32 | # basepath=$(cd `dirname $0`; pwd)
33 |
34 | ## 拷贝需要的文件到APP内
35 | # cp -rf "${basepath}/uc.dat" "$2/uc.dat"
36 | # cp -rf "${basepath}/AFNetworking.framework" "$2/Frameworks/AFNetworking.framework"
37 |
38 | ## 将指定动态库注入到目标二进制内
39 | # optool install -p "@rpath/AFNetworking.framework/AFNetworking" -t "$2/WeChat"
40 |
41 | echo "$@"
42 | panic 0 "调用 before"
43 | }
44 |
45 | # 重签之后调用此函数,可在此函数中重命名生成的文件,拷贝生成的文件到指定路径等
46 | # 参数如下:
47 | # $1: 原文件输入路径,如:/Users/h4ck/Downloads/Payload.ipa
48 | # $2: 重签后文件保存路径,文件格式可能为ipa或app,如:/Users/h4ck/Desktop/Payload_resign.ipa
49 | #
50 | # 请在此函数内编写自定义的脚本代码
51 | function after()
52 | {
53 | echo "$@"
54 | panic 0 "调用 after"
55 | }
56 | # -------------------------
57 |
58 | # Replica 将会调用此脚本,传入before和after参数,分别在重签开始前和重签完成后调用
59 | if [[ "$1" == "before" ]]; then
60 | before "$2" "$3"
61 | else
62 | after "$2" "$3"
63 | fi
64 |
--------------------------------------------------------------------------------
/Replica/VerifyCertView.h:
--------------------------------------------------------------------------------
1 | //
2 | // VerifyCertView.h
3 | // Replica
4 | //
5 | // Created by h4ck on 18/11/1.
6 | // Copyright © 2018年 字节时代(https://byteage.com) All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | @interface VerifyCertView : NSView
12 |
13 | @end
14 |
--------------------------------------------------------------------------------
/Replica/main.m:
--------------------------------------------------------------------------------
1 | //
2 | // main.m
3 | // Replica
4 | //
5 | // Created by h4ck on 18/11/1.
6 | // Copyright © 2018年 字节时代(https://byteage.com) All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | int main(int argc, const char * argv[]) {
12 | return NSApplicationMain(argc, argv);
13 | }
14 |
--------------------------------------------------------------------------------
/Replica/optool/NSData+Reading.h:
--------------------------------------------------------------------------------
1 | //
2 | // NSData+Reading.h
3 | // optool
4 | // Copyright (c) 2014, Alex Zielenski
5 | // All rights reserved.
6 | //
7 | // Redistribution and use in source and binary forms, with or without
8 | // modification, are permitted provided that the following conditions are met:
9 | //
10 | // * Redistributions of source code must retain the above copyright notice, this
11 | // list of conditions and the following disclaimer.
12 | //
13 | // * Redistributions in binary form must reproduce the above copyright notice,
14 | // this list of conditions and the following disclaimer in the documentation
15 | // and/or other materials provided with the distribution.
16 | //
17 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18 | // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 | // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20 | // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
21 | // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 | // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
23 | // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
24 | // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
25 | // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 |
28 | #import
29 |
30 | @interface NSData (Reading)
31 |
32 | - (NSUInteger)currentOffset;
33 | - (void)setCurrentOffset:(NSUInteger)offset;
34 |
35 | - (uint8_t)nextByte;
36 | - (uint8_t)byteAtOffset:(NSUInteger)offset;
37 |
38 | - (uint16_t)nextShort;
39 | - (uint16_t)shortAtOffset:(NSUInteger)offset;
40 |
41 | - (uint32_t)nextInt;
42 | - (uint32_t)intAtOffset:(NSUInteger)offset;
43 |
44 | - (uint64_t)nextLong;
45 | - (uint64_t)longAtOffset:(NSUInteger)offset;
46 |
47 | @end
48 |
--------------------------------------------------------------------------------
/Replica/optool/NSData+Reading.m:
--------------------------------------------------------------------------------
1 | //
2 | // NSData+Reading.m
3 | // optool
4 | // Copyright (c) 2014, Alex Zielenski
5 | // All rights reserved.
6 | //
7 | // Redistribution and use in source and binary forms, with or without
8 | // modification, are permitted provided that the following conditions are met:
9 | //
10 | // * Redistributions of source code must retain the above copyright notice, this
11 | // list of conditions and the following disclaimer.
12 | //
13 | // * Redistributions in binary form must reproduce the above copyright notice,
14 | // this list of conditions and the following disclaimer in the documentation
15 | // and/or other materials provided with the distribution.
16 | //
17 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18 | // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 | // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20 | // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
21 | // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 | // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
23 | // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
24 | // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
25 | // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 |
28 | #import "NSData+Reading.h"
29 | #import
30 |
31 | @implementation NSData (Reading)
32 |
33 | static char OFFSET;
34 | - (NSUInteger)currentOffset
35 | {
36 | NSNumber *value = objc_getAssociatedObject(self, &OFFSET);
37 | return value.unsignedIntegerValue;
38 | }
39 |
40 | - (void)setCurrentOffset:(NSUInteger)offset
41 | {
42 | [self willChangeValueForKey:@"currentOffset"];
43 | objc_setAssociatedObject(self, &OFFSET, [NSNumber numberWithUnsignedInteger:offset], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
44 | [self didChangeValueForKey:@"currentOffset"];
45 | }
46 |
47 | - (uint8_t)nextByte
48 | {
49 | uint8_t nextByte = [self byteAtOffset:self.currentOffset];
50 | self.currentOffset += sizeof(uint8_t);
51 | return nextByte;
52 | }
53 |
54 | - (uint8_t)byteAtOffset:(NSUInteger)offset
55 | {
56 | uint8_t result;
57 | [self getBytes:&result range:NSMakeRange(offset, sizeof(result))];
58 | return result;
59 | }
60 |
61 | - (uint16_t)nextShort
62 | {
63 | uint16_t nextShort = [self shortAtOffset:self.currentOffset];
64 | self.currentOffset += sizeof(uint16_t);
65 | return nextShort;
66 | }
67 |
68 | - (uint16_t)shortAtOffset:(NSUInteger)offset
69 | {
70 | uint16_t result;
71 | [self getBytes:&result range:NSMakeRange(offset, sizeof(result))];
72 | return result;
73 | }
74 |
75 | - (uint32_t)nextInt
76 | {
77 | uint32_t nextInt = [self intAtOffset:self.currentOffset];
78 | self.currentOffset += sizeof(uint32_t);
79 | return nextInt;
80 | }
81 |
82 | - (uint32_t)intAtOffset:(NSUInteger)offset
83 | {
84 | uint32_t result;
85 | [self getBytes:&result range:NSMakeRange(offset, sizeof(result))];
86 | return result;
87 | }
88 |
89 | - (uint64_t)nextLong
90 | {
91 | uint64_t nextLong = [self longAtOffset:self.currentOffset];
92 | self.currentOffset += sizeof(uint64_t);
93 | return nextLong;
94 | }
95 |
96 | - (uint64_t)longAtOffset:(NSUInteger)offset;
97 | {
98 | uint64_t result;
99 | [self getBytes:&result range:NSMakeRange(offset, sizeof(result))];
100 | return result;
101 | }
102 |
103 | @end
104 |
105 | @implementation NSMutableData (ByteAdditions)
106 |
107 | - (void)appendByte:(uint8_t)value
108 | {
109 | [self appendBytes:&value length:sizeof(value)];
110 | }
111 |
112 | - (void)appendShort:(uint16_t)value
113 | {
114 | uint16_t swap = CFSwapInt16HostToLittle(value);
115 | [self appendBytes:&swap length:sizeof(swap)];
116 | }
117 |
118 | - (void)appendInt:(uint32_t)value
119 | {
120 | uint32_t swap = CFSwapInt32HostToLittle(value);
121 | [self appendBytes:&swap length:sizeof(swap)];
122 | }
123 |
124 | - (void)appendLong:(uint64_t)value;
125 | {
126 | uint64_t swap = CFSwapInt64HostToLittle(value);
127 | [self appendBytes:&swap length:sizeof(swap)];
128 | }
129 |
130 | @end
131 |
--------------------------------------------------------------------------------
/Replica/optool/defines.h:
--------------------------------------------------------------------------------
1 | //
2 | // defines.h
3 | // optool
4 | // Copyright (c) 2014, Alex Zielenski
5 | // All rights reserved.
6 | //
7 | // Redistribution and use in source and binary forms, with or without
8 | // modification, are permitted provided that the following conditions are met:
9 | //
10 | // * Redistributions of source code must retain the above copyright notice, this
11 | // list of conditions and the following disclaimer.
12 | //
13 | // * Redistributions in binary form must reproduce the above copyright notice,
14 | // this list of conditions and the following disclaimer in the documentation
15 | // and/or other materials provided with the distribution.
16 | //
17 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18 | // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 | // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20 | // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
21 | // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 | // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
23 | // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
24 | // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
25 | // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 |
28 |
29 | #import
30 |
31 | #ifndef CPU_TYPE_ARM64
32 | #define CPU_TYPE_ARM64 (CPU_TYPE_ARM | CPU_ARCH_ABI64)
33 | #endif
34 |
35 | #define LOG(fmt, args...) printf(fmt "\n", ##args)
36 |
37 | #define CPU(CPUTYPE) ({ \
38 | const char *c = ""; \
39 | if (CPUTYPE == CPU_TYPE_I386) \
40 | c = "x86"; \
41 | if (CPUTYPE == CPU_TYPE_X86_64) \
42 | c = "x86_64"; \
43 | if (CPUTYPE == CPU_TYPE_ARM) \
44 | c = "arm"; \
45 | if (CPUTYPE == CPU_TYPE_ARM64) \
46 | c = "arm64"; \
47 | c; \
48 | })
49 |
50 | #define LC(LOADCOMMAND) ({ \
51 | const char *c = ""; \
52 | if (LOADCOMMAND == LC_REEXPORT_DYLIB) \
53 | c = "LC_REEXPORT_DYLIB";\
54 | else if (LOADCOMMAND == LC_LOAD_WEAK_DYLIB) \
55 | c = "LC_LOAD_WEAK_DYLIB";\
56 | else if (LOADCOMMAND == LC_LOAD_UPWARD_DYLIB) \
57 | c = "LC_LOAD_UPWARD_DYLIB";\
58 | else if (LOADCOMMAND == LC_LOAD_DYLIB) \
59 | c = "LC_LOAD_DYLIB";\
60 | c;\
61 | })
62 |
63 | #define COMMAND(str) ({ \
64 | uint32_t cmd = -1; \
65 | if ([str isEqualToString: @"reexport"]) \
66 | cmd = LC_REEXPORT_DYLIB; \
67 | else if ([str isEqualToString: @"weak"]) \
68 | cmd = LC_LOAD_WEAK_DYLIB; \
69 | else if ([str isEqualToString: @"upward"]) \
70 | cmd = LC_LOAD_UPWARD_DYLIB; \
71 | else if ([str isEqualToString: @"load"]) \
72 | cmd = LC_LOAD_DYLIB; \
73 | cmd; \
74 | })
75 |
76 | // we pass around this header which includes some extra information
77 | // and a 32-bit header which we used for both 32-bit and 64-bit files
78 | // since the 64-bit just adds an extra field to the end which we don't need
79 | struct thin_header {
80 | uint32_t offset;
81 | uint32_t size;
82 | struct mach_header header;
83 | };
84 |
85 | typedef NS_ENUM(int, OPError) {
86 | OPErrorNone = 0,
87 | OPErrorRead = 1, // failed to read target path
88 | OPErrorIncompatibleBinary = 2, // couldn't find x86 or x86_64 architecture in binary
89 | OPErrorStripFailure = 3, // failed to strip codesignature
90 | OPErrorWriteFailure = 4, // failed to write data to final output path
91 | OPErrorNoBackup = 5, // no backup to restore
92 | OPErrorRemovalFailure = 6, // failed to remove executable during restore
93 | OPErrorMoveFailure = 7, // failed to move backup to correct location
94 | OPErrorNoEntries = 8, // cant remove dylib entries because they dont exist
95 | OPErrorInsertFailure = 9, // failed to insert load command
96 | OPErrorInvalidLoadCommand = 10, // user provided an unnacceptable load command string
97 | OPErrorResignFailure = 11, // codesign failed for some reason
98 | OPErrorBackupFailure = 12, // failed to write backup
99 | OPErrorInvalidArguments = 13, // bad arguments
100 | OPErrorBadULEB = 14, // uleb while reading binding ordinals is in an invalid format
101 | OPErrorULEBEncodeFailure = 15 // failed to encode a uleb within specified length requirements
102 | };
--------------------------------------------------------------------------------
/Replica/optool/headers.h:
--------------------------------------------------------------------------------
1 | //
2 | // headers.h
3 | // optool
4 | // Copyright (c) 2014, Alex Zielenski
5 | // All rights reserved.
6 | //
7 | // Redistribution and use in source and binary forms, with or without
8 | // modification, are permitted provided that the following conditions are met:
9 | //
10 | // * Redistributions of source code must retain the above copyright notice, this
11 | // list of conditions and the following disclaimer.
12 | //
13 | // * Redistributions in binary form must reproduce the above copyright notice,
14 | // this list of conditions and the following disclaimer in the documentation
15 | // and/or other materials provided with the distribution.
16 | //
17 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18 | // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 | // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20 | // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
21 | // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 | // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
23 | // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
24 | // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
25 | // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 |
28 | #import
29 | #import "defines.h"
30 |
31 | struct thin_header headerAtOffset(NSData *binary, uint32_t offset);
32 | struct thin_header *headersFromBinary(struct thin_header *headers, NSData *binary, uint32_t *amount);
--------------------------------------------------------------------------------
/Replica/optool/headers.m:
--------------------------------------------------------------------------------
1 | //
2 | // headers.m
3 | // optool
4 | // Copyright (c) 2014, Alex Zielenski
5 | // All rights reserved.
6 | //
7 | // Redistribution and use in source and binary forms, with or without
8 | // modification, are permitted provided that the following conditions are met:
9 | //
10 | // * Redistributions of source code must retain the above copyright notice, this
11 | // list of conditions and the following disclaimer.
12 | //
13 | // * Redistributions in binary form must reproduce the above copyright notice,
14 | // this list of conditions and the following disclaimer in the documentation
15 | // and/or other materials provided with the distribution.
16 | //
17 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18 | // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 | // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20 | // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
21 | // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 | // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
23 | // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
24 | // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
25 | // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 |
28 | #import "headers.h"
29 | #import
30 | #import
31 | #import "NSData+Reading.h"
32 |
33 | struct thin_header headerAtOffset(NSData *binary, uint32_t offset) {
34 | struct thin_header macho;
35 | macho.offset = offset;
36 | macho.header = *(struct mach_header *)(binary.bytes + offset);
37 | if (macho.header.magic == MH_MAGIC || macho.header.magic == MH_CIGAM) {
38 | macho.size = sizeof(struct mach_header);
39 | } else {
40 | macho.size = sizeof(struct mach_header_64);
41 | }
42 | if (macho.header.cputype != CPU_TYPE_X86_64 && macho.header.cputype != CPU_TYPE_I386 && macho.header.cputype != CPU_TYPE_ARM && macho.header.cputype != CPU_TYPE_ARM64){
43 | macho.size = 0;
44 | }
45 |
46 | return macho;
47 | }
48 |
49 | struct thin_header *headersFromBinary(struct thin_header *headers, NSData *binary, uint32_t *amount) {
50 | // In a MachO/FAT binary the first 4 bytes is a magic number
51 | // which gives details about the type of binary it is
52 | // CIGAM and co. mean the target binary has a byte order
53 | // in reverse relation to the host machine so we have to swap the bytes
54 | uint32_t magic = [binary intAtOffset:0];
55 | bool shouldSwap = magic == MH_CIGAM || magic == MH_CIGAM_64 || magic == FAT_CIGAM;
56 | #define SWAP(NUM) shouldSwap ? CFSwapInt32(NUM) : NUM
57 |
58 | uint32_t numArchs = 0;
59 |
60 | // a FAT file is basically a collection of thin MachO binaries
61 | if (magic == FAT_CIGAM || magic == FAT_MAGIC) {
62 | LOG("Found FAT Header");
63 |
64 | // WE GOT A FAT ONE
65 | struct fat_header fat = *(struct fat_header *)binary.bytes;
66 | fat.nfat_arch = SWAP(fat.nfat_arch);
67 | int offset = sizeof(struct fat_header);
68 |
69 | // Loop through the architectures within the FAT binary to find
70 | // a thin macho header that we can work with (x86 or x86_64)
71 | for (int i = 0; i < fat.nfat_arch; i++) {
72 | struct fat_arch arch;
73 | arch = *(struct fat_arch *)([binary bytes] + offset);
74 | arch.cputype = SWAP(arch.cputype);
75 | arch.offset = SWAP(arch.offset);
76 |
77 | struct thin_header macho = headerAtOffset(binary, arch.offset);
78 | if (macho.size > 0) {
79 | LOG("Found thin header...");
80 |
81 | headers[numArchs] = macho;
82 | numArchs++;
83 | }
84 |
85 | offset += sizeof(struct fat_arch);
86 | }
87 | // The binary is thin, meaning it contains only one architecture
88 | } else if (magic == MH_MAGIC || magic == MH_MAGIC_64) {
89 | struct thin_header macho = headerAtOffset(binary, 0);
90 | if (macho.size > 0) {
91 | LOG("Found thin header...");
92 |
93 | numArchs++;
94 | headers[0] = macho;
95 | }
96 |
97 | } else {
98 | LOG("No headers found.");
99 | }
100 |
101 | *amount = numArchs;
102 |
103 | return headers;
104 | }
105 |
--------------------------------------------------------------------------------
/Replica/optool/operations.h:
--------------------------------------------------------------------------------
1 | //
2 | // operations.h
3 | // optool
4 | // Copyright (c) 2014, Alex Zielenski
5 | // All rights reserved.
6 | //
7 | // Redistribution and use in source and binary forms, with or without
8 | // modification, are permitted provided that the following conditions are met:
9 | //
10 | // * Redistributions of source code must retain the above copyright notice, this
11 | // list of conditions and the following disclaimer.
12 | //
13 | // * Redistributions in binary form must reproduce the above copyright notice,
14 | // this list of conditions and the following disclaimer in the documentation
15 | // and/or other materials provided with the distribution.
16 | //
17 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18 | // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 | // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20 | // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
21 | // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 | // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
23 | // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
24 | // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
25 | // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 |
28 |
29 | #import
30 | #import "defines.h"
31 |
32 | BOOL stripCodeSignatureFromBinary(NSMutableData *binary, struct thin_header macho, BOOL soft);
33 | BOOL unrestrictBinary(NSMutableData *binary, struct thin_header macho, BOOL soft);
34 | BOOL removeLoadEntryFromBinary(NSMutableData *binary, struct thin_header macho, NSString *payload);
35 | BOOL binaryHasLoadCommandForDylib(NSMutableData *binary, NSString *dylib, uint32_t *lastOffset, struct thin_header macho);
36 | BOOL insertLoadEntryIntoBinary(NSString *dylibPath, NSMutableData *binary, struct thin_header macho, uint32_t type);
37 | BOOL removeASLRFromBinary(NSMutableData *binary, struct thin_header macho);
38 | BOOL renameBinary(NSMutableData *binary, struct thin_header macho, NSString *from, NSString *to);
39 |
--------------------------------------------------------------------------------
/ScreenShot/QQ20190321-000789@2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lemon4ex/Replica/dfd190a3667a47e19b45da4d9492209114073de6/ScreenShot/QQ20190321-000789@2x.png
--------------------------------------------------------------------------------
/ScreenShot/QQ20190321-000790@2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lemon4ex/Replica/dfd190a3667a47e19b45da4d9492209114073de6/ScreenShot/QQ20190321-000790@2x.png
--------------------------------------------------------------------------------
/ScreenShot/QQ20190321-000792@2x.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/lemon4ex/Replica/dfd190a3667a47e19b45da4d9492209114073de6/ScreenShot/QQ20190321-000792@2x.png
--------------------------------------------------------------------------------