├── README.md ├── RSA加密 ├── RSA加密.xcodeproj │ ├── project.pbxproj │ ├── project.xcworkspace │ │ ├── contents.xcworkspacedata │ │ └── xcuserdata │ │ │ ├── basic_10.xcuserdatad │ │ │ └── UserInterfaceState.xcuserstate │ │ │ └── craneteng.xcuserdatad │ │ │ └── UserInterfaceState.xcuserstate │ └── xcuserdata │ │ ├── basic_10.xcuserdatad │ │ ├── xcdebugger │ │ │ └── Breakpoints_v2.xcbkptlist │ │ └── xcschemes │ │ │ ├── RSA加密.xcscheme │ │ │ └── xcschememanagement.plist │ │ └── craneteng.xcuserdatad │ │ └── xcschemes │ │ ├── RSA加密.xcscheme │ │ └── xcschememanagement.plist └── RSA加密 │ ├── AppDelegate.h │ ├── AppDelegate.m │ ├── Assets.xcassets │ └── AppIcon.appiconset │ │ └── Contents.json │ ├── Base.lproj │ ├── LaunchScreen.storyboard │ └── Main.storyboard │ ├── Info.plist │ ├── ViewController.h │ ├── ViewController.m │ ├── XHCryptorTools.h │ ├── XHCryptorTools.m │ ├── main.m │ ├── p.p12 │ ├── private.pem │ ├── rsacert.crt │ ├── rsacert.csr │ └── rsacert.der ├── XHCryptorTools.h └── XHCryptorTools.m /README.md: -------------------------------------------------------------------------------- 1 | 2 | #工具类介绍 3 | 框架从 CryptoExercise(苹果3.0时的包)进行提取扩展 4 | iOS 系统自带相关函数说明,框架主要使用前两种: 5 | SecKeyEncrypt 使用公钥对数据加密 6 | SecKeyDecrypt 使用私钥对数据解密 7 | SecKeyRawVerify 使用公钥对数字签名进行验证 8 | SecKeyRawSign 使用私钥生成数字签名 9 | 10 | ####普遍的加密方法:客户端用RSA的公钥加密AES的秘钥,服务器端用私钥解开获得的AES的秘钥,客户端再与服务器端进行AES加密的数据传输,即HTTPS协议传输的原理 11 | --- 12 | #加密解密概念 13 | * 对称加密算法:加密解密都使用相同的秘钥,速度快,适合对大数据加密,方法有DES,3DES,AES等 14 | 15 | * 非对称加密算法 16 | 非对称加密算法需要两个密钥:公开密钥(publickey)和私有密钥(privatekey) 17 | 公开密钥与私有密钥是一对,可逆的加密算法,用公钥加密,用私钥解密,用私钥加密,用公钥解密,速度慢,适合对小数据加密,方法有RSA 18 | 19 | * 散列算法(加密后不能解密,上面都是可以解密的) 20 | 用于密码的密文存储,服务器端是判断加密后的数据 21 | 不可逆加密方法:MD5、SHA1、SHA256、SHA512 22 | 23 | 24 | > RSA算法原理: 25 | 1. 找出两个“很大”的质数:P & Q(上百位) 26 | N = P * Q 27 | M = (P – 1) * (Q – 1) 28 | 2. 找出整数E,E与M互质,即除了1之外,没有其他公约数 29 | 3. 找出整数D,使得 ED 除以 M 余 1,即 (E * D) % M = 1 30 | 4. 经过上述准备工作之后,可以得到:E是公钥,负责加密D是私钥,负责解密N负责公钥和私钥之间的联系 31 | 5. 加密算法,假定对X进行加密(X ^ E) % N = Y(6)解密算法,根据费尔马小定义,可以使用以下公式完成解密(Y ^ D) % N = X 32 | 33 | --- 34 | #使用方法 35 | ~~~ 36 | XHCryptorTools *tools = [[XHCryptorTools alloc] init]; 37 | // 1. 加载公钥 38 | NSString *pubPath = [[NSBundle mainBundle] pathForResource:@"rsacert.der" ofType:nil]; 39 | [tools loadPublicKeyWithFilePath:pubPath]; 40 | // 2. 使用公钥加密,加密内容最大长度 117 41 | NSString *result = [tools RSAEncryptString:@"abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890abcdefghi"]; 42 | NSLog(@"RSA 加密 %@", result); 43 | // 3. 加载私钥,并指定导出 p12 时设置的密码 44 | NSString *privatePath = [[NSBundle mainBundle] pathForResource:@"p.p12" ofType:nil]; 45 | [tools loadPrivateKey:privatePath password:@"123"]; 46 | // 4. 使用私钥解密 47 | NSLog(@"解密结果 %@", [tools RSADecryptString:result]); 48 | ~~~ 49 | --- 50 | #公钥、私钥生成 51 | >公钥:就是签名机构签完给我们颁发的,放在网站的根目录上,可以分发 52 | 私钥:一般保存在中心服务器 53 | 54 | ######加密解密使用了两种文件 .p12是私钥  .der是公钥,终端命令生成步骤如下: 55 | 1. 创建私钥,生成安全强度是512(也可以是1024)的RAS私钥,.pem是base64的证书文件 56 | `openssl genrsa -out private.pem 512` 57 | 2. 生成一个证书请求,生成证书请求文件.csr 58 | `openssl req -new -key private.pem -out rsacert.csr` 59 | 60 | >终端提示如下: 61 | * 国家名字、代码 62 | * 省的名字 63 | * 城市的名字 64 | * 公司的名字 65 | * 公司的单位 66 | * 我的名字 67 | * 电子邮件 68 | * 以及两个附加信息可以跳过 69 | 70 | ![生成证书请求界面](http://upload-images.jianshu.io/upload_images/1385290-336f85949fdb4ad7.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 71 | 72 | 3. 签名,找证书颁发机构签名,证明证书合法有效的,也可以自签名一个证书 73 | 生成证书并签名,有效期10年,生成一个.crt的一个base64公钥文件 74 | `openssl x509 -req -days 3650 -in rsacert.csr -signkey private.pem -out rsacert.crt` 75 | 由于iOS开发时使用的时候不能是base64的,必须解成二进制文件! 76 | 77 | 4. 解成.der公钥二进制文件,放程序做加密用 78 | `openssl x509 -outform der -in rsacert.crt -out rsacert.der` 79 | 80 | 5. 生成.p12二进制私钥文件 81 | .pem 是base64的不能直接使用,必须导成.p12信息交换文件用来传递秘钥 82 | `openssl pkcs12 -export -out p.p12 -inkey private.pem -in rsacert.crt` 83 | 输入一个导出密码(框架中loadPrivateKey:方法的password参数需要用的密码): 84 | ![输入导出密码界面.png](http://upload-images.jianshu.io/upload_images/1385290-afb3dbc16d06cab0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 85 | -------------------------------------------------------------------------------- /RSA加密/RSA加密.xcodeproj/project.pbxproj: -------------------------------------------------------------------------------- 1 | // !$*UTF8*$! 2 | { 3 | archiveVersion = 1; 4 | classes = { 5 | }; 6 | objectVersion = 46; 7 | objects = { 8 | 9 | /* Begin PBXBuildFile section */ 10 | 45516CEB1CD874EE00C3511F /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 45516CEA1CD874EE00C3511F /* main.m */; }; 11 | 45516CEE1CD874EE00C3511F /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 45516CED1CD874EE00C3511F /* AppDelegate.m */; }; 12 | 45516CF11CD874EE00C3511F /* ViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 45516CF01CD874EE00C3511F /* ViewController.m */; }; 13 | 45516CF41CD874EE00C3511F /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 45516CF21CD874EE00C3511F /* Main.storyboard */; }; 14 | 45516CF61CD874EE00C3511F /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 45516CF51CD874EE00C3511F /* Assets.xcassets */; }; 15 | 45516CF91CD874EE00C3511F /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 45516CF71CD874EE00C3511F /* LaunchScreen.storyboard */; }; 16 | 45516D021CD8750300C3511F /* XHCryptorTools.m in Sources */ = {isa = PBXBuildFile; fileRef = 45516D011CD8750300C3511F /* XHCryptorTools.m */; settings = {ASSET_TAGS = (); }; }; 17 | 45516D081CD8761100C3511F /* p.p12 in Resources */ = {isa = PBXBuildFile; fileRef = 45516D031CD8761100C3511F /* p.p12 */; settings = {ASSET_TAGS = (); }; }; 18 | 45516D091CD8761100C3511F /* private.pem in Resources */ = {isa = PBXBuildFile; fileRef = 45516D041CD8761100C3511F /* private.pem */; settings = {ASSET_TAGS = (); }; }; 19 | 45516D0A1CD8761100C3511F /* rsacert.crt in Resources */ = {isa = PBXBuildFile; fileRef = 45516D051CD8761100C3511F /* rsacert.crt */; settings = {ASSET_TAGS = (); }; }; 20 | 45516D0B1CD8761100C3511F /* rsacert.csr in Resources */ = {isa = PBXBuildFile; fileRef = 45516D061CD8761100C3511F /* rsacert.csr */; settings = {ASSET_TAGS = (); }; }; 21 | 45516D0C1CD8761100C3511F /* rsacert.der in Resources */ = {isa = PBXBuildFile; fileRef = 45516D071CD8761100C3511F /* rsacert.der */; settings = {ASSET_TAGS = (); }; }; 22 | /* End PBXBuildFile section */ 23 | 24 | /* Begin PBXFileReference section */ 25 | 45516CE61CD874EE00C3511F /* RSA加密.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "RSA加密.app"; sourceTree = BUILT_PRODUCTS_DIR; }; 26 | 45516CEA1CD874EE00C3511F /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; 27 | 45516CEC1CD874EE00C3511F /* AppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; }; 28 | 45516CED1CD874EE00C3511F /* AppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = ""; }; 29 | 45516CEF1CD874EE00C3511F /* ViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ViewController.h; sourceTree = ""; }; 30 | 45516CF01CD874EE00C3511F /* ViewController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = ViewController.m; sourceTree = ""; }; 31 | 45516CF31CD874EE00C3511F /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; 32 | 45516CF51CD874EE00C3511F /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 33 | 45516CF81CD874EE00C3511F /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 34 | 45516CFA1CD874EE00C3511F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 35 | 45516D001CD8750300C3511F /* XHCryptorTools.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = XHCryptorTools.h; sourceTree = ""; }; 36 | 45516D011CD8750300C3511F /* XHCryptorTools.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = XHCryptorTools.m; sourceTree = ""; }; 37 | 45516D031CD8761100C3511F /* p.p12 */ = {isa = PBXFileReference; lastKnownFileType = file; path = p.p12; sourceTree = ""; }; 38 | 45516D041CD8761100C3511F /* private.pem */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = private.pem; sourceTree = ""; }; 39 | 45516D051CD8761100C3511F /* rsacert.crt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = rsacert.crt; sourceTree = ""; }; 40 | 45516D061CD8761100C3511F /* rsacert.csr */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = rsacert.csr; sourceTree = ""; }; 41 | 45516D071CD8761100C3511F /* rsacert.der */ = {isa = PBXFileReference; lastKnownFileType = file; path = rsacert.der; sourceTree = ""; }; 42 | /* End PBXFileReference section */ 43 | 44 | /* Begin PBXFrameworksBuildPhase section */ 45 | 45516CE31CD874EE00C3511F /* Frameworks */ = { 46 | isa = PBXFrameworksBuildPhase; 47 | buildActionMask = 2147483647; 48 | files = ( 49 | ); 50 | runOnlyForDeploymentPostprocessing = 0; 51 | }; 52 | /* End PBXFrameworksBuildPhase section */ 53 | 54 | /* Begin PBXGroup section */ 55 | 45516CDD1CD874EE00C3511F = { 56 | isa = PBXGroup; 57 | children = ( 58 | 45516CE81CD874EE00C3511F /* RSA加密 */, 59 | 45516CE71CD874EE00C3511F /* Products */, 60 | ); 61 | sourceTree = ""; 62 | }; 63 | 45516CE71CD874EE00C3511F /* Products */ = { 64 | isa = PBXGroup; 65 | children = ( 66 | 45516CE61CD874EE00C3511F /* RSA加密.app */, 67 | ); 68 | name = Products; 69 | sourceTree = ""; 70 | }; 71 | 45516CE81CD874EE00C3511F /* RSA加密 */ = { 72 | isa = PBXGroup; 73 | children = ( 74 | 45516D031CD8761100C3511F /* p.p12 */, 75 | 45516D041CD8761100C3511F /* private.pem */, 76 | 45516D051CD8761100C3511F /* rsacert.crt */, 77 | 45516D061CD8761100C3511F /* rsacert.csr */, 78 | 45516D071CD8761100C3511F /* rsacert.der */, 79 | 45516D001CD8750300C3511F /* XHCryptorTools.h */, 80 | 45516D011CD8750300C3511F /* XHCryptorTools.m */, 81 | 45516CEC1CD874EE00C3511F /* AppDelegate.h */, 82 | 45516CED1CD874EE00C3511F /* AppDelegate.m */, 83 | 45516CEF1CD874EE00C3511F /* ViewController.h */, 84 | 45516CF01CD874EE00C3511F /* ViewController.m */, 85 | 45516CF21CD874EE00C3511F /* Main.storyboard */, 86 | 45516CF51CD874EE00C3511F /* Assets.xcassets */, 87 | 45516CF71CD874EE00C3511F /* LaunchScreen.storyboard */, 88 | 45516CFA1CD874EE00C3511F /* Info.plist */, 89 | 45516CE91CD874EE00C3511F /* Supporting Files */, 90 | ); 91 | path = "RSA加密"; 92 | sourceTree = ""; 93 | }; 94 | 45516CE91CD874EE00C3511F /* Supporting Files */ = { 95 | isa = PBXGroup; 96 | children = ( 97 | 45516CEA1CD874EE00C3511F /* main.m */, 98 | ); 99 | name = "Supporting Files"; 100 | sourceTree = ""; 101 | }; 102 | /* End PBXGroup section */ 103 | 104 | /* Begin PBXNativeTarget section */ 105 | 45516CE51CD874EE00C3511F /* RSA加密 */ = { 106 | isa = PBXNativeTarget; 107 | buildConfigurationList = 45516CFD1CD874EE00C3511F /* Build configuration list for PBXNativeTarget "RSA加密" */; 108 | buildPhases = ( 109 | 45516CE21CD874EE00C3511F /* Sources */, 110 | 45516CE31CD874EE00C3511F /* Frameworks */, 111 | 45516CE41CD874EE00C3511F /* Resources */, 112 | ); 113 | buildRules = ( 114 | ); 115 | dependencies = ( 116 | ); 117 | name = "RSA加密"; 118 | productName = "RSA加密"; 119 | productReference = 45516CE61CD874EE00C3511F /* RSA加密.app */; 120 | productType = "com.apple.product-type.application"; 121 | }; 122 | /* End PBXNativeTarget section */ 123 | 124 | /* Begin PBXProject section */ 125 | 45516CDE1CD874EE00C3511F /* Project object */ = { 126 | isa = PBXProject; 127 | attributes = { 128 | LastUpgradeCheck = 0700; 129 | ORGANIZATIONNAME = heima; 130 | TargetAttributes = { 131 | 45516CE51CD874EE00C3511F = { 132 | CreatedOnToolsVersion = 7.0; 133 | }; 134 | }; 135 | }; 136 | buildConfigurationList = 45516CE11CD874EE00C3511F /* Build configuration list for PBXProject "RSA加密" */; 137 | compatibilityVersion = "Xcode 3.2"; 138 | developmentRegion = English; 139 | hasScannedForEncodings = 0; 140 | knownRegions = ( 141 | en, 142 | Base, 143 | ); 144 | mainGroup = 45516CDD1CD874EE00C3511F; 145 | productRefGroup = 45516CE71CD874EE00C3511F /* Products */; 146 | projectDirPath = ""; 147 | projectRoot = ""; 148 | targets = ( 149 | 45516CE51CD874EE00C3511F /* RSA加密 */, 150 | ); 151 | }; 152 | /* End PBXProject section */ 153 | 154 | /* Begin PBXResourcesBuildPhase section */ 155 | 45516CE41CD874EE00C3511F /* Resources */ = { 156 | isa = PBXResourcesBuildPhase; 157 | buildActionMask = 2147483647; 158 | files = ( 159 | 45516D0C1CD8761100C3511F /* rsacert.der in Resources */, 160 | 45516CF91CD874EE00C3511F /* LaunchScreen.storyboard in Resources */, 161 | 45516D091CD8761100C3511F /* private.pem in Resources */, 162 | 45516D0B1CD8761100C3511F /* rsacert.csr in Resources */, 163 | 45516CF61CD874EE00C3511F /* Assets.xcassets in Resources */, 164 | 45516D081CD8761100C3511F /* p.p12 in Resources */, 165 | 45516D0A1CD8761100C3511F /* rsacert.crt in Resources */, 166 | 45516CF41CD874EE00C3511F /* Main.storyboard in Resources */, 167 | ); 168 | runOnlyForDeploymentPostprocessing = 0; 169 | }; 170 | /* End PBXResourcesBuildPhase section */ 171 | 172 | /* Begin PBXSourcesBuildPhase section */ 173 | 45516CE21CD874EE00C3511F /* Sources */ = { 174 | isa = PBXSourcesBuildPhase; 175 | buildActionMask = 2147483647; 176 | files = ( 177 | 45516CF11CD874EE00C3511F /* ViewController.m in Sources */, 178 | 45516CEE1CD874EE00C3511F /* AppDelegate.m in Sources */, 179 | 45516CEB1CD874EE00C3511F /* main.m in Sources */, 180 | 45516D021CD8750300C3511F /* XHCryptorTools.m in Sources */, 181 | ); 182 | runOnlyForDeploymentPostprocessing = 0; 183 | }; 184 | /* End PBXSourcesBuildPhase section */ 185 | 186 | /* Begin PBXVariantGroup section */ 187 | 45516CF21CD874EE00C3511F /* Main.storyboard */ = { 188 | isa = PBXVariantGroup; 189 | children = ( 190 | 45516CF31CD874EE00C3511F /* Base */, 191 | ); 192 | name = Main.storyboard; 193 | sourceTree = ""; 194 | }; 195 | 45516CF71CD874EE00C3511F /* LaunchScreen.storyboard */ = { 196 | isa = PBXVariantGroup; 197 | children = ( 198 | 45516CF81CD874EE00C3511F /* Base */, 199 | ); 200 | name = LaunchScreen.storyboard; 201 | sourceTree = ""; 202 | }; 203 | /* End PBXVariantGroup section */ 204 | 205 | /* Begin XCBuildConfiguration section */ 206 | 45516CFB1CD874EE00C3511F /* Debug */ = { 207 | isa = XCBuildConfiguration; 208 | buildSettings = { 209 | ALWAYS_SEARCH_USER_PATHS = NO; 210 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; 211 | CLANG_CXX_LIBRARY = "libc++"; 212 | CLANG_ENABLE_MODULES = YES; 213 | CLANG_ENABLE_OBJC_ARC = YES; 214 | CLANG_WARN_BOOL_CONVERSION = YES; 215 | CLANG_WARN_CONSTANT_CONVERSION = YES; 216 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 217 | CLANG_WARN_EMPTY_BODY = YES; 218 | CLANG_WARN_ENUM_CONVERSION = YES; 219 | CLANG_WARN_INT_CONVERSION = YES; 220 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 221 | CLANG_WARN_UNREACHABLE_CODE = YES; 222 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 223 | "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; 224 | COPY_PHASE_STRIP = NO; 225 | DEBUG_INFORMATION_FORMAT = dwarf; 226 | ENABLE_STRICT_OBJC_MSGSEND = YES; 227 | ENABLE_TESTABILITY = YES; 228 | GCC_C_LANGUAGE_STANDARD = gnu99; 229 | GCC_DYNAMIC_NO_PIC = NO; 230 | GCC_NO_COMMON_BLOCKS = YES; 231 | GCC_OPTIMIZATION_LEVEL = 0; 232 | GCC_PREPROCESSOR_DEFINITIONS = ( 233 | "DEBUG=1", 234 | "$(inherited)", 235 | ); 236 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 237 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 238 | GCC_WARN_UNDECLARED_SELECTOR = YES; 239 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 240 | GCC_WARN_UNUSED_FUNCTION = YES; 241 | GCC_WARN_UNUSED_VARIABLE = YES; 242 | IPHONEOS_DEPLOYMENT_TARGET = 9.0; 243 | MTL_ENABLE_DEBUG_INFO = YES; 244 | ONLY_ACTIVE_ARCH = YES; 245 | SDKROOT = iphoneos; 246 | }; 247 | name = Debug; 248 | }; 249 | 45516CFC1CD874EE00C3511F /* Release */ = { 250 | isa = XCBuildConfiguration; 251 | buildSettings = { 252 | ALWAYS_SEARCH_USER_PATHS = NO; 253 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; 254 | CLANG_CXX_LIBRARY = "libc++"; 255 | CLANG_ENABLE_MODULES = YES; 256 | CLANG_ENABLE_OBJC_ARC = YES; 257 | CLANG_WARN_BOOL_CONVERSION = YES; 258 | CLANG_WARN_CONSTANT_CONVERSION = YES; 259 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 260 | CLANG_WARN_EMPTY_BODY = YES; 261 | CLANG_WARN_ENUM_CONVERSION = YES; 262 | CLANG_WARN_INT_CONVERSION = YES; 263 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 264 | CLANG_WARN_UNREACHABLE_CODE = YES; 265 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 266 | "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; 267 | COPY_PHASE_STRIP = NO; 268 | DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; 269 | ENABLE_NS_ASSERTIONS = NO; 270 | ENABLE_STRICT_OBJC_MSGSEND = YES; 271 | GCC_C_LANGUAGE_STANDARD = gnu99; 272 | GCC_NO_COMMON_BLOCKS = YES; 273 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 274 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 275 | GCC_WARN_UNDECLARED_SELECTOR = YES; 276 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 277 | GCC_WARN_UNUSED_FUNCTION = YES; 278 | GCC_WARN_UNUSED_VARIABLE = YES; 279 | IPHONEOS_DEPLOYMENT_TARGET = 9.0; 280 | MTL_ENABLE_DEBUG_INFO = NO; 281 | SDKROOT = iphoneos; 282 | VALIDATE_PRODUCT = YES; 283 | }; 284 | name = Release; 285 | }; 286 | 45516CFE1CD874EE00C3511F /* Debug */ = { 287 | isa = XCBuildConfiguration; 288 | buildSettings = { 289 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; 290 | INFOPLIST_FILE = "RSA加密/Info.plist"; 291 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; 292 | PRODUCT_BUNDLE_IDENTIFIER = "cn.8test.RSA--"; 293 | PRODUCT_NAME = "$(TARGET_NAME)"; 294 | }; 295 | name = Debug; 296 | }; 297 | 45516CFF1CD874EE00C3511F /* Release */ = { 298 | isa = XCBuildConfiguration; 299 | buildSettings = { 300 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; 301 | INFOPLIST_FILE = "RSA加密/Info.plist"; 302 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; 303 | PRODUCT_BUNDLE_IDENTIFIER = "cn.8test.RSA--"; 304 | PRODUCT_NAME = "$(TARGET_NAME)"; 305 | }; 306 | name = Release; 307 | }; 308 | /* End XCBuildConfiguration section */ 309 | 310 | /* Begin XCConfigurationList section */ 311 | 45516CE11CD874EE00C3511F /* Build configuration list for PBXProject "RSA加密" */ = { 312 | isa = XCConfigurationList; 313 | buildConfigurations = ( 314 | 45516CFB1CD874EE00C3511F /* Debug */, 315 | 45516CFC1CD874EE00C3511F /* Release */, 316 | ); 317 | defaultConfigurationIsVisible = 0; 318 | defaultConfigurationName = Release; 319 | }; 320 | 45516CFD1CD874EE00C3511F /* Build configuration list for PBXNativeTarget "RSA加密" */ = { 321 | isa = XCConfigurationList; 322 | buildConfigurations = ( 323 | 45516CFE1CD874EE00C3511F /* Debug */, 324 | 45516CFF1CD874EE00C3511F /* Release */, 325 | ); 326 | defaultConfigurationIsVisible = 0; 327 | }; 328 | /* End XCConfigurationList section */ 329 | }; 330 | rootObject = 45516CDE1CD874EE00C3511F /* Project object */; 331 | } 332 | -------------------------------------------------------------------------------- /RSA加密/RSA加密.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /RSA加密/RSA加密.xcodeproj/project.xcworkspace/xcuserdata/basic_10.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XHTeng/XHCryptorTools/3f49fe92d069095aa0ceca85365b79e799693bd0/RSA加密/RSA加密.xcodeproj/project.xcworkspace/xcuserdata/basic_10.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /RSA加密/RSA加密.xcodeproj/project.xcworkspace/xcuserdata/craneteng.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XHTeng/XHCryptorTools/3f49fe92d069095aa0ceca85365b79e799693bd0/RSA加密/RSA加密.xcodeproj/project.xcworkspace/xcuserdata/craneteng.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /RSA加密/RSA加密.xcodeproj/xcuserdata/basic_10.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | -------------------------------------------------------------------------------- /RSA加密/RSA加密.xcodeproj/xcuserdata/basic_10.xcuserdatad/xcschemes/RSA加密.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 32 | 33 | 39 | 40 | 41 | 42 | 43 | 44 | 54 | 56 | 62 | 63 | 64 | 65 | 66 | 67 | 73 | 75 | 81 | 82 | 83 | 84 | 86 | 87 | 90 | 91 | 92 | -------------------------------------------------------------------------------- /RSA加密/RSA加密.xcodeproj/xcuserdata/basic_10.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | RSA加密.xcscheme 8 | 9 | orderHint 10 | 0 11 | 12 | 13 | SuppressBuildableAutocreation 14 | 15 | 45516CE51CD874EE00C3511F 16 | 17 | primary 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /RSA加密/RSA加密.xcodeproj/xcuserdata/craneteng.xcuserdatad/xcschemes/RSA加密.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 32 | 33 | 39 | 40 | 41 | 42 | 43 | 44 | 54 | 56 | 62 | 63 | 64 | 65 | 66 | 67 | 73 | 75 | 81 | 82 | 83 | 84 | 86 | 87 | 90 | 91 | 92 | -------------------------------------------------------------------------------- /RSA加密/RSA加密.xcodeproj/xcuserdata/craneteng.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | RSA加密.xcscheme 8 | 9 | orderHint 10 | 0 11 | 12 | 13 | SuppressBuildableAutocreation 14 | 15 | 45516CE51CD874EE00C3511F 16 | 17 | primary 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /RSA加密/RSA加密/AppDelegate.h: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.h 3 | // RSA加密 4 | // 5 | // Created by XHTeng on 16/5/3. 6 | // Copyright © 2016年 XHTeng. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface AppDelegate : UIResponder 12 | 13 | @property (strong, nonatomic) UIWindow *window; 14 | 15 | 16 | @end 17 | 18 | -------------------------------------------------------------------------------- /RSA加密/RSA加密/AppDelegate.m: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.m 3 | // RSA加密 4 | // 5 | // Created by XHTeng on 16/5/3. 6 | // Copyright © 2016年 XHTeng. All rights reserved. 7 | // 8 | 9 | #import "AppDelegate.h" 10 | 11 | @interface AppDelegate () 12 | 13 | @end 14 | 15 | @implementation AppDelegate 16 | 17 | 18 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 19 | // Override point for customization after application launch. 20 | return YES; 21 | } 22 | 23 | - (void)applicationWillResignActive:(UIApplication *)application { 24 | // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. 25 | // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. 26 | } 27 | 28 | - (void)applicationDidEnterBackground:(UIApplication *)application { 29 | // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 30 | // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 31 | } 32 | 33 | - (void)applicationWillEnterForeground:(UIApplication *)application { 34 | // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. 35 | } 36 | 37 | - (void)applicationDidBecomeActive:(UIApplication *)application { 38 | // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. 39 | } 40 | 41 | - (void)applicationWillTerminate:(UIApplication *)application { 42 | // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. 43 | } 44 | 45 | @end 46 | -------------------------------------------------------------------------------- /RSA加密/RSA加密/Assets.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "iphone", 5 | "size" : "29x29", 6 | "scale" : "2x" 7 | }, 8 | { 9 | "idiom" : "iphone", 10 | "size" : "29x29", 11 | "scale" : "3x" 12 | }, 13 | { 14 | "idiom" : "iphone", 15 | "size" : "40x40", 16 | "scale" : "2x" 17 | }, 18 | { 19 | "idiom" : "iphone", 20 | "size" : "40x40", 21 | "scale" : "3x" 22 | }, 23 | { 24 | "idiom" : "iphone", 25 | "size" : "60x60", 26 | "scale" : "2x" 27 | }, 28 | { 29 | "idiom" : "iphone", 30 | "size" : "60x60", 31 | "scale" : "3x" 32 | } 33 | ], 34 | "info" : { 35 | "version" : 1, 36 | "author" : "xcode" 37 | } 38 | } -------------------------------------------------------------------------------- /RSA加密/RSA加密/Base.lproj/LaunchScreen.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /RSA加密/RSA加密/Base.lproj/Main.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /RSA加密/RSA加密/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | APPL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | LSRequiresIPhoneOS 24 | 25 | UILaunchStoryboardName 26 | LaunchScreen 27 | UIMainStoryboardFile 28 | Main 29 | UIRequiredDeviceCapabilities 30 | 31 | armv7 32 | 33 | UISupportedInterfaceOrientations 34 | 35 | UIInterfaceOrientationPortrait 36 | UIInterfaceOrientationLandscapeLeft 37 | UIInterfaceOrientationLandscapeRight 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /RSA加密/RSA加密/ViewController.h: -------------------------------------------------------------------------------- 1 | // 2 | // ViewController.h 3 | // RSA加密 4 | // 5 | // Created by XHTeng on 16/5/3. 6 | // Copyright © 2016年 XHTeng. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface ViewController : UIViewController 12 | 13 | 14 | @end 15 | 16 | -------------------------------------------------------------------------------- /RSA加密/RSA加密/ViewController.m: -------------------------------------------------------------------------------- 1 | // 2 | // ViewController.m 3 | // RSA加密 4 | // 5 | // Created by XHTeng on 16/5/3. 6 | // Copyright © 2016年 XHTeng. All rights reserved. 7 | // 8 | 9 | #import "ViewController.h" 10 | #import 11 | #import "XHCryptorTools.h" 12 | @interface ViewController () 13 | 14 | @end 15 | 16 | @implementation ViewController 17 | 18 | - (void)viewDidLoad { 19 | [super viewDidLoad]; 20 | // Do any additional setup after loading the view, typically from a nib. 21 | } 22 | -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 23 | { 24 | XHCryptorTools *tools = [[XHCryptorTools alloc] init]; 25 | //1加载公钥 26 | NSString *pubPath = [[NSBundle mainBundle] pathForResource:@"rsacert.der" ofType:nil]; 27 | [tools loadPublicKeyWithFilePath:pubPath]; 28 | //2:使用公钥加密 29 | NSString *result = [tools RSAEncryptString:@"123456jkkkhhh"]; 30 | NSLog(@"加密之后的结果是:%@",result); 31 | //3:加载私钥,并且指定导出p12时设定的密码 32 | NSString *privatePath = [[NSBundle mainBundle] pathForResource:@"p.p12" ofType:nil]; 33 | [tools loadPrivateKey:privatePath password:@"123456"]; 34 | // 4. 使用私钥解密 35 | NSLog(@"解密结果 %@", [tools RSADecryptString:result]); 36 | 37 | } 38 | 39 | - (void)didReceiveMemoryWarning { 40 | [super didReceiveMemoryWarning]; 41 | // Dispose of any resources that can be recreated. 42 | } 43 | 44 | @end 45 | -------------------------------------------------------------------------------- /RSA加密/RSA加密/XHCryptorTools.h: -------------------------------------------------------------------------------- 1 | // 2 | // XHCryptorTools.h 3 | // 加密/解密工具 4 | // 5 | // Created by XHTeng on 15/4/26. 6 | // Copyright (c) 2015年 XHTeng. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | /// 加密工具类 12 | /// 提供RSA & AES & DES加密方法 13 | @interface XHCryptorTools : NSObject 14 | 15 | #pragma mark - DES 加密/解密 16 | /// DES 加密 17 | /// 18 | /// @param data 要加密的二进制数据 19 | /// @param keyString 加密密钥 20 | /// @param iv IV向量 21 | /// 22 | /// @return 加密后的二进制数据 23 | + (NSData *)DESEncryptData:(NSData *)data keyString:(NSString *)keyString iv:(NSData *)iv; 24 | 25 | /// DES 加密字符串 26 | /// 27 | /// @param string 要加密的字符串 28 | /// @param keyString 加密密钥 29 | /// @param iv IV向量 30 | /// 31 | /// @return 加密后的 BASE64 编码字符串 32 | + (NSString *)DESEncryptString:(NSString *)string keyString:(NSString *)keyString iv:(NSData *)iv; 33 | 34 | /// DES 解密 35 | /// 36 | /// @param data 要解密的二进制数据 37 | /// @param keyString 解密密钥 38 | /// @param iv IV向量 39 | /// 40 | /// @return 解密后的二进制数据 41 | + (NSData *)DESDecryptData:(NSData *)data keyString:(NSString *)keyString iv:(NSData *)iv; 42 | 43 | /// DES 解密 44 | /// 45 | /// @param string 要解密的 BASE64 编码字符串 46 | /// @param keyString 解密密钥 47 | /// @param iv IV向量 48 | /// 49 | /// @return 解密后的二进制数据 50 | + (NSString *)DESDecryptString:(NSString *)string keyString:(NSString *)keyString iv:(NSData *)iv; 51 | 52 | #pragma mark - AES 加密/解密 53 | /// AES 加密 54 | /// 55 | /// @param data 要加密的二进制数据 56 | /// @param keyString 加密密钥 57 | /// @param iv IV向量 58 | /// 59 | /// @return 加密后的二进制数据 60 | + (NSData *)AESEncryptData:(NSData *)data keyString:(NSString *)keyString iv:(NSData *)iv; 61 | 62 | /// AES 加密字符串 63 | /// 64 | /// @param string 要加密的字符串 65 | /// @param keyString 加密密钥 66 | /// @param iv IV向量 67 | /// 68 | /// @return 加密后的 BASE64 编码字符串 69 | + (NSString *)AESEncryptString:(NSString *)string keyString:(NSString *)keyString iv:(NSData *)iv; 70 | 71 | /// AES 解密 72 | /// 73 | /// @param data 要解密的二进制数据 74 | /// @param keyString 解密密钥 75 | /// @param iv IV向量 76 | /// 77 | /// @return 解密后的二进制数据 78 | + (NSData *)AESDecryptData:(NSData *)data keyString:(NSString *)keyString iv:(NSData *)iv; 79 | 80 | /// AES 解密 81 | /// 82 | /// @param string 要解密的 BASE64 编码字符串 83 | /// @param keyString 解密密钥 84 | /// @param iv IV向量 85 | /// 86 | /// @return 解密后的二进制数据 87 | + (NSString *)AESDecryptString:(NSString *)string keyString:(NSString *)keyString iv:(NSData *)iv; 88 | 89 | #pragma mark - RSA 加密/解密算法 90 | /// 加载公钥 91 | /// 92 | /// @param filePath DER 公钥文件路径 93 | - (void)loadPublicKeyWithFilePath:(NSString *)filePath; 94 | 95 | /// 加载私钥 96 | /// 97 | /// @param filePath P12 私钥文件路径 98 | /// @param password P12 密码 99 | - (void)loadPrivateKey:(NSString *)filePath password:(NSString *)password; 100 | 101 | /// RSA 加密数据 102 | /// 103 | /// @param data 要加密的数据 104 | /// 105 | /// @return 加密后的二进制数据 106 | - (NSData *)RSAEncryptData:(NSData *)data; 107 | 108 | /// RSA 加密字符串 109 | /// 110 | /// @param string 要加密的字符串 111 | /// 112 | /// @return 加密后的 BASE64 编码字符串 113 | - (NSString *)RSAEncryptString:(NSString *)string; 114 | 115 | /// RSA 解密数据 116 | /// 117 | /// @param data 要解密的数据 118 | /// 119 | /// @return 解密后的二进制数据 120 | - (NSData *)RSADecryptData:(NSData *)data; 121 | 122 | /// RSA 解密字符串 123 | /// 124 | /// @param string 要解密的 BASE64 编码字符串 125 | /// 126 | /// @return 解密后的字符串 127 | - (NSString *)RSADecryptString:(NSString *)string; 128 | 129 | @end 130 | -------------------------------------------------------------------------------- /RSA加密/RSA加密/XHCryptorTools.m: -------------------------------------------------------------------------------- 1 | // 2 | // XHCryptorTools.m 3 | // 加密/解密工具 4 | // 5 | // Created by XHTeng on 15/4/26. 6 | // Copyright (c) 2015年 XHTeng. All rights reserved. 7 | // 8 | 9 | #import "XHCryptorTools.h" 10 | #import 11 | 12 | // 填充模式 13 | #define kTypeOfWrapPadding kSecPaddingPKCS1 14 | 15 | @interface XHCryptorTools() { 16 | SecKeyRef _publicKeyRef; // 公钥引用 17 | SecKeyRef _privateKeyRef; // 私钥引用 18 | } 19 | 20 | @end 21 | 22 | @implementation XHCryptorTools 23 | 24 | #pragma mark - DES 加密/解密 25 | #pragma mark 加密 26 | + (NSData *)DESEncryptData:(NSData *)data keyString:(NSString *)keyString iv:(NSData *)iv { 27 | return [self CCCryptData:data algorithm:kCCAlgorithmDES operation:kCCEncrypt keyString:keyString iv:iv]; 28 | } 29 | 30 | + (NSString *)DESEncryptString:(NSString *)string keyString:(NSString *)keyString iv:(NSData *)iv { 31 | NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding]; 32 | NSData *result = [self DESEncryptData:data keyString:keyString iv:iv]; 33 | 34 | // BASE 64 编码 35 | return [result base64EncodedStringWithOptions:0]; 36 | } 37 | 38 | #pragma mark 解密 39 | + (NSData *)DESDecryptData:(NSData *)data keyString:(NSString *)keyString iv:(NSData *)iv { 40 | return [self CCCryptData:data algorithm:kCCAlgorithmDES operation:kCCDecrypt keyString:keyString iv:iv]; 41 | } 42 | 43 | + (NSString *)DESDecryptString:(NSString *)string keyString:(NSString *)keyString iv:(NSData *)iv { 44 | // BASE 64 解码 45 | NSData *data = [[NSData alloc] initWithBase64EncodedString:string options:0]; 46 | NSData *result = [self DESDecryptData:data keyString:keyString iv:iv]; 47 | 48 | return [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding]; 49 | } 50 | 51 | #pragma mark - AES 加密/解密 52 | #pragma mark 加密 53 | + (NSData *)AESEncryptData:(NSData *)data keyString:(NSString *)keyString iv:(NSData *)iv { 54 | return [self CCCryptData:data algorithm:kCCAlgorithmAES operation:kCCEncrypt keyString:keyString iv:iv]; 55 | } 56 | 57 | + (NSString *)AESEncryptString:(NSString *)string keyString:(NSString *)keyString iv:(NSData *)iv { 58 | NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding]; 59 | NSData *result = [self AESEncryptData:data keyString:keyString iv:iv]; 60 | 61 | // BASE 64 编码 62 | return [result base64EncodedStringWithOptions:0]; 63 | } 64 | 65 | #pragma mark 解密 66 | + (NSData *)AESDecryptData:(NSData *)data keyString:(NSString *)keyString iv:(NSData *)iv { 67 | return [self CCCryptData:data algorithm:kCCAlgorithmAES operation:kCCDecrypt keyString:keyString iv:iv]; 68 | } 69 | 70 | + (NSString *)AESDecryptString:(NSString *)string keyString:(NSString *)keyString iv:(NSData *)iv { 71 | // BASE 64 解码 72 | NSData *data = [[NSData alloc] initWithBase64EncodedString:string options:0]; 73 | NSData *result = [self AESDecryptData:data keyString:keyString iv:iv]; 74 | 75 | return [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding]; 76 | } 77 | 78 | #pragma mark 对称加密&解密核心方法 79 | /// 对称加密&解密核心方法 80 | /// 81 | /// @param data 加密/解密的二进制数据 82 | /// @param algorithm 加密算法 83 | /// @param operation 加密/解密操作 84 | /// @param keyString 密钥字符串 85 | /// @param iv IV 向量 86 | /// 87 | /// @return 加密/解密结果 88 | + (NSData *)CCCryptData:(NSData *)data algorithm:(CCAlgorithm)algorithm operation:(CCOperation)operation keyString:(NSString *)keyString iv:(NSData *)iv { 89 | 90 | int keySize = (algorithm == kCCAlgorithmAES) ? kCCKeySizeAES128 : kCCKeySizeDES; 91 | int blockSize = (algorithm == kCCAlgorithmAES) ? kCCBlockSizeAES128: kCCBlockSizeDES; 92 | 93 | // 设置密钥 94 | NSData *keyData = [keyString dataUsingEncoding:NSUTF8StringEncoding]; 95 | uint8_t cKey[keySize]; 96 | bzero(cKey, sizeof(cKey)); 97 | [keyData getBytes:cKey length:keySize]; 98 | 99 | // 设置 IV 向量 100 | uint8_t cIv[blockSize]; 101 | bzero(cIv, blockSize); 102 | int option = kCCOptionPKCS7Padding | kCCOptionECBMode; 103 | if (iv) { 104 | [iv getBytes:cIv length:blockSize]; 105 | option = kCCOptionPKCS7Padding; 106 | } 107 | 108 | // 设置输出缓冲区 109 | size_t bufferSize = [data length] + blockSize; 110 | void *buffer = malloc(bufferSize); 111 | 112 | // 加密或解密 113 | size_t cryptorSize = 0; 114 | CCCryptorStatus cryptStatus = CCCrypt(operation, 115 | algorithm, 116 | option, 117 | cKey, 118 | keySize, 119 | cIv, 120 | [data bytes], 121 | [data length], 122 | buffer, 123 | bufferSize, 124 | &cryptorSize); 125 | 126 | NSData *result = nil; 127 | if (cryptStatus == kCCSuccess) { 128 | result = [NSData dataWithBytesNoCopy:buffer length:cryptorSize]; 129 | } else { 130 | free(buffer); 131 | NSLog(@"[错误] 加密或解密失败 | 状态编码: %d", cryptStatus); 132 | } 133 | 134 | return result; 135 | } 136 | 137 | #pragma mark - RSA 加密/解密算法 138 | - (void)loadPublicKeyWithFilePath:(NSString *)filePath; { 139 | 140 | NSAssert(filePath.length != 0, @"公钥路径为空"); 141 | 142 | // 删除当前公钥 143 | if (_publicKeyRef) CFRelease(_publicKeyRef); 144 | 145 | // 从一个 DER 表示的证书创建一个证书对象 146 | NSData *certificateData = [NSData dataWithContentsOfFile:filePath]; 147 | SecCertificateRef certificateRef = SecCertificateCreateWithData(kCFAllocatorDefault, (__bridge CFDataRef)certificateData); 148 | NSAssert(certificateRef != NULL, @"公钥文件错误"); 149 | 150 | // 返回一个默认 X509 策略的公钥对象,使用之后需要调用 CFRelease 释放 151 | SecPolicyRef policyRef = SecPolicyCreateBasicX509(); 152 | // 包含信任管理信息的结构体 153 | SecTrustRef trustRef; 154 | 155 | // 基于证书和策略创建一个信任管理对象 156 | OSStatus status = SecTrustCreateWithCertificates(certificateRef, policyRef, &trustRef); 157 | NSAssert(status == errSecSuccess, @"创建信任管理对象失败"); 158 | 159 | // 信任结果 160 | SecTrustResultType trustResult; 161 | // 评估指定证书和策略的信任管理是否有效 162 | status = SecTrustEvaluate(trustRef, &trustResult); 163 | NSAssert(status == errSecSuccess, @"信任评估失败"); 164 | 165 | // 评估之后返回公钥子证书 166 | _publicKeyRef = SecTrustCopyPublicKey(trustRef); 167 | NSAssert(_publicKeyRef != NULL, @"公钥创建失败"); 168 | 169 | if (certificateRef) CFRelease(certificateRef); 170 | if (policyRef) CFRelease(policyRef); 171 | if (trustRef) CFRelease(trustRef); 172 | } 173 | 174 | - (void)loadPrivateKey:(NSString *)filePath password:(NSString *)password { 175 | 176 | NSAssert(filePath.length != 0, @"私钥路径为空"); 177 | 178 | // 删除当前私钥 179 | if (_privateKeyRef) CFRelease(_privateKeyRef); 180 | 181 | NSData *PKCS12Data = [NSData dataWithContentsOfFile:filePath]; 182 | CFDataRef inPKCS12Data = (__bridge CFDataRef)PKCS12Data; 183 | CFStringRef passwordRef = (__bridge CFStringRef)password; 184 | 185 | // 从 PKCS #12 证书中提取标示和证书 186 | SecIdentityRef myIdentity; 187 | SecTrustRef myTrust; 188 | const void *keys[] = {kSecImportExportPassphrase}; 189 | const void *values[] = {passwordRef}; 190 | CFDictionaryRef optionsDictionary = CFDictionaryCreate(NULL, keys, values, 1, NULL, NULL); 191 | CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL); 192 | 193 | // 返回 PKCS #12 格式数据中的标示和证书 194 | OSStatus status = SecPKCS12Import(inPKCS12Data, optionsDictionary, &items); 195 | 196 | if (status == noErr) { 197 | CFDictionaryRef myIdentityAndTrust = CFArrayGetValueAtIndex(items, 0); 198 | myIdentity = (SecIdentityRef)CFDictionaryGetValue(myIdentityAndTrust, kSecImportItemIdentity); 199 | myTrust = (SecTrustRef)CFDictionaryGetValue(myIdentityAndTrust, kSecImportItemTrust); 200 | } 201 | 202 | if (optionsDictionary) CFRelease(optionsDictionary); 203 | 204 | NSAssert(status == noErr, @"提取身份和信任失败"); 205 | 206 | SecTrustResultType trustResult; 207 | // 评估指定证书和策略的信任管理是否有效 208 | status = SecTrustEvaluate(myTrust, &trustResult); 209 | NSAssert(status == errSecSuccess, @"信任评估失败"); 210 | 211 | // 提取私钥 212 | status = SecIdentityCopyPrivateKey(myIdentity, &_privateKeyRef); 213 | NSAssert(status == errSecSuccess, @"私钥创建失败"); 214 | CFRelease(items); 215 | } 216 | 217 | - (NSString *)RSAEncryptString:(NSString *)string { 218 | NSData *cipher = [self RSAEncryptData:[string dataUsingEncoding:NSUTF8StringEncoding]]; 219 | 220 | return [cipher base64EncodedStringWithOptions:0]; 221 | } 222 | 223 | - (NSData *)RSAEncryptData:(NSData *)data { 224 | OSStatus sanityCheck = noErr; 225 | size_t cipherBufferSize = 0; 226 | size_t keyBufferSize = 0; 227 | 228 | NSAssert(data, @"明文数据为空"); 229 | NSAssert(_publicKeyRef, @"公钥为空"); 230 | 231 | NSData *cipher = nil; 232 | uint8_t *cipherBuffer = NULL; 233 | 234 | // 计算缓冲区大小 235 | cipherBufferSize = SecKeyGetBlockSize(_publicKeyRef); 236 | keyBufferSize = data.length; 237 | 238 | if (kTypeOfWrapPadding == kSecPaddingNone) { 239 | NSAssert(keyBufferSize <= cipherBufferSize, @"加密内容太大"); 240 | } else { 241 | NSAssert(keyBufferSize <= (cipherBufferSize - 11), @"加密内容太大"); 242 | } 243 | 244 | // 分配缓冲区 245 | cipherBuffer = malloc(cipherBufferSize * sizeof(uint8_t)); 246 | memset((void *)cipherBuffer, 0x0, cipherBufferSize); 247 | 248 | // 使用公钥加密 249 | sanityCheck = SecKeyEncrypt(_publicKeyRef, 250 | kTypeOfWrapPadding, 251 | (const uint8_t *)data.bytes, 252 | keyBufferSize, 253 | cipherBuffer, 254 | &cipherBufferSize 255 | ); 256 | 257 | NSAssert(sanityCheck == noErr, @"加密错误,OSStatus == %d", sanityCheck); 258 | 259 | // 生成密文数据 260 | cipher = [NSData dataWithBytes:(const void *)cipherBuffer length:(NSUInteger)cipherBufferSize]; 261 | 262 | if (cipherBuffer) free(cipherBuffer); 263 | 264 | return cipher; 265 | } 266 | 267 | - (NSString *)RSADecryptString:(NSString *)string { 268 | NSData *keyData = [self RSADecryptData:[[NSData alloc] initWithBase64EncodedString:string options:0]]; 269 | 270 | return [[NSString alloc] initWithData:keyData encoding:NSUTF8StringEncoding]; 271 | } 272 | 273 | - (NSData *)RSADecryptData:(NSData *)data { 274 | OSStatus sanityCheck = noErr; 275 | size_t cipherBufferSize = 0; 276 | size_t keyBufferSize = 0; 277 | 278 | NSData *key = nil; 279 | uint8_t *keyBuffer = NULL; 280 | 281 | SecKeyRef privateKey = _privateKeyRef; 282 | NSAssert(privateKey != NULL, @"私钥不存在"); 283 | 284 | // 计算缓冲区大小 285 | cipherBufferSize = SecKeyGetBlockSize(privateKey); 286 | keyBufferSize = data.length; 287 | 288 | NSAssert(keyBufferSize <= cipherBufferSize, @"解密内容太大"); 289 | 290 | // 分配缓冲区 291 | keyBuffer = malloc(keyBufferSize * sizeof(uint8_t)); 292 | memset((void *)keyBuffer, 0x0, keyBufferSize); 293 | 294 | // 使用私钥解密 295 | sanityCheck = SecKeyDecrypt(privateKey, 296 | kTypeOfWrapPadding, 297 | (const uint8_t *)data.bytes, 298 | cipherBufferSize, 299 | keyBuffer, 300 | &keyBufferSize 301 | ); 302 | 303 | NSAssert1(sanityCheck == noErr, @"解密错误,OSStatus == %d", sanityCheck); 304 | 305 | // 生成明文数据 306 | key = [NSData dataWithBytes:(const void *)keyBuffer length:(NSUInteger)keyBufferSize]; 307 | 308 | if (keyBuffer) free(keyBuffer); 309 | 310 | return key; 311 | } 312 | 313 | @end 314 | -------------------------------------------------------------------------------- /RSA加密/RSA加密/main.m: -------------------------------------------------------------------------------- 1 | // 2 | // main.m 3 | // RSA加密 4 | // 5 | // Created by XHTeng on 16/5/3. 6 | // Copyright © 2016年 XHTeng. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "AppDelegate.h" 11 | 12 | int main(int argc, char * argv[]) { 13 | @autoreleasepool { 14 | return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /RSA加密/RSA加密/p.p12: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XHTeng/XHCryptorTools/3f49fe92d069095aa0ceca85365b79e799693bd0/RSA加密/RSA加密/p.p12 -------------------------------------------------------------------------------- /RSA加密/RSA加密/private.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN RSA PRIVATE KEY----- 2 | MIIBOgIBAAJBAJtHBOE1ugAon5uN6pRs3vlV4RBRNMpAFuHdhHJU/Bn1ttFHnKsw 3 | 52ohhI5oJGpiyYe6ZUXBmB0Z5FRibnmDkLkCAwEAAQJAdesL6J8tXjt7Ydz3HLpE 4 | 5iJypTqWFVVwSxw3HcAuJuOEjf0bPWMCGJUuTOlufzyZNXaKh/dS+2nxj4WmlhZM 5 | EQIhAMtkR5yZzHDxN3ssVsJIVMUpALakgVjvVAcKZT5slEG1AiEAw3DRg9AI1Evz 6 | fdJt/qTgKHqbFkogat27LlJM3TI1BXUCICi2E9d2uYNJ5S8UevE8hStJv8jPOMzS 7 | auFV5VoPZcWZAiAAv57dzV8rSPsuwS6Qqhr9rLKJXFFRd3XvEHug4T9YvQIhAKga 8 | r/ctnsF7H9CzZ9CLfxeNBPFWvlijlbbpe9Fwb8Hc 9 | -----END RSA PRIVATE KEY----- 10 | -------------------------------------------------------------------------------- /RSA加密/RSA加密/rsacert.crt: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIB6DCCAZICCQCUPeUfjeo4TjANBgkqhkiG9w0BAQUFADB7MQswCQYDVQQGEwJD 3 | TjEQMA4GA1UECBMHYmVpamluZzEQMA4GA1UEBxMHYmVpamluZzEQMA4GA1UEChMH 4 | aXRoZWltYTENMAsGA1UECxMELmNvbTEMMAoGA1UEAxMDemZ0MRkwFwYJKoZIhvcN 5 | AQkBFgp6ZnRAcXEuY29tMB4XDTE2MDUwMzA1NTQ0OFoXDTI2MDUwMTA1NTQ0OFow 6 | ezELMAkGA1UEBhMCQ04xEDAOBgNVBAgTB2JlaWppbmcxEDAOBgNVBAcTB2JlaWpp 7 | bmcxEDAOBgNVBAoTB2l0aGVpbWExDTALBgNVBAsTBC5jb20xDDAKBgNVBAMTA3pm 8 | dDEZMBcGCSqGSIb3DQEJARYKemZ0QHFxLmNvbTBcMA0GCSqGSIb3DQEBAQUAA0sA 9 | MEgCQQCbRwThNboAKJ+bjeqUbN75VeEQUTTKQBbh3YRyVPwZ9bbRR5yrMOdqIYSO 10 | aCRqYsmHumVFwZgdGeRUYm55g5C5AgMBAAEwDQYJKoZIhvcNAQEFBQADQQBZJdvI 11 | qsgPDARW97ACTqhz5b/+2hDJQStLeHwvj8b+LIH/G94YtstBQncYKzwKsSjQymP6 12 | mHrKuIawmL/ZIr7y 13 | -----END CERTIFICATE----- 14 | -------------------------------------------------------------------------------- /RSA加密/RSA加密/rsacert.csr: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE REQUEST----- 2 | MIIBZDCCAQ4CAQAwezELMAkGA1UEBhMCQ04xEDAOBgNVBAgTB2JlaWppbmcxEDAO 3 | BgNVBAcTB2JlaWppbmcxEDAOBgNVBAoTB2l0aGVpbWExDTALBgNVBAsTBC5jb20x 4 | DDAKBgNVBAMTA3pmdDEZMBcGCSqGSIb3DQEJARYKemZ0QHFxLmNvbTBcMA0GCSqG 5 | SIb3DQEBAQUAA0sAMEgCQQCbRwThNboAKJ+bjeqUbN75VeEQUTTKQBbh3YRyVPwZ 6 | 9bbRR5yrMOdqIYSOaCRqYsmHumVFwZgdGeRUYm55g5C5AgMBAAGgLjAVBgkqhkiG 7 | 9w0BCQIxCBMGMTIzNDU2MBUGCSqGSIb3DQEJBzEIEwYxMjM0NTYwDQYJKoZIhvcN 8 | AQEFBQADQQBb5L4FL4TNJDDnMYHZZeLmJZDL/NMNVl2xjJXsfCaq7Mkfm1ugzVCi 9 | BrPA0NAbmUZO1GpjKvuFzF31LErpqOp2 10 | -----END CERTIFICATE REQUEST----- 11 | -------------------------------------------------------------------------------- /RSA加密/RSA加密/rsacert.der: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/XHTeng/XHCryptorTools/3f49fe92d069095aa0ceca85365b79e799693bd0/RSA加密/RSA加密/rsacert.der -------------------------------------------------------------------------------- /XHCryptorTools.h: -------------------------------------------------------------------------------- 1 | // 2 | // XHCryptorTools.h 3 | // 加密/解密工具 4 | // 5 | // Created by XHTeng on 15/4/26. 6 | // Copyright (c) 2015年 XHTeng. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | /// 加密工具类 12 | /// 提供RSA & AES & DES加密方法 13 | @interface XHCryptorTools : NSObject 14 | 15 | #pragma mark - DES 加密/解密 16 | /// DES 加密 17 | /// 18 | /// @param data 要加密的二进制数据 19 | /// @param keyString 加密密钥 20 | /// @param iv IV向量 21 | /// 22 | /// @return 加密后的二进制数据 23 | + (NSData *)DESEncryptData:(NSData *)data keyString:(NSString *)keyString iv:(NSData *)iv; 24 | 25 | /// DES 加密字符串 26 | /// 27 | /// @param string 要加密的字符串 28 | /// @param keyString 加密密钥 29 | /// @param iv IV向量 30 | /// 31 | /// @return 加密后的 BASE64 编码字符串 32 | + (NSString *)DESEncryptString:(NSString *)string keyString:(NSString *)keyString iv:(NSData *)iv; 33 | 34 | /// DES 解密 35 | /// 36 | /// @param data 要解密的二进制数据 37 | /// @param keyString 解密密钥 38 | /// @param iv IV向量 39 | /// 40 | /// @return 解密后的二进制数据 41 | + (NSData *)DESDecryptData:(NSData *)data keyString:(NSString *)keyString iv:(NSData *)iv; 42 | 43 | /// DES 解密 44 | /// 45 | /// @param string 要解密的 BASE64 编码字符串 46 | /// @param keyString 解密密钥 47 | /// @param iv IV向量 48 | /// 49 | /// @return 解密后的二进制数据 50 | + (NSString *)DESDecryptString:(NSString *)string keyString:(NSString *)keyString iv:(NSData *)iv; 51 | 52 | #pragma mark - AES 加密/解密 53 | /// AES 加密 54 | /// 55 | /// @param data 要加密的二进制数据 56 | /// @param keyString 加密密钥 57 | /// @param iv IV向量 58 | /// 59 | /// @return 加密后的二进制数据 60 | + (NSData *)AESEncryptData:(NSData *)data keyString:(NSString *)keyString iv:(NSData *)iv; 61 | 62 | /// AES 加密字符串 63 | /// 64 | /// @param string 要加密的字符串 65 | /// @param keyString 加密密钥 66 | /// @param iv IV向量 67 | /// 68 | /// @return 加密后的 BASE64 编码字符串 69 | + (NSString *)AESEncryptString:(NSString *)string keyString:(NSString *)keyString iv:(NSData *)iv; 70 | 71 | /// AES 解密 72 | /// 73 | /// @param data 要解密的二进制数据 74 | /// @param keyString 解密密钥 75 | /// @param iv IV向量 76 | /// 77 | /// @return 解密后的二进制数据 78 | + (NSData *)AESDecryptData:(NSData *)data keyString:(NSString *)keyString iv:(NSData *)iv; 79 | 80 | /// AES 解密 81 | /// 82 | /// @param string 要解密的 BASE64 编码字符串 83 | /// @param keyString 解密密钥 84 | /// @param iv IV向量 85 | /// 86 | /// @return 解密后的二进制数据 87 | + (NSString *)AESDecryptString:(NSString *)string keyString:(NSString *)keyString iv:(NSData *)iv; 88 | 89 | #pragma mark - RSA 加密/解密算法 90 | /// 加载公钥 91 | /// 92 | /// @param filePath DER 公钥文件路径 93 | - (void)loadPublicKeyWithFilePath:(NSString *)filePath; 94 | 95 | /// 加载私钥 96 | /// 97 | /// @param filePath P12 私钥文件路径 98 | /// @param password P12 密码 99 | - (void)loadPrivateKey:(NSString *)filePath password:(NSString *)password; 100 | 101 | /// RSA 加密数据 102 | /// 103 | /// @param data 要加密的数据 104 | /// 105 | /// @return 加密后的二进制数据 106 | - (NSData *)RSAEncryptData:(NSData *)data; 107 | 108 | /// RSA 加密字符串 109 | /// 110 | /// @param string 要加密的字符串 111 | /// 112 | /// @return 加密后的 BASE64 编码字符串 113 | - (NSString *)RSAEncryptString:(NSString *)string; 114 | 115 | /// RSA 解密数据 116 | /// 117 | /// @param data 要解密的数据 118 | /// 119 | /// @return 解密后的二进制数据 120 | - (NSData *)RSADecryptData:(NSData *)data; 121 | 122 | /// RSA 解密字符串 123 | /// 124 | /// @param string 要解密的 BASE64 编码字符串 125 | /// 126 | /// @return 解密后的字符串 127 | - (NSString *)RSADecryptString:(NSString *)string; 128 | 129 | @end 130 | -------------------------------------------------------------------------------- /XHCryptorTools.m: -------------------------------------------------------------------------------- 1 | // 2 | // XHCryptorTools.m 3 | // 加密/解密工具 4 | // 5 | // Created by XHTeng on 15/4/26. 6 | // Copyright (c) 2015年 XHTeng. All rights reserved. 7 | // 8 | 9 | #import "XHCryptorTools.h" 10 | #import 11 | 12 | // 填充模式 13 | #define kTypeOfWrapPadding kSecPaddingPKCS1 14 | 15 | @interface XHCryptorTools() { 16 | SecKeyRef _publicKeyRef; // 公钥引用 17 | SecKeyRef _privateKeyRef; // 私钥引用 18 | } 19 | 20 | @end 21 | 22 | @implementation XHCryptorTools 23 | 24 | #pragma mark - DES 加密/解密 25 | #pragma mark 加密 26 | + (NSData *)DESEncryptData:(NSData *)data keyString:(NSString *)keyString iv:(NSData *)iv { 27 | return [self CCCryptData:data algorithm:kCCAlgorithmDES operation:kCCEncrypt keyString:keyString iv:iv]; 28 | } 29 | 30 | + (NSString *)DESEncryptString:(NSString *)string keyString:(NSString *)keyString iv:(NSData *)iv { 31 | NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding]; 32 | NSData *result = [self DESEncryptData:data keyString:keyString iv:iv]; 33 | 34 | // BASE 64 编码 35 | return [result base64EncodedStringWithOptions:0]; 36 | } 37 | 38 | #pragma mark 解密 39 | + (NSData *)DESDecryptData:(NSData *)data keyString:(NSString *)keyString iv:(NSData *)iv { 40 | return [self CCCryptData:data algorithm:kCCAlgorithmDES operation:kCCDecrypt keyString:keyString iv:iv]; 41 | } 42 | 43 | + (NSString *)DESDecryptString:(NSString *)string keyString:(NSString *)keyString iv:(NSData *)iv { 44 | // BASE 64 解码 45 | NSData *data = [[NSData alloc] initWithBase64EncodedString:string options:0]; 46 | NSData *result = [self DESDecryptData:data keyString:keyString iv:iv]; 47 | 48 | return [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding]; 49 | } 50 | 51 | #pragma mark - AES 加密/解密 52 | #pragma mark 加密 53 | + (NSData *)AESEncryptData:(NSData *)data keyString:(NSString *)keyString iv:(NSData *)iv { 54 | return [self CCCryptData:data algorithm:kCCAlgorithmAES operation:kCCEncrypt keyString:keyString iv:iv]; 55 | } 56 | 57 | + (NSString *)AESEncryptString:(NSString *)string keyString:(NSString *)keyString iv:(NSData *)iv { 58 | NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding]; 59 | NSData *result = [self AESEncryptData:data keyString:keyString iv:iv]; 60 | 61 | // BASE 64 编码 62 | return [result base64EncodedStringWithOptions:0]; 63 | } 64 | 65 | #pragma mark 解密 66 | + (NSData *)AESDecryptData:(NSData *)data keyString:(NSString *)keyString iv:(NSData *)iv { 67 | return [self CCCryptData:data algorithm:kCCAlgorithmAES operation:kCCDecrypt keyString:keyString iv:iv]; 68 | } 69 | 70 | + (NSString *)AESDecryptString:(NSString *)string keyString:(NSString *)keyString iv:(NSData *)iv { 71 | // BASE 64 解码 72 | NSData *data = [[NSData alloc] initWithBase64EncodedString:string options:0]; 73 | NSData *result = [self AESDecryptData:data keyString:keyString iv:iv]; 74 | 75 | return [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding]; 76 | } 77 | 78 | #pragma mark 对称加密&解密核心方法 79 | /// 对称加密&解密核心方法 80 | /// 81 | /// @param data 加密/解密的二进制数据 82 | /// @param algorithm 加密算法 83 | /// @param operation 加密/解密操作 84 | /// @param keyString 密钥字符串 85 | /// @param iv IV 向量 86 | /// 87 | /// @return 加密/解密结果 88 | + (NSData *)CCCryptData:(NSData *)data algorithm:(CCAlgorithm)algorithm operation:(CCOperation)operation keyString:(NSString *)keyString iv:(NSData *)iv { 89 | 90 | int keySize = (algorithm == kCCAlgorithmAES) ? kCCKeySizeAES128 : kCCKeySizeDES; 91 | int blockSize = (algorithm == kCCAlgorithmAES) ? kCCBlockSizeAES128: kCCBlockSizeDES; 92 | 93 | // 设置密钥 94 | NSData *keyData = [keyString dataUsingEncoding:NSUTF8StringEncoding]; 95 | uint8_t cKey[keySize]; 96 | bzero(cKey, sizeof(cKey)); 97 | [keyData getBytes:cKey length:keySize]; 98 | 99 | // 设置 IV 向量 100 | uint8_t cIv[blockSize]; 101 | bzero(cIv, blockSize); 102 | int option = kCCOptionPKCS7Padding | kCCOptionECBMode; 103 | if (iv) { 104 | [iv getBytes:cIv length:blockSize]; 105 | option = kCCOptionPKCS7Padding; 106 | } 107 | 108 | // 设置输出缓冲区 109 | size_t bufferSize = [data length] + blockSize; 110 | void *buffer = malloc(bufferSize); 111 | 112 | // 加密或解密 113 | size_t cryptorSize = 0; 114 | CCCryptorStatus cryptStatus = CCCrypt(operation, 115 | algorithm, 116 | option, 117 | cKey, 118 | keySize, 119 | cIv, 120 | [data bytes], 121 | [data length], 122 | buffer, 123 | bufferSize, 124 | &cryptorSize); 125 | 126 | NSData *result = nil; 127 | if (cryptStatus == kCCSuccess) { 128 | result = [NSData dataWithBytesNoCopy:buffer length:cryptorSize]; 129 | } else { 130 | free(buffer); 131 | NSLog(@"[错误] 加密或解密失败 | 状态编码: %d", cryptStatus); 132 | } 133 | 134 | return result; 135 | } 136 | 137 | #pragma mark - RSA 加密/解密算法 138 | - (void)loadPublicKeyWithFilePath:(NSString *)filePath; { 139 | 140 | NSAssert(filePath.length != 0, @"公钥路径为空"); 141 | 142 | // 删除当前公钥 143 | if (_publicKeyRef) CFRelease(_publicKeyRef); 144 | 145 | // 从一个 DER 表示的证书创建一个证书对象 146 | NSData *certificateData = [NSData dataWithContentsOfFile:filePath]; 147 | SecCertificateRef certificateRef = SecCertificateCreateWithData(kCFAllocatorDefault, (__bridge CFDataRef)certificateData); 148 | NSAssert(certificateRef != NULL, @"公钥文件错误"); 149 | 150 | // 返回一个默认 X509 策略的公钥对象,使用之后需要调用 CFRelease 释放 151 | SecPolicyRef policyRef = SecPolicyCreateBasicX509(); 152 | // 包含信任管理信息的结构体 153 | SecTrustRef trustRef; 154 | 155 | // 基于证书和策略创建一个信任管理对象 156 | OSStatus status = SecTrustCreateWithCertificates(certificateRef, policyRef, &trustRef); 157 | NSAssert(status == errSecSuccess, @"创建信任管理对象失败"); 158 | 159 | // 信任结果 160 | SecTrustResultType trustResult; 161 | // 评估指定证书和策略的信任管理是否有效 162 | status = SecTrustEvaluate(trustRef, &trustResult); 163 | NSAssert(status == errSecSuccess, @"信任评估失败"); 164 | 165 | // 评估之后返回公钥子证书 166 | _publicKeyRef = SecTrustCopyPublicKey(trustRef); 167 | NSAssert(_publicKeyRef != NULL, @"公钥创建失败"); 168 | 169 | if (certificateRef) CFRelease(certificateRef); 170 | if (policyRef) CFRelease(policyRef); 171 | if (trustRef) CFRelease(trustRef); 172 | } 173 | 174 | - (void)loadPrivateKey:(NSString *)filePath password:(NSString *)password { 175 | 176 | NSAssert(filePath.length != 0, @"私钥路径为空"); 177 | 178 | // 删除当前私钥 179 | if (_privateKeyRef) CFRelease(_privateKeyRef); 180 | 181 | NSData *PKCS12Data = [NSData dataWithContentsOfFile:filePath]; 182 | CFDataRef inPKCS12Data = (__bridge CFDataRef)PKCS12Data; 183 | CFStringRef passwordRef = (__bridge CFStringRef)password; 184 | 185 | // 从 PKCS #12 证书中提取标示和证书 186 | SecIdentityRef myIdentity; 187 | SecTrustRef myTrust; 188 | const void *keys[] = {kSecImportExportPassphrase}; 189 | const void *values[] = {passwordRef}; 190 | CFDictionaryRef optionsDictionary = CFDictionaryCreate(NULL, keys, values, 1, NULL, NULL); 191 | CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL); 192 | 193 | // 返回 PKCS #12 格式数据中的标示和证书 194 | OSStatus status = SecPKCS12Import(inPKCS12Data, optionsDictionary, &items); 195 | 196 | if (status == noErr) { 197 | CFDictionaryRef myIdentityAndTrust = CFArrayGetValueAtIndex(items, 0); 198 | myIdentity = (SecIdentityRef)CFDictionaryGetValue(myIdentityAndTrust, kSecImportItemIdentity); 199 | myTrust = (SecTrustRef)CFDictionaryGetValue(myIdentityAndTrust, kSecImportItemTrust); 200 | } 201 | 202 | if (optionsDictionary) CFRelease(optionsDictionary); 203 | 204 | NSAssert(status == noErr, @"提取身份和信任失败"); 205 | 206 | SecTrustResultType trustResult; 207 | // 评估指定证书和策略的信任管理是否有效 208 | status = SecTrustEvaluate(myTrust, &trustResult); 209 | NSAssert(status == errSecSuccess, @"信任评估失败"); 210 | 211 | // 提取私钥 212 | status = SecIdentityCopyPrivateKey(myIdentity, &_privateKeyRef); 213 | NSAssert(status == errSecSuccess, @"私钥创建失败"); 214 | CFRelease(items); 215 | } 216 | 217 | - (NSString *)RSAEncryptString:(NSString *)string { 218 | NSData *cipher = [self RSAEncryptData:[string dataUsingEncoding:NSUTF8StringEncoding]]; 219 | 220 | return [cipher base64EncodedStringWithOptions:0]; 221 | } 222 | 223 | - (NSData *)RSAEncryptData:(NSData *)data { 224 | OSStatus sanityCheck = noErr; 225 | size_t cipherBufferSize = 0; 226 | size_t keyBufferSize = 0; 227 | 228 | NSAssert(data, @"明文数据为空"); 229 | NSAssert(_publicKeyRef, @"公钥为空"); 230 | 231 | NSData *cipher = nil; 232 | uint8_t *cipherBuffer = NULL; 233 | 234 | // 计算缓冲区大小 235 | cipherBufferSize = SecKeyGetBlockSize(_publicKeyRef); 236 | keyBufferSize = data.length; 237 | 238 | if (kTypeOfWrapPadding == kSecPaddingNone) { 239 | NSAssert(keyBufferSize <= cipherBufferSize, @"加密内容太大"); 240 | } else { 241 | NSAssert(keyBufferSize <= (cipherBufferSize - 11), @"加密内容太大"); 242 | } 243 | 244 | // 分配缓冲区 245 | cipherBuffer = malloc(cipherBufferSize * sizeof(uint8_t)); 246 | memset((void *)cipherBuffer, 0x0, cipherBufferSize); 247 | 248 | // 使用公钥加密 249 | sanityCheck = SecKeyEncrypt(_publicKeyRef, 250 | kTypeOfWrapPadding, 251 | (const uint8_t *)data.bytes, 252 | keyBufferSize, 253 | cipherBuffer, 254 | &cipherBufferSize 255 | ); 256 | 257 | NSAssert(sanityCheck == noErr, @"加密错误,OSStatus == %d", sanityCheck); 258 | 259 | // 生成密文数据 260 | cipher = [NSData dataWithBytes:(const void *)cipherBuffer length:(NSUInteger)cipherBufferSize]; 261 | 262 | if (cipherBuffer) free(cipherBuffer); 263 | 264 | return cipher; 265 | } 266 | 267 | - (NSString *)RSADecryptString:(NSString *)string { 268 | NSData *keyData = [self RSADecryptData:[[NSData alloc] initWithBase64EncodedString:string options:0]]; 269 | 270 | return [[NSString alloc] initWithData:keyData encoding:NSUTF8StringEncoding]; 271 | } 272 | 273 | - (NSData *)RSADecryptData:(NSData *)data { 274 | OSStatus sanityCheck = noErr; 275 | size_t cipherBufferSize = 0; 276 | size_t keyBufferSize = 0; 277 | 278 | NSData *key = nil; 279 | uint8_t *keyBuffer = NULL; 280 | 281 | SecKeyRef privateKey = _privateKeyRef; 282 | NSAssert(privateKey != NULL, @"私钥不存在"); 283 | 284 | // 计算缓冲区大小 285 | cipherBufferSize = SecKeyGetBlockSize(privateKey); 286 | keyBufferSize = data.length; 287 | 288 | NSAssert(keyBufferSize <= cipherBufferSize, @"解密内容太大"); 289 | 290 | // 分配缓冲区 291 | keyBuffer = malloc(keyBufferSize * sizeof(uint8_t)); 292 | memset((void *)keyBuffer, 0x0, keyBufferSize); 293 | 294 | // 使用私钥解密 295 | sanityCheck = SecKeyDecrypt(privateKey, 296 | kTypeOfWrapPadding, 297 | (const uint8_t *)data.bytes, 298 | cipherBufferSize, 299 | keyBuffer, 300 | &keyBufferSize 301 | ); 302 | 303 | NSAssert1(sanityCheck == noErr, @"解密错误,OSStatus == %d", sanityCheck); 304 | 305 | // 生成明文数据 306 | key = [NSData dataWithBytes:(const void *)keyBuffer length:(NSUInteger)keyBufferSize]; 307 | 308 | if (keyBuffer) free(keyBuffer); 309 | 310 | return key; 311 | } 312 | 313 | @end 314 | --------------------------------------------------------------------------------