├── .gitignore ├── CommonCrypto ├── module.map └── module.modulemap ├── LICENSE ├── README-en.md ├── README.md ├── SecrecTestPy ├── cert.crt ├── cert.csr ├── cert.der ├── cert.p12 ├── private.pem ├── public.pem └── test.py ├── SecrecySwift.podspec ├── SecrecySwift.xcodeproj ├── project.pbxproj ├── project.xcworkspace │ └── contents.xcworkspacedata ├── xcshareddata │ └── xcschemes │ │ └── SecrecySwift.xcscheme └── xcuserdata │ └── reynoldqin.xcuserdatad │ └── xcschemes │ └── xcschememanagement.plist ├── SecrecySwift ├── AES.swift ├── Digest.swift ├── HMAC.swift ├── Info.plist ├── RSA.swift ├── SecrecyExtension.swift └── SecrecySwift.h └── SecrecySwiftDemo ├── AppDelegate.swift ├── Assets.xcassets └── AppIcon.appiconset │ └── Contents.json ├── Base.lproj ├── LaunchScreen.storyboard └── Main.storyboard ├── Info.plist ├── ViewController.swift ├── cert.der └── cert.p12 /.gitignore: -------------------------------------------------------------------------------- 1 | # Xcode 2 | # 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 | *.xccheckout 14 | *.moved-aside 15 | DerivedData 16 | *.hmap 17 | *.ipa 18 | *.xcuserstate 19 | *.swp 20 | 21 | # CocoaPods 22 | # 23 | # We recommend against adding the Pods directory to your .gitignore. However 24 | # you should judge for yourself, the pros and cons are mentioned at: 25 | # http://guides.cocoapods.org/using/using-cocoapods.html#should-i-ignore-the-pods-directory-in-source-control 26 | # 27 | # Pods/ 28 | 29 | # Carthage 30 | # 31 | # Add this line if you want to avoid checking in source code from Carthage dependencies. 32 | # Carthage/Checkouts 33 | 34 | Carthage/Build 35 | -------------------------------------------------------------------------------- /CommonCrypto/module.map: -------------------------------------------------------------------------------- 1 | module CommonCrypto [system] { 2 | header "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/usr/include/CommonCrypto/CommonCrypto.h" 3 | link "CommonCrypto" 4 | export * 5 | } 6 | -------------------------------------------------------------------------------- /CommonCrypto/module.modulemap: -------------------------------------------------------------------------------- 1 | module CommonCrypto [system] { 2 | header "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/usr/include/CommonCrypto/CommonCrypto.h" 3 | link "CommonCrypto" 4 | export * 5 | } 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 adow 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /README-en.md: -------------------------------------------------------------------------------- 1 | # SecrecySwift 2 | 3 | 4 | SecrecySwift is a wrapper library for `CommonCrypto` and `Security.framework` in Swift. It provides crpyto related functions. 5 | 6 | ## Features 7 | 8 | * Digest and HMAC: `MD2`/`MD4`/`MD5`/`SHA1`/`SHA224`/`SHA384`/`SHA512`; 9 | * AES Encrypt and Decrypt: `EBC`/`CBC`; 10 | * RSA Encrypt/Decrypt and Sign/Verify with digest of `MD2`/`MD5`/`SHA1`/`SHA224`/`SHA384`; 11 | 12 | ## Installing 13 | 14 | ### Carthage 15 | 16 | Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. 17 | 18 | You can install Carthage with Homebrew using the following command: 19 | 20 | $ brew update 21 | $ brew install carthage 22 | 23 | Buid for iOS 24 | 25 | 1. Create a Cartfile that lists the frameworks you’d like to use in your project. 26 | 27 | git "https://github.com/adow/SecrecySwift.git" >= 0.3.4 28 | 29 | 2. Run `carthage update`. This will fetch dependencies into a Carthage/Checkouts folder, then build each one. 30 | 3. On your application targets’ “General” settings tab, in the “Linked Frameworks and Libraries” section, drag and drop each framework you want to use from the Carthage/Build folder on disk. 31 | 32 | ![secrecy-1](http://7vihfk.com1.z0.glb.clouddn.com/secrecy-1.png) 33 | 34 | 4. On your application targets’ “Build Phases” settings tab, click the “+” icon and choose “New Run Script Phase”. Create a Run Script with the following contents: 35 | 36 | /usr/local/bin/carthage copy-frameworks 37 | 38 | and add the paths to the frameworks you want to use under “Input Files”, e.g.: 39 | 40 | $(SRCROOT)/Carthage/Build/iOS/Secrecy.framework 41 | 42 | 43 | ![secrecy-2](http://7vihfk.com1.z0.glb.clouddn.com/secrecy-2.png) 44 | 45 | ### Manually 46 | 47 | #### Git Submodule 48 | 49 | 1. Make sure that your project is in Git repository; 50 | 2. Add `SecrecySwift` as submodule; 51 | 52 | git submodule https://github.com/adow/SecrecySwift.git 53 | 54 | 3. Drag and drop `SecrecySwift.xcodeproj` to your project; 55 | 4. On your application targets, `General` tab, `Embedded Binaries` setting, click `+` to add `Secrecy.framework`. You will find `Secrecy.framework` is also in `Build Phases` / `Link Binary with Libraries`. 56 | 57 | 58 | #### Add Source Code to your project (Compatible with iOS7) 59 | 60 | 1. Copy following files in folder `SecrecySwift` to your project: 61 | 62 | * AES.swift 63 | * Digest.swift 64 | * HMAC.swift 65 | * RSA.swift 66 | * SecrecyExtension.swift 67 | 68 | 2. Crate a folder named `CommonCrypto` in your project and put a `module.map` file: 69 | 70 | module CommonCrypto [system] { 71 | header "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/usr/include/CommonCrypto/CommonCrypto.h" 72 | link "CommonCrypto" 73 | export * 74 | } 75 | 76 | 3. On your application targets `Build Settings`, `Import Paths` setting, add `CommonCrypto`. And add `/usr/lib/system/` on `Library Search Paths` ; 77 | 4. On your applicationtargets `Build Phases` tab, `Link Binary with Linbrries` setting, add `Security.framework` and `SystemConfiguration.framework`; 78 | 79 | You should not `import Secrecy` any more. 80 | 81 | ## Usage 82 | 83 | 84 | ### Digest and HMAC 85 | 86 | Digest.swift and HMAC.swift are forked from SwiftSSL: [https://github.com/SwiftP2P/SwiftSSL](https://github.com/SwiftP2P/SwiftSSL) 87 | 88 | Following alagorithms are available. 89 | 90 | * MD2; 91 | * MD4; 92 | * MD5; 93 | * SHA1; 94 | * SHA224; 95 | * SHA256; 96 | * SHA384; 97 | * SHA512; 98 | 99 | #### Digest: 100 | 101 | 102 | Methods `digestHex/digestBase64` in `NSData` and `String` could be used to digest it to Hex or Base64 Strings. 103 | 104 | let raw = "abc123" 105 | print(raw.digestHex(DigestAlgorithm.MD5)) 106 | print(raw.digestBase64(DigestAlgorithm.MD5)) 107 | 108 | 109 | #### HMAC Signarure 110 | 111 | `signHex/signBase64` in `NSData` and `String` are signature methods to Hex and Base64 Strings. 112 | 113 | let raw = "abc123" 114 | print(raw.signHex(HMACAlgorithm.SHA1, key: "abc")) 115 | print(raw.signBase64(HMACAlgorithm.SHA1, key: "abc")) 116 | print(raw.signBase64(HMACAlgorithm.SHA1, key: "你好")) 117 | 118 | 119 | ## AES 120 | 121 | 122 | It supports modes of: 123 | 124 | * EBC; 125 | * CBC: 126 | 127 | Only PKCSPadding7 for AES is supported. Following encrypt alagorithms are supported depending on the length of KEY. 128 | 129 | * AES128: 16; 130 | * AES192: 24; 131 | * AES256: 32; 132 | 133 | ### EBC MODE 134 | 135 | * `aesEBCEncrypt`: Encrypt in EBC Mode. 136 | * `aesEBCDecryptFromHex` Decrypt in EBC Mode from a Hex String. 137 | * `aesEBCDecryptBase64` Decrypt in EBC Mode from a Base64 String. 138 | 139 | let key = "0000000000000000" 140 | let raw = "0123456789abcdef" 141 | let encrypt_1 = raw.aesEBCEncrypt(key) 142 | print(encrypt_1!.hexString) 143 | print(encrypt_1!.hexString.aesEBCDecryptFromHex(key)) 144 | print(encrypt_1!.base64String) 145 | print(encrypt_1!.base64String.aesEBCDecryptFromBase64(key)) 146 | 147 | ### CBC Mode 148 | 149 | CBC Mode can use IV, which will be filled with Zero if not specificed. 150 | 151 | * `aesCBCEncrypt` Encyrpt in CBC Mode; 152 | * `aecCBCDecryptFromHex`: Decrypt in CBC mode from a Hex String. 153 | * `aesCBCDecryptFromBase64`: Decrypt in CBC mode from a Base64 String. 154 | 155 | let iv = "0000000000000000" 156 | let encrypt = raw.aesCBCEncrypt(key,iv: iv) 157 | print(encrypt!.hexString) 158 | print(encrypt!.hexString.aesCBCDecryptFromHex(key,iv: iv)) 159 | print(encrypt!.base64String) 160 | print(encrypt!.base64String.aesCBCDecryptFromBase64(key,iv: iv)) 161 | 162 | ## RSA 163 | 164 | RSA in SecrecySwift supports file formats of `.der` for public key and `.p12` for private key. PKCS1Padding is used in RSA. 165 | 166 | Generate certificates by `OpenSSL`: 167 | 168 | # Generate RSA Private Key 169 | openssl genrsa -out private.pem 2048 170 | 171 | # Get Public Key (pem file) from private key 172 | openssl rsa -pubout -in private.pem -out public.pem 173 | 174 | # Genrate Certificate Request from private key 175 | openssl req -new -key private.pem -out cert.csr 176 | 177 | # Generate Self-Signature Certificate from private key 178 | openssl x509 -req -days 3650 -in cert.csr -signkey private.pem -out cert.crt 179 | 180 | # Convert it to DER Format (Contains Public key) 181 | openssl x509 -outform der -in cert.crt -out cert.der 182 | 183 | # Export p12 file, with a password (Contains Private key) 184 | openssl pkcs12 -export -inkey private.pem -in cert.crt -out cert.p12 185 | 186 | 187 | ### Encrypt and Decrypt 188 | 189 | Encrypt using Public Key 190 | 191 | * `public func encrypt(data:NSData) -> NSData?` 192 | 193 | Decrypt usign Private Key 194 | 195 | * `public func decrypt(data:NSData) -> NSData?` 196 | * `public func decrypt(fromHexString hexString:String) -> NSData?` 197 | * `public func decrypt(fromBase64String base64String:String) -> NSData?` 198 | 199 | let path_public = NSBundle.mainBundle().pathForResource("cert", ofType: "der")! 200 | let path_private = NSBundle.mainBundle().pathForResource("cert", ofType: "p12")! 201 | let raw = "0123456789abcdefg" 202 | let raw_data = raw.dataUsingEncoding(NSUTF8StringEncoding)! 203 | let rsa = RSA(filenameOfPulbicKey: path_public, filenameOfPrivateKey: path_private) 204 | guard let _rsa = rsa else { 205 | return 206 | } 207 | let encrypt_data = _rsa.encrypt(raw_data) 208 | let base64_string = encrypt_data!.base64String 209 | print(base64_string) 210 | let old_data = _rsa.decrypt(fromBase64String: base64_string) 211 | let old_string = String(data: old_data!, encoding: NSUTF8StringEncoding) 212 | print("old_string:\(old_string)") 213 | 214 | ### Sign and Verify 215 | 216 | You can use following alagorithms to sign: 217 | 218 | * MD2; 219 | * MD5; 220 | * SHA1; 221 | * SHA224; 222 | * SHA256; 223 | * SHA384; 224 | * SHA512; 225 | 226 | 227 | Sign using Private Key: 228 | 229 | `public func sign(algorithm:RSAAlgorithm,inputData:NSData) -> NSData?` 230 | 231 | Verify using Public Key: 232 | 233 | `public func verify(algorithm:RSAAlgorithm,inputData:NSData, signedData:NSData) -> Bool` 234 | 235 | 236 | let path_public = NSBundle.mainBundle().pathForResource("cert", ofType: "der")! 237 | let path_private = NSBundle.mainBundle().pathForResource("cert", ofType: "p12")! 238 | 239 | let rsa = RSA(filenameOfPulbicKey: path_public, filenameOfPrivateKey: path_private) 240 | guard let _rsa = rsa else { 241 | return 242 | } 243 | 244 | let raw = "0123456789abcdefg" 245 | let raw_data = raw.dataUsingEncoding(NSUTF8StringEncoding)! 246 | let sign_data = _rsa.sign(RSAAlgorithm.SHA1,inputData:raw_data) 247 | // print(sign_data!.hexString) 248 | print(sign_data!.base64String) 249 | 250 | let raw_test = "0123456789abcdefg" 251 | let raw_test_data = raw_test.dataUsingEncoding(NSUTF8StringEncoding)! 252 | let verified = _rsa.verify(RSAAlgorithm.SHA1,inputData: raw_test_data, signedData: sign_data!) 253 | print("\(verified)") 254 | 255 | ## NSData Extension 256 | 257 | * `hexString`: Hex string; 258 | * `base64String`: Base64 String 259 | * `arrayOfBytes`: Array of UInt8 260 | 261 | 262 | extension NSData { 263 | public var hexString : String 264 | public var base64String:String 265 | public func arrayOfBytes() -> [UInt8] 266 | } 267 | 268 | ## String Extension 269 | 270 | * `dataFromHexadecimalString`: Get NSData from Hex String; 271 | 272 | extenstion String { 273 | func dataFromHexadecimalString() -> NSData? 274 | } 275 | 276 | ## Test Script in Python 277 | 278 | * Checkout how to impletment same functions in Python as SecrecySwift. [SecrecyTestPy/test.py](SecrecyTestPy/test.py) 279 | 280 | ## References 281 | 282 | * [【加密解密】加密解密介绍](http://www.jianshu.com/p/98610bdc9bd6) 283 | * [iOS 系统中 AES 和 RSA 算法的实现](http://kvmisc.github.io/blog/2015/02/10/implement-aes-and-rsa-algorithm-in-ios/) 284 | * [AES.swift](https://github.com/adow/SecrecySwift/blob/master/SecrecySwift/AES.swift) 285 | * [iOS 系统中 AES 和 RSA 算法的实现](http://kvmisc.github.io/blog/2015/02/10/implement-aes-and-rsa-algorithm-in-ios/) 286 | * [RSA加密](http://blog.cnbluebox.com/blog/2014/03/19/rsajia-mi/) 287 | * [RSA.swift](https://github.com/adow/SecrecySwift/blob/master/SecrecySwift/RSA.swift) 288 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SecrecySwift 2 | 3 | [Readme in English](README-en.md) 4 | 5 | SecrecySwift ,通过包装 `CommonCrypto` 和 `Security.framework`,实现 Swift 下的摘要方法/AES/RSA加密和签名。 6 | 7 | ## 特性 8 | 9 | * 摘要算法 (Digest/HMAC): `MD2`/`MD4`/`MD5`/`SHA1`/`SHA224`/`SHA384`/`SHA512`; 10 | * AES 加密和解密: `EBC`/`CBC` 模式; 11 | * RSA 加密/解密以及签名和验证算法: `MD2`/`MD5`/`SHA1`/`SHA224`/`SHA384`; 12 | 13 | ## 安装 14 | 15 | ### 使用 Carthage 安装 16 | 17 | `Carthage` 是一个去中心化的包管理工具。 18 | 19 | 安装 Carthage 20 | 21 | $ brew update 22 | $ brew install carthage 23 | 24 | 集成 SecrecySwift 到 iOS 项目 25 | 26 | 1. 在项目中创建 `Cartfile` 文件,并添加下面内容 27 | 28 | git "https://github.com/adow/SecrecySwift.git" >= 0.3.4 29 | 30 | 2. 运行 `Carthage update`, 获取 SecrecySwift; 31 | 3. 拖动 `Carthage/Build/iOS` 下面的 `Secrecy.framwork` 到项目 `Targets`, `General` 设置标签的 `Linked Frameworks and Linraries` 中; 32 | 33 | ![secrecy-1](http://7vihfk.com1.z0.glb.clouddn.com/secrecy-1.png) 34 | 35 | 4. 在 `Targes` 的 `Build Phases` 设置中,点击 `+` 按钮,添加 `New Run Script Phase` 来添加脚本: 36 | 37 | /usr/local/bin/carthage copy-frameworks 38 | 39 | 同时在下面的 `Input Files` 中添加: 40 | 41 | $(SRCROOT)/Carthage/Build/iOS/Secrecy.framework 42 | 43 | ![secrecy-2](http://7vihfk.com1.z0.glb.clouddn.com/secrecy-2.png) 44 | 45 | ### 手动安装 46 | 47 | #### 通过 Git Submodule 48 | 49 | 通过 Submodule 将 SecrecySwift 作为 Embedded Framework 添加到项目中。 50 | 51 | 1. 首先确保项目已经在 git 仓库中; 52 | 2. 添加 `SecrecySwift` 作为 Submodule: 53 | 54 | git submodule add https://github.com/adow/SecrecySwift.git 55 | 56 | 3. 在 Xcode 中打开项目,将 SecrecySwift.xcodeproj 拖放到你的项目的根目录下; 57 | 4. 在你的项目下,选择 `Targets` , `General` 中添加 `Embedded Binaries`, 选择 `Secrecy.framework`, 确保 `Build Phases` 中的 `Link Binary with Libraries` 中有 `Secrecy.framework`; 58 | 59 | 60 | #### 项目中直接部署源代码 (兼容iOS7) 61 | 62 | 1. 复制 `SecrecySwift` 目录下的这些文件到项目中 63 | 64 | * AES.swift 65 | * Digest.swift 66 | * HMAC.swift 67 | * RSA.swift 68 | * SecrecyExtension.swift 69 | 70 | 2. 在项目根目录下建立一个 CommonCrypto, 并建立一个 module.map 文件 71 | 72 | module CommonCrypto [system] { 73 | header "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/usr/include/CommonCrypto/CommonCrypto.h" 74 | link "CommonCrypto" 75 | export * 76 | } 77 | 78 | 3. 在项目 Targets 的 `Build Settings` 中添加 `Import Paths` 中添加 `CommonCrypto`, 在 `Library Search Path` 中添加 `/usr/lib/system`。 79 | 80 | 4. 在 `Targets` 中 `Build Phases` 的 `Link Binary with Libraries` 中添加 `Security.framework` 和 `SystemConfiguration.framework`。 81 | 82 | 这样就不需要 `import Secrecy`, 直接使用里面的函数了; 83 | 84 | ### 为什么没有 Cocoapods 85 | 86 | 我尝试了好多次使用 `Cocoapods` 发布,但是实在没有制作 Cocoapods 的经验,好像是由于需要链接 `CommonCrypto` 的缘故,我参考了很多人写的 podspec 文件,仍然无法正确的链接 `CommonCrypto`, `pod lib lint` 一直都失败。如果您知道如何正确的为这个项目写一个 `podspec`,请一定要发一个 Pull Request 给我。 87 | 88 | ## 使用 89 | 90 | ### 摘要和 HMAC 91 | 92 | 只要方法来自 SwiftSSL 项目: [https://github.com/SwiftP2P/SwiftSSL](https://github.com/SwiftP2P/SwiftSSL) 93 | 94 | 支持以下的摘要方法 95 | 96 | * MD2; 97 | * MD4; 98 | * MD5; 99 | * SHA1; 100 | * SHA224; 101 | * SHA256; 102 | * SHA384; 103 | * SHA512; 104 | 105 | #### 摘要方法: 106 | 107 | NSData/String 的 `digestHex/digestBase64` 支持将摘要输出为 hex 和 base64 字符串; 108 | 109 | let raw = "abc123" 110 | print(raw.digestHex(DigestAlgorithm.MD5)) 111 | print(raw.digestBase64(DigestAlgorithm.MD5)) 112 | 113 | 114 | #### HMAC 签名方法 115 | 116 | NSData/String 的 `signHex/signBase64` 方法支持签名输出为 hex 和 base64 字符串; 117 | 118 | let raw = "abc123" 119 | print(raw.signHex(HMACAlgorithm.SHA1, key: "abc")) 120 | print(raw.signBase64(HMACAlgorithm.SHA1, key: "abc")) 121 | print(raw.signBase64(HMACAlgorithm.SHA1, key: "你好")) 122 | 123 | 124 | ### AES 125 | 126 | 127 | 支持 AES 模式 : 128 | 129 | * EBC; 130 | * CBC: 131 | 132 | ** 只支持 PKCSPaddding7 的补齐方式;** 133 | 134 | 根据提供的 Key 的长度,支持以下的加密方法 135 | 136 | * AES128: 16位 137 | * AES192: 24位; 138 | * AES256: 32位; 139 | 140 | 141 | #### EBC 模式 142 | 143 | * `aesEBCEncrypt` 进行EBC模式加密, 144 | * `aesEBCDecryptFromHex` 从 hex 字符串进行EBC模式解密 145 | * `aesEBCDecryptBase64` 从 base64 字符串进行EBC解密 146 | 147 | let key = "0000000000000000" 148 | let raw = "0123456789abcdef" 149 | let encrypt_1 = raw.aesEBCEncrypt(key) 150 | print(encrypt_1!.hexString) 151 | print(encrypt_1!.hexString.aesEBCDecryptFromHex(key)) 152 | print(encrypt_1!.base64String) 153 | print(encrypt_1!.base64String.aesEBCDecryptFromBase64(key)) 154 | 155 | #### CBC 模式 156 | 157 | CBC 模式可以指定 IV,如果不指定 IV 的话将用 0 填充; 158 | 159 | * `aesCBCEncrypt` 进行加密; 160 | * `aecCBCDecryptFromHex` 从 hex 字符串进行解密 161 | * `aesCBCDecryptFromBase64` 从 base64 字符串进行解密 162 | 163 | let iv = "0000000000000000" 164 | let encrypt = raw.aesCBCEncrypt(key,iv: iv) 165 | print(encrypt!.hexString) 166 | print(encrypt!.hexString.aesCBCDecryptFromHex(key,iv: iv)) 167 | print(encrypt!.base64String) 168 | print(encrypt!.base64String.aesCBCDecryptFromBase64(key,iv: iv)) 169 | 170 | ### RSA 171 | 172 | ** 只支持 `.der` 文件格式的公钥和 `.p12` 格式的私钥 (而 PHP/Java/Python 这些平台使用 pem 文件);只支持 PKCS1Padding 的补齐; ** 173 | 174 | 使用 `OpenSSL` 生成各个证书的方法 175 | 176 | # 生成 RSA 私钥 177 | openssl genrsa -out private.pem 2048 178 | 179 | # 从密钥中提取公钥 180 | openssl rsa -pubout -in private.pem -out public.pem 181 | 182 | # 用私钥生成证书签名请求 183 | openssl req -new -key private.pem -out cert.csr 184 | 185 | # 用私钥和证书签名请求生成自签名的证书 186 | openssl x509 -req -days 3650 -in cert.csr -signkey private.pem -out cert.crt 187 | 188 | # 将自签名的证书转换为 DER 格式(里面包含公钥) 189 | openssl x509 -outform der -in cert.crt -out cert.der 190 | 191 | # 将私钥和证书导出到 p12 文件中(要求输入密码) 192 | openssl pkcs12 -export -inkey private.pem -in cert.crt -out cert.p12 193 | 194 | 195 | #### 加密和解密 196 | 197 | 使用公钥进行加密 198 | 199 | * `public func encrypt(data:NSData) -> NSData?` 200 | 201 | 使用私钥进行解密 202 | 203 | * `public func decrypt(data:NSData) -> NSData?` 204 | * `public func decrypt(fromHexString hexString:String) -> NSData?` 205 | * `public func decrypt(fromBase64String base64String:String) -> NSData?` 206 | 207 | let path_public = NSBundle.mainBundle().pathForResource("cert", ofType: "der")! 208 | let path_private = NSBundle.mainBundle().pathForResource("cert", ofType: "p12")! 209 | let raw = "0123456789abcdefg" 210 | let raw_data = raw.dataUsingEncoding(NSUTF8StringEncoding)! 211 | let rsa = RSA(filenameOfPulbicKey: path_public, filenameOfPrivateKey: path_private) 212 | guard let _rsa = rsa else { 213 | return 214 | } 215 | let encrypt_data = _rsa.encrypt(raw_data) 216 | let base64_string = encrypt_data!.base64String 217 | print(base64_string) 218 | let old_data = _rsa.decrypt(fromBase64String: base64_string) 219 | let old_string = String(data: old_data!, encoding: NSUTF8StringEncoding) 220 | print("old_string:\(old_string)") 221 | 222 | ### 签名和验证 223 | 224 | 支持签名时的摘要算法: 225 | 226 | * MD2; 227 | * MD5; 228 | * SHA1; 229 | * SHA224; 230 | * SHA256; 231 | * SHA384; 232 | * SHA512; 233 | 234 | 235 | 使用私钥签名方法: 236 | 237 | `public func sign(algorithm:RSAAlgorithm,inputData:NSData) -> NSData?` 238 | 239 | 使用公钥的验证方法: 240 | 241 | `public func verify(algorithm:RSAAlgorithm,inputData:NSData, signedData:NSData) -> Bool` 242 | 243 | 244 | let path_public = NSBundle.mainBundle().pathForResource("cert", ofType: "der")! 245 | let path_private = NSBundle.mainBundle().pathForResource("cert", ofType: "p12")! 246 | 247 | let rsa = RSA(filenameOfPulbicKey: path_public, filenameOfPrivateKey: path_private) 248 | guard let _rsa = rsa else { 249 | return 250 | } 251 | 252 | let raw = "0123456789abcdefg" 253 | let raw_data = raw.dataUsingEncoding(NSUTF8StringEncoding)! 254 | let sign_data = _rsa.sign(RSAAlgorithm.SHA1,inputData:raw_data) 255 | // print(sign_data!.hexString) 256 | print(sign_data!.base64String) 257 | 258 | let raw_test = "0123456789abcdefg" 259 | let raw_test_data = raw_test.dataUsingEncoding(NSUTF8StringEncoding)! 260 | let verified = _rsa.verify(RSAAlgorithm.SHA1,inputData: raw_test_data, signedData: sign_data!) 261 | print("\(verified)") 262 | 263 | ## 扩展 NSData 264 | 265 | * `hexString`: 输出 hex 字符串; 266 | * `base64String`: 输出 base64 字符串 267 | * `arrayOfBytes`: 输出 `[UInt8]` 数组; 268 | 269 | 270 | extension NSData { 271 | public var hexString : String 272 | public var base64String:String 273 | public func arrayOfBytes() -> [UInt8] 274 | } 275 | 276 | ## 扩展 String 277 | 278 | * `dataFromHexadecimalString`: 从 hex 字符串转换到 NSData; 279 | 280 | extenstion String { 281 | func dataFromHexadecimalString() -> NSData? 282 | } 283 | 284 | ## 测试 285 | 286 | * 如何在 Python 中验证和 SecrecySwift 相同功能的示例 [SecrecyTestPy/test.py](SecrecyTestPy/test.py) 287 | 288 | ## References 289 | 290 | * [【加密解密】加密解密介绍](http://www.jianshu.com/p/98610bdc9bd6) 291 | * [iOS 系统中 AES 和 RSA 算法的实现](http://kvmisc.github.io/blog/2015/02/10/implement-aes-and-rsa-algorithm-in-ios/) 292 | * [AES.swift](https://github.com/adow/SecrecySwift/blob/master/SecrecySwift/AES.swift) 293 | * [iOS 系统中 AES 和 RSA 算法的实现](http://kvmisc.github.io/blog/2015/02/10/implement-aes-and-rsa-algorithm-in-ios/) 294 | * [RSA加密](http://blog.cnbluebox.com/blog/2014/03/19/rsajia-mi/) 295 | * [RSA.swift](https://github.com/adow/SecrecySwift/blob/master/SecrecySwift/RSA.swift) 296 | -------------------------------------------------------------------------------- /SecrecTestPy/cert.crt: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIDBjCCAe4CCQDaedbJhfBqUjANBgkqhkiG9w0BAQUFADBFMQswCQYDVQQGEwJB 3 | VTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50ZXJuZXQgV2lkZ2l0 4 | cyBQdHkgTHRkMB4XDTE1MTIxNTAyNDE1OFoXDTI1MTIxMjAyNDE1OFowRTELMAkG 5 | A1UEBhMCQVUxEzARBgNVBAgTClNvbWUtU3RhdGUxITAfBgNVBAoTGEludGVybmV0 6 | IFdpZGdpdHMgUHR5IEx0ZDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB 7 | AMfVL6H0Tb1VRXb8UczPLBANN6uBkadwvvILHHnk6mwAbMOLzLyIL3v+d9hMgXsg 8 | C/TXMyJPCN055ymEI5FMM6Md3rHQgJRgUaPVaqc9GkyH5j+gt9nTJpD/jVqVdwXL 9 | G3HA4qaR/BvmMIxohmmseFLYCvL6uYioJRF9qvle2A83Of5VrNmn+7wEz/IUE+K0 10 | pfk/ezdfwYoveVKq04yXv8/kUsG93L10pJZYd0kVaWMznhxqXGW1OKEmaW9jNotc 11 | 4lj/l6Dws1//BRsy1e+R2FtHrM3o1PrPOIcoTCXAAKGzbg+R28GIOt4AGniMd4kn 12 | n0CQumQT8ykfNE4krkhB9B8CAwEAATANBgkqhkiG9w0BAQUFAAOCAQEAHQVvswAQ 13 | tMlhkjI8u8nLhOQH1pk/aZmcmnQLTSV41k7nRNOddVwtpeKAAG83NZgR+i1/taBK 14 | EDCoDBTsRZcTwZlM1NH8nV9cESf09TfI0yKv3aRAhgxBkCLe/GkoEqFxDN4xr+5q 15 | XNLtOSfgIkkoGiMxMoed68LECZwq+vdjdP+WLfVEcdjxSLIm/P9ltFLZfCOkRyLy 16 | ZTz/FnVEEyDK6IUQTR4d3UuJ3U4coQfOHwdOM/XZQpcloUQHSvIz3Xia0o9jFwR6 17 | A5hVxIPBnXQ7OLcfCRwGwv9ITmbeK12lq2qsqTrafyCmILja2mTmaya0DY0YViBz 18 | X6dQS+cTkBP+Jg== 19 | -----END CERTIFICATE----- 20 | -------------------------------------------------------------------------------- /SecrecTestPy/cert.csr: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE REQUEST----- 2 | MIICijCCAXICAQAwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgTClNvbWUtU3RhdGUx 3 | ITAfBgNVBAoTGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDCCASIwDQYJKoZIhvcN 4 | AQEBBQADggEPADCCAQoCggEBAMfVL6H0Tb1VRXb8UczPLBANN6uBkadwvvILHHnk 5 | 6mwAbMOLzLyIL3v+d9hMgXsgC/TXMyJPCN055ymEI5FMM6Md3rHQgJRgUaPVaqc9 6 | GkyH5j+gt9nTJpD/jVqVdwXLG3HA4qaR/BvmMIxohmmseFLYCvL6uYioJRF9qvle 7 | 2A83Of5VrNmn+7wEz/IUE+K0pfk/ezdfwYoveVKq04yXv8/kUsG93L10pJZYd0kV 8 | aWMznhxqXGW1OKEmaW9jNotc4lj/l6Dws1//BRsy1e+R2FtHrM3o1PrPOIcoTCXA 9 | AKGzbg+R28GIOt4AGniMd4knn0CQumQT8ykfNE4krkhB9B8CAwEAAaAAMA0GCSqG 10 | SIb3DQEBBQUAA4IBAQC9UjL7UXKVDjzEZhvagpdPAim1k9ie9/eN9evCVuANhSUG 11 | BVw0mKoISPa18kXlLSX7cWAhrtAZ9Le9rZLAkJM3KC1N3qKW58zEuC6nTwcuxCwi 12 | bkH74cFwzN3QpEI9ugOR9Mm5nn4PZaMm1VSvvqT1kqAkm357TcXA6vhzZb5yN8CJ 13 | psHHxtbVZZ+37HEe2U9LfLzizs+auLMUFiEy+vVy2snh6S61gHMUsmBUxgpWSKey 14 | yexTfCmLdWQHbYC4uWbhGxhxR5iKP0LvQsuWv1q6ZK4xoGm9n4WjN2AencKIaGjW 15 | kuQ9AKk4wBJL/QMpTdPnTc5wnmHLLjtZk/GzNYdH 16 | -----END CERTIFICATE REQUEST----- 17 | -------------------------------------------------------------------------------- /SecrecTestPy/cert.der: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adow/SecrecySwift/254bc17928b51219e7d09c4631f6000e12419df4/SecrecTestPy/cert.der -------------------------------------------------------------------------------- /SecrecTestPy/cert.p12: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adow/SecrecySwift/254bc17928b51219e7d09c4631f6000e12419df4/SecrecTestPy/cert.p12 -------------------------------------------------------------------------------- /SecrecTestPy/private.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN RSA PRIVATE KEY----- 2 | MIIEowIBAAKCAQEAx9UvofRNvVVFdvxRzM8sEA03q4GRp3C+8gsceeTqbABsw4vM 3 | vIgve/532EyBeyAL9NczIk8I3TnnKYQjkUwzox3esdCAlGBRo9Vqpz0aTIfmP6C3 4 | 2dMmkP+NWpV3BcsbccDippH8G+YwjGiGaax4UtgK8vq5iKglEX2q+V7YDzc5/lWs 5 | 2af7vATP8hQT4rSl+T97N1/Bii95UqrTjJe/z+RSwb3cvXSkllh3SRVpYzOeHGpc 6 | ZbU4oSZpb2M2i1ziWP+XoPCzX/8FGzLV75HYW0eszejU+s84hyhMJcAAobNuD5Hb 7 | wYg63gAaeIx3iSefQJC6ZBPzKR80TiSuSEH0HwIDAQABAoIBAQCkMn3TG4SNH/XW 8 | EPm9yjUwc0vc9rgR10huZcbeOcSNPcQg4Uw3Vcd+oNckuahi3TA13GW9uSdVb/CL 9 | YnI/P1fmnfKQNPyR7prmfcQG6uQjIj+E5LBsoV09I16oocuMzRkd3RnfOHDpE7ms 10 | hW58giTUHYTRpkaxDUh4GMRV5yKtTITo0cyh0xxZu0FGoPQciNuUbrUUHXM6dPK1 11 | nH78b7rfKsynPwOnECs1Oi6WzooGnje/ScCS9er2oac7FzTmkAsrd70ZT8ALizyg 12 | QYRZWW+S8XLeuqZMRvbp+Ho3/4Rs+pIBbVaeFvZ//ZktChYcAeFml3iD0sW56fV9 13 | xe4rLoBxAoGBAPQd5nji8dtz0js9jb7U7M8UAAwM+HUMlfzX4+5z0geFDBGHLQ6A 14 | 8mUijaE+OACMFOxK5ia8YqnBqVkDjS0V++r5WCJ9Wk8MpLmfBH+U0UNTmybW9ZM4 15 | ee2eydiioLu9ZSF9iUaFuesEsgIs5Vb6GCPc6i6RdliPlmRN2TwxwrrdAoGBANGP 16 | buucRglm62GIxLDkm1n5hGqUNG9HyyZiCops0ZbKsu17qIOW65DERSCi/Fz/Wywt 17 | htWeaiNWDIxkH4OUN8eF0vGorMbK7WjgWwClcBMOJ0fUaQuWl0MgM8KHr+uQFIiy 18 | yCXSpo5957ylWpLcvXDyhYKwYZBPFtDR8kzIe0UrAoGAA9rxB9m1rhyPJmZbdbcR 19 | IlgThB00U0zmlX6nV922ZG4CechjusXojhZUnEZKRh/wOKcaKWRyPnIThZdbxGmD 20 | d/uGG81U/siZVWEghg9ImsKYQa3FZRTQQCNw1p4C4dQk47mC0H1OKVsCoKwq1wvO 21 | E8rqW9/qOY3S9zSPiLbUd3UCgYBwNN/MclGh6SSxhbzjhpSUGaFIO/DTgNqKw8Yn 22 | Flsm5YPm2uaBBwc87YqiDgMYfHZB8mKW8Qqdvw5bAaVKG8u+Hq6zTICutKtoE3FG 23 | qE6ZNWPc9yQD229EtvJf/603cV89TpUSg3dBJrM1dEhKCL26w3CvaGflECQETdXy 24 | PQqcHwKBgGkEB9fYHVbZ8A7fB1WU6THcUTycjFEOtwwHxm+qE8ZPgNqOB38Z3XVP 25 | gjQa26Yf1tBDGGWKhaOqkmDePsirmvFGTz9rP6s0lt7hdkZfmti5WCPG3tQu69Td 26 | aPJyrWqpC2BaJyO7inajt4/YoGADZwRd+qEH89MH6CqJtYd2PgJ9 27 | -----END RSA PRIVATE KEY----- 28 | -------------------------------------------------------------------------------- /SecrecTestPy/public.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN PUBLIC KEY----- 2 | MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAx9UvofRNvVVFdvxRzM8s 3 | EA03q4GRp3C+8gsceeTqbABsw4vMvIgve/532EyBeyAL9NczIk8I3TnnKYQjkUwz 4 | ox3esdCAlGBRo9Vqpz0aTIfmP6C32dMmkP+NWpV3BcsbccDippH8G+YwjGiGaax4 5 | UtgK8vq5iKglEX2q+V7YDzc5/lWs2af7vATP8hQT4rSl+T97N1/Bii95UqrTjJe/ 6 | z+RSwb3cvXSkllh3SRVpYzOeHGpcZbU4oSZpb2M2i1ziWP+XoPCzX/8FGzLV75HY 7 | W0eszejU+s84hyhMJcAAobNuD5HbwYg63gAaeIx3iSefQJC6ZBPzKR80TiSuSEH0 8 | HwIDAQAB 9 | -----END PUBLIC KEY----- 10 | -------------------------------------------------------------------------------- /SecrecTestPy/test.py: -------------------------------------------------------------------------------- 1 | #coding= utf-8 2 | ''' 3 | 4 | by adow 5 | ''' 6 | import os 7 | import logging 8 | import functools 9 | import uuid 10 | from string import Template 11 | import time 12 | import datetime 13 | import json 14 | import hashlib 15 | import re 16 | import base64 17 | import urllib as urllib_parse 18 | 19 | from Crypto.PublicKey import RSA 20 | from Crypto.Hash import MD5 21 | from Crypto.Hash import SHA 22 | from Crypto.Cipher import AES 23 | from Crypto import Random 24 | 25 | # load_key 26 | f = open('private.pem') 27 | private_key_str = f.read() 28 | f.close() 29 | private_key = RSA.importKey(private_key_str) 30 | 31 | f = open('public.pem') 32 | public_key_str = f.read() 33 | f.close() 34 | public_key = RSA.importKey(public_key_str) 35 | 36 | def _pkcs7padding(data): 37 | """ 38 | 对齐块 39 | size 16 40 | 999999999=>9999999997777777 41 | """ 42 | size = AES.block_size 43 | count = size - len(data)%size 44 | if count: 45 | data+=(chr(count)*count) 46 | return data 47 | 48 | def test_rsa_decrypt(): 49 | from Crypto.Cipher import PKCS1_v1_5 50 | '''测试 RSA 解密,从 SwcrecyDemo 中得到加密后的 base64 字符串''' 51 | encrypt_base64 = "fvuu1fKeeo3Z/qoSAsZ80IyTu+7BJ2OEfcGJAgnxaO6D82lsNp+QEYgSzTK7IgrUnHhqEFYWsqnGIlX5N/SDblZbBTTEXKHcWntlV3bVJQUUxK+GGC1j7GK02bL0yNZRZ1xz/JU9nZV2L7lt3PQckh0f1Lc2xBe7hqprbVYkufFVnE3hwPirVUyfbbhE8KZ2eiMTApxRY+GRHtpBhibPkZ44E4NDmNaT9S8uMjZ6TqTzQddp9MCGMo+6Kp4HA+O33LG9pgxAoAgm/J6NeJJB3iSdtMdQ6IyBnw2p93KaVlnD8kWg10BbxtJ0QWg7osiEoLXVWoLBzqARkk1pl+66FQ==" 52 | encrypt = base64.b64decode(encrypt_base64) 53 | cipher = PKCS1_v1_5.new(private_key) 54 | 55 | dsize = SHA.digest_size 56 | sentinel = Random.new().read(15 + dsize) 57 | decrypt = cipher.decrypt(encrypt,sentinel) 58 | print 'rsa_decrypt:%s'%(decrypt,) 59 | 60 | def test_rsa_sign(): 61 | from Crypto.Signature import PKCS1_v1_5 62 | raw = "0123456789abcdefg" 63 | digest = SHA.new(raw) 64 | 65 | verifier = PKCS1_v1_5.new(private_key) 66 | sign = verifier.sign(digest) 67 | sign_base64 = base64.b64encode(sign) 68 | print "sign:%s"%(sign_base64,) 69 | 70 | def test_rsa_verify(): 71 | from Crypto.Signature import PKCS1_v1_5 72 | raw = "0123456789abcdefg" 73 | digest = SHA.new(raw) 74 | sign_base64 = '''g/mL63vojOxMVMB/K4EeuG6VFg3smN/sd5zOrNZyBjYSXTELcmkzl7yqduSyBT/BvR6i3qeuyvb+lZ4osatXyZMe0q0dT0NiMNDfXAJ+awD8+5/SymKsPs0lrQXBjNhuCLbwC4Up5ueg5Whox3hRG2iMkN50y37wLYTqSWyYJ6RpvdsXNks2051m5pohCoD2OB97qEteqri0BqYfgmXh0Xq9weCtfdAbs20w2vp+wdFFqduu01ElGQtbkCuTokMzr5O9WWl8F7dKq1j7nXpdxKD9SFfQafUNSarET3qw2VC/Jck9u0q6sOZErb03fl034t5GeYKPtPIwBvzCGSsFsA==''' 75 | #print sign_base64 76 | sign = base64.b64decode(sign_base64) 77 | #verifier = PKCS1_v1_5.new(public_key) 78 | verifier = PKCS1_v1_5.new(public_key) 79 | v = verifier.verify(digest,sign) 80 | print "verifiy:%s"%(str(v),) 81 | 82 | def test_aes_encrypt(): 83 | raw = "0123456789abcdef" 84 | #raw = "012345678" 85 | raw = _pkcs7padding(raw) 86 | key = "0000000000000000" 87 | cipher = AES.new(key,AES.MODE_ECB) 88 | encrypt = cipher.encrypt(raw) 89 | encrypt_base64 = base64.b64encode(encrypt) 90 | print 'encrypt:%s'%(encrypt_base64,) 91 | 92 | iv = '0' * (AES.block_size) 93 | #print iv 94 | cipher = AES.new(key,AES.MODE_CBC,iv) 95 | encrypt = cipher.encrypt(raw) 96 | encrypt_base64 = base64.b64encode(encrypt) 97 | print 'encrypt:%s'%(encrypt_base64,) 98 | 99 | def test_aes_decrypt(): 100 | encrypt_base64 = "8dL/6Vu+D81gqcXzLXGl1TRrzguO7TTaEPao+ruERJQ=" 101 | encrypt = base64.b64decode(encrypt_base64) 102 | key = "0000000000000000" 103 | cipher = AES.new(key,AES.MODE_ECB) 104 | raw = cipher.decrypt(encrypt) 105 | print 'decrypt:%s'%(raw,) 106 | 107 | 108 | 109 | if __name__ == '__main__': 110 | test_rsa_decrypt() 111 | test_rsa_sign() 112 | test_rsa_verify() 113 | test_aes_encrypt() 114 | test_aes_decrypt() 115 | -------------------------------------------------------------------------------- /SecrecySwift.podspec: -------------------------------------------------------------------------------- 1 | Pod::Spec.new do |s| 2 | 3 | s.name = "SecrecySwift" 4 | s.version = "0.1.0" 5 | s.summary = "RSA/AES/Digest/HMAC for Swift" 6 | 7 | s.description = <<-DESC 8 | RSA/AES/Digest/HMAC for Swift 9 | DESC 10 | 11 | s.homepage = "https://github.com/adow/SecrecySwift" 12 | 13 | s.license = { :type => "MIT", :file => "LICENSE" } 14 | 15 | s.authors = { "adow" => "reynoldqin@gmail.com" } 16 | s.social_media_url = "http://twitter.com/reynoldqin" 17 | 18 | s.ios.deployment_target = "8.0" 19 | s.module_name = s.name 20 | s.source = { :git => "git@github.com:adow/SecrecySwift.git", :tag => s.version } 21 | s.source_files = ["SecrecySwift/*.swift","SecrecySwift/*.h"] 22 | s.requires_arc = true 23 | s.framework = "SystemConfiguration","Security" 24 | s.library = "CommonCrypto" 25 | #s.libraries = "CommonCrypto" 26 | s.module_map = "$(PODS_ROOT)/CommonCrypto/module.modulemap" 27 | s.pod_target_xcconfig = { 'HEADER_SEARCH_PATHS' => '$(PODS_ROOT)/CommonCrypto '} 28 | s.xcconfig = { 'HEADER_SEARCH_PATHS' => '$(SDKROOT)/usr/include/CommonCrypto $(PODS_ROOT)/CommonCrypto' } 29 | end 30 | 31 | 32 | -------------------------------------------------------------------------------- /SecrecySwift.xcodeproj/project.pbxproj: -------------------------------------------------------------------------------- 1 | // !$*UTF8*$! 2 | { 3 | archiveVersion = 1; 4 | classes = { 5 | }; 6 | objectVersion = 46; 7 | objects = { 8 | 9 | /* Begin PBXBuildFile section */ 10 | 6861DFFE1C21308800F410C9 /* SecrecySwift.h in Headers */ = {isa = PBXBuildFile; fileRef = 6861DFFD1C21308800F410C9 /* SecrecySwift.h */; settings = {ATTRIBUTES = (Public, ); }; }; 11 | 6861E00C1C2130AB00F410C9 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6861E00B1C2130AB00F410C9 /* AppDelegate.swift */; }; 12 | 6861E00E1C2130AB00F410C9 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6861E00D1C2130AB00F410C9 /* ViewController.swift */; }; 13 | 6861E0111C2130AB00F410C9 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 6861E00F1C2130AB00F410C9 /* Main.storyboard */; }; 14 | 6861E0131C2130AB00F410C9 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 6861E0121C2130AB00F410C9 /* Assets.xcassets */; }; 15 | 6861E0161C2130AB00F410C9 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 6861E0141C2130AB00F410C9 /* LaunchScreen.storyboard */; }; 16 | 6861E0201C21313F00F410C9 /* AES.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6861E01B1C21313F00F410C9 /* AES.swift */; }; 17 | 6861E0211C21313F00F410C9 /* RSA.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6861E01C1C21313F00F410C9 /* RSA.swift */; }; 18 | 6861E0221C21313F00F410C9 /* SecrecyExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6861E01D1C21313F00F410C9 /* SecrecyExtension.swift */; }; 19 | 6861E0231C21313F00F410C9 /* Digest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6861E01E1C21313F00F410C9 /* Digest.swift */; }; 20 | 6861E0241C21313F00F410C9 /* HMAC.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6861E01F1C21313F00F410C9 /* HMAC.swift */; }; 21 | 6861E0261C2131B600F410C9 /* SystemConfiguration.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6861E0251C2131B600F410C9 /* SystemConfiguration.framework */; }; 22 | 6861E0281C2131BF00F410C9 /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6861E0271C2131BF00F410C9 /* Security.framework */; }; 23 | 6861E0331C2135EA00F410C9 /* cert.der in Resources */ = {isa = PBXBuildFile; fileRef = 6861E0311C2135EA00F410C9 /* cert.der */; }; 24 | 6861E0341C2135EA00F410C9 /* cert.p12 in Resources */ = {isa = PBXBuildFile; fileRef = 6861E0321C2135EA00F410C9 /* cert.p12 */; }; 25 | 68C768051C3B5CEC0029AD08 /* Secrecy.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 6861DFFA1C21308800F410C9 /* Secrecy.framework */; }; 26 | 68C768061C3B5CEC0029AD08 /* Secrecy.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 6861DFFA1C21308800F410C9 /* Secrecy.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; 27 | /* End PBXBuildFile section */ 28 | 29 | /* Begin PBXContainerItemProxy section */ 30 | 68C768031C3B5CDC0029AD08 /* PBXContainerItemProxy */ = { 31 | isa = PBXContainerItemProxy; 32 | containerPortal = 6861DFF11C21308800F410C9 /* Project object */; 33 | proxyType = 1; 34 | remoteGlobalIDString = 6861DFF91C21308800F410C9; 35 | remoteInfo = SecrecySwift; 36 | }; 37 | /* End PBXContainerItemProxy section */ 38 | 39 | /* Begin PBXCopyFilesBuildPhase section */ 40 | 68C768071C3B5CED0029AD08 /* Embed Frameworks */ = { 41 | isa = PBXCopyFilesBuildPhase; 42 | buildActionMask = 2147483647; 43 | dstPath = ""; 44 | dstSubfolderSpec = 10; 45 | files = ( 46 | 68C768061C3B5CEC0029AD08 /* Secrecy.framework in Embed Frameworks */, 47 | ); 48 | name = "Embed Frameworks"; 49 | runOnlyForDeploymentPostprocessing = 0; 50 | }; 51 | /* End PBXCopyFilesBuildPhase section */ 52 | 53 | /* Begin PBXFileReference section */ 54 | 6861DFFA1C21308800F410C9 /* Secrecy.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Secrecy.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 55 | 6861DFFD1C21308800F410C9 /* SecrecySwift.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = SecrecySwift.h; sourceTree = ""; }; 56 | 6861DFFF1C21308800F410C9 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 57 | 6861E0091C2130AB00F410C9 /* SecrecySwiftDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SecrecySwiftDemo.app; sourceTree = BUILT_PRODUCTS_DIR; }; 58 | 6861E00B1C2130AB00F410C9 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 59 | 6861E00D1C2130AB00F410C9 /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; }; 60 | 6861E0101C2130AB00F410C9 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; 61 | 6861E0121C2130AB00F410C9 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 62 | 6861E0151C2130AB00F410C9 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 63 | 6861E0171C2130AB00F410C9 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 64 | 6861E01B1C21313F00F410C9 /* AES.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AES.swift; sourceTree = ""; }; 65 | 6861E01C1C21313F00F410C9 /* RSA.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RSA.swift; sourceTree = ""; }; 66 | 6861E01D1C21313F00F410C9 /* SecrecyExtension.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SecrecyExtension.swift; sourceTree = ""; }; 67 | 6861E01E1C21313F00F410C9 /* Digest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Digest.swift; sourceTree = ""; }; 68 | 6861E01F1C21313F00F410C9 /* HMAC.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HMAC.swift; sourceTree = ""; }; 69 | 6861E0251C2131B600F410C9 /* SystemConfiguration.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SystemConfiguration.framework; path = System/Library/Frameworks/SystemConfiguration.framework; sourceTree = SDKROOT; }; 70 | 6861E0271C2131BF00F410C9 /* Security.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Security.framework; path = System/Library/Frameworks/Security.framework; sourceTree = SDKROOT; }; 71 | 6861E02B1C2132CB00F410C9 /* module.map */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = "sourcecode.module-map"; path = module.map; sourceTree = ""; }; 72 | 6861E0311C2135EA00F410C9 /* cert.der */ = {isa = PBXFileReference; lastKnownFileType = file; path = cert.der; sourceTree = ""; }; 73 | 6861E0321C2135EA00F410C9 /* cert.p12 */ = {isa = PBXFileReference; lastKnownFileType = file; path = cert.p12; sourceTree = ""; }; 74 | /* End PBXFileReference section */ 75 | 76 | /* Begin PBXFrameworksBuildPhase section */ 77 | 6861DFF61C21308800F410C9 /* Frameworks */ = { 78 | isa = PBXFrameworksBuildPhase; 79 | buildActionMask = 2147483647; 80 | files = ( 81 | 6861E0281C2131BF00F410C9 /* Security.framework in Frameworks */, 82 | 6861E0261C2131B600F410C9 /* SystemConfiguration.framework in Frameworks */, 83 | ); 84 | runOnlyForDeploymentPostprocessing = 0; 85 | }; 86 | 6861E0061C2130AB00F410C9 /* Frameworks */ = { 87 | isa = PBXFrameworksBuildPhase; 88 | buildActionMask = 2147483647; 89 | files = ( 90 | 68C768051C3B5CEC0029AD08 /* Secrecy.framework in Frameworks */, 91 | ); 92 | runOnlyForDeploymentPostprocessing = 0; 93 | }; 94 | /* End PBXFrameworksBuildPhase section */ 95 | 96 | /* Begin PBXGroup section */ 97 | 6861DFF01C21308800F410C9 = { 98 | isa = PBXGroup; 99 | children = ( 100 | 6861E02A1C2132CB00F410C9 /* CommonCrypto */, 101 | 6861E0291C2131C900F410C9 /* Frameworks */, 102 | 6861DFFC1C21308800F410C9 /* SecrecySwift */, 103 | 6861E00A1C2130AB00F410C9 /* SecrecySwiftDemo */, 104 | 6861DFFB1C21308800F410C9 /* Products */, 105 | ); 106 | sourceTree = ""; 107 | }; 108 | 6861DFFB1C21308800F410C9 /* Products */ = { 109 | isa = PBXGroup; 110 | children = ( 111 | 6861DFFA1C21308800F410C9 /* Secrecy.framework */, 112 | 6861E0091C2130AB00F410C9 /* SecrecySwiftDemo.app */, 113 | ); 114 | name = Products; 115 | sourceTree = ""; 116 | }; 117 | 6861DFFC1C21308800F410C9 /* SecrecySwift */ = { 118 | isa = PBXGroup; 119 | children = ( 120 | 6861E01B1C21313F00F410C9 /* AES.swift */, 121 | 6861E01C1C21313F00F410C9 /* RSA.swift */, 122 | 6861E01D1C21313F00F410C9 /* SecrecyExtension.swift */, 123 | 6861E01E1C21313F00F410C9 /* Digest.swift */, 124 | 6861E01F1C21313F00F410C9 /* HMAC.swift */, 125 | 6861DFFD1C21308800F410C9 /* SecrecySwift.h */, 126 | 6861DFFF1C21308800F410C9 /* Info.plist */, 127 | ); 128 | path = SecrecySwift; 129 | sourceTree = ""; 130 | }; 131 | 6861E00A1C2130AB00F410C9 /* SecrecySwiftDemo */ = { 132 | isa = PBXGroup; 133 | children = ( 134 | 6861E0311C2135EA00F410C9 /* cert.der */, 135 | 6861E0321C2135EA00F410C9 /* cert.p12 */, 136 | 6861E00B1C2130AB00F410C9 /* AppDelegate.swift */, 137 | 6861E00D1C2130AB00F410C9 /* ViewController.swift */, 138 | 6861E00F1C2130AB00F410C9 /* Main.storyboard */, 139 | 6861E0121C2130AB00F410C9 /* Assets.xcassets */, 140 | 6861E0141C2130AB00F410C9 /* LaunchScreen.storyboard */, 141 | 6861E0171C2130AB00F410C9 /* Info.plist */, 142 | ); 143 | path = SecrecySwiftDemo; 144 | sourceTree = ""; 145 | }; 146 | 6861E0291C2131C900F410C9 /* Frameworks */ = { 147 | isa = PBXGroup; 148 | children = ( 149 | 6861E0271C2131BF00F410C9 /* Security.framework */, 150 | 6861E0251C2131B600F410C9 /* SystemConfiguration.framework */, 151 | ); 152 | name = Frameworks; 153 | sourceTree = ""; 154 | }; 155 | 6861E02A1C2132CB00F410C9 /* CommonCrypto */ = { 156 | isa = PBXGroup; 157 | children = ( 158 | 6861E02B1C2132CB00F410C9 /* module.map */, 159 | ); 160 | path = CommonCrypto; 161 | sourceTree = ""; 162 | }; 163 | /* End PBXGroup section */ 164 | 165 | /* Begin PBXHeadersBuildPhase section */ 166 | 6861DFF71C21308800F410C9 /* Headers */ = { 167 | isa = PBXHeadersBuildPhase; 168 | buildActionMask = 2147483647; 169 | files = ( 170 | 6861DFFE1C21308800F410C9 /* SecrecySwift.h in Headers */, 171 | ); 172 | runOnlyForDeploymentPostprocessing = 0; 173 | }; 174 | /* End PBXHeadersBuildPhase section */ 175 | 176 | /* Begin PBXNativeTarget section */ 177 | 6861DFF91C21308800F410C9 /* SecrecySwift */ = { 178 | isa = PBXNativeTarget; 179 | buildConfigurationList = 6861E0021C21308800F410C9 /* Build configuration list for PBXNativeTarget "SecrecySwift" */; 180 | buildPhases = ( 181 | 6861DFF51C21308800F410C9 /* Sources */, 182 | 6861DFF61C21308800F410C9 /* Frameworks */, 183 | 6861DFF71C21308800F410C9 /* Headers */, 184 | 6861DFF81C21308800F410C9 /* Resources */, 185 | ); 186 | buildRules = ( 187 | ); 188 | dependencies = ( 189 | ); 190 | name = SecrecySwift; 191 | productName = SecrecySwift; 192 | productReference = 6861DFFA1C21308800F410C9 /* Secrecy.framework */; 193 | productType = "com.apple.product-type.framework"; 194 | }; 195 | 6861E0081C2130AB00F410C9 /* SecrecySwiftDemo */ = { 196 | isa = PBXNativeTarget; 197 | buildConfigurationList = 6861E0181C2130AB00F410C9 /* Build configuration list for PBXNativeTarget "SecrecySwiftDemo" */; 198 | buildPhases = ( 199 | 6861E0051C2130AB00F410C9 /* Sources */, 200 | 6861E0061C2130AB00F410C9 /* Frameworks */, 201 | 6861E0071C2130AB00F410C9 /* Resources */, 202 | 68C768071C3B5CED0029AD08 /* Embed Frameworks */, 203 | ); 204 | buildRules = ( 205 | ); 206 | dependencies = ( 207 | 68C768041C3B5CDC0029AD08 /* PBXTargetDependency */, 208 | ); 209 | name = SecrecySwiftDemo; 210 | productName = SecrecySwiftDemo; 211 | productReference = 6861E0091C2130AB00F410C9 /* SecrecySwiftDemo.app */; 212 | productType = "com.apple.product-type.application"; 213 | }; 214 | /* End PBXNativeTarget section */ 215 | 216 | /* Begin PBXProject section */ 217 | 6861DFF11C21308800F410C9 /* Project object */ = { 218 | isa = PBXProject; 219 | attributes = { 220 | LastSwiftUpdateCheck = 0720; 221 | LastUpgradeCheck = 0800; 222 | ORGANIZATIONNAME = "秦 道平"; 223 | TargetAttributes = { 224 | 6861DFF91C21308800F410C9 = { 225 | CreatedOnToolsVersion = 7.2; 226 | LastSwiftMigration = 0800; 227 | }; 228 | 6861E0081C2130AB00F410C9 = { 229 | CreatedOnToolsVersion = 7.2; 230 | LastSwiftMigration = 0800; 231 | }; 232 | }; 233 | }; 234 | buildConfigurationList = 6861DFF41C21308800F410C9 /* Build configuration list for PBXProject "SecrecySwift" */; 235 | compatibilityVersion = "Xcode 3.2"; 236 | developmentRegion = English; 237 | hasScannedForEncodings = 0; 238 | knownRegions = ( 239 | en, 240 | Base, 241 | ); 242 | mainGroup = 6861DFF01C21308800F410C9; 243 | productRefGroup = 6861DFFB1C21308800F410C9 /* Products */; 244 | projectDirPath = ""; 245 | projectRoot = ""; 246 | targets = ( 247 | 6861DFF91C21308800F410C9 /* SecrecySwift */, 248 | 6861E0081C2130AB00F410C9 /* SecrecySwiftDemo */, 249 | ); 250 | }; 251 | /* End PBXProject section */ 252 | 253 | /* Begin PBXResourcesBuildPhase section */ 254 | 6861DFF81C21308800F410C9 /* Resources */ = { 255 | isa = PBXResourcesBuildPhase; 256 | buildActionMask = 2147483647; 257 | files = ( 258 | ); 259 | runOnlyForDeploymentPostprocessing = 0; 260 | }; 261 | 6861E0071C2130AB00F410C9 /* Resources */ = { 262 | isa = PBXResourcesBuildPhase; 263 | buildActionMask = 2147483647; 264 | files = ( 265 | 6861E0161C2130AB00F410C9 /* LaunchScreen.storyboard in Resources */, 266 | 6861E0341C2135EA00F410C9 /* cert.p12 in Resources */, 267 | 6861E0131C2130AB00F410C9 /* Assets.xcassets in Resources */, 268 | 6861E0111C2130AB00F410C9 /* Main.storyboard in Resources */, 269 | 6861E0331C2135EA00F410C9 /* cert.der in Resources */, 270 | ); 271 | runOnlyForDeploymentPostprocessing = 0; 272 | }; 273 | /* End PBXResourcesBuildPhase section */ 274 | 275 | /* Begin PBXSourcesBuildPhase section */ 276 | 6861DFF51C21308800F410C9 /* Sources */ = { 277 | isa = PBXSourcesBuildPhase; 278 | buildActionMask = 2147483647; 279 | files = ( 280 | 6861E0221C21313F00F410C9 /* SecrecyExtension.swift in Sources */, 281 | 6861E0241C21313F00F410C9 /* HMAC.swift in Sources */, 282 | 6861E0211C21313F00F410C9 /* RSA.swift in Sources */, 283 | 6861E0201C21313F00F410C9 /* AES.swift in Sources */, 284 | 6861E0231C21313F00F410C9 /* Digest.swift in Sources */, 285 | ); 286 | runOnlyForDeploymentPostprocessing = 0; 287 | }; 288 | 6861E0051C2130AB00F410C9 /* Sources */ = { 289 | isa = PBXSourcesBuildPhase; 290 | buildActionMask = 2147483647; 291 | files = ( 292 | 6861E00E1C2130AB00F410C9 /* ViewController.swift in Sources */, 293 | 6861E00C1C2130AB00F410C9 /* AppDelegate.swift in Sources */, 294 | ); 295 | runOnlyForDeploymentPostprocessing = 0; 296 | }; 297 | /* End PBXSourcesBuildPhase section */ 298 | 299 | /* Begin PBXTargetDependency section */ 300 | 68C768041C3B5CDC0029AD08 /* PBXTargetDependency */ = { 301 | isa = PBXTargetDependency; 302 | target = 6861DFF91C21308800F410C9 /* SecrecySwift */; 303 | targetProxy = 68C768031C3B5CDC0029AD08 /* PBXContainerItemProxy */; 304 | }; 305 | /* End PBXTargetDependency section */ 306 | 307 | /* Begin PBXVariantGroup section */ 308 | 6861E00F1C2130AB00F410C9 /* Main.storyboard */ = { 309 | isa = PBXVariantGroup; 310 | children = ( 311 | 6861E0101C2130AB00F410C9 /* Base */, 312 | ); 313 | name = Main.storyboard; 314 | sourceTree = ""; 315 | }; 316 | 6861E0141C2130AB00F410C9 /* LaunchScreen.storyboard */ = { 317 | isa = PBXVariantGroup; 318 | children = ( 319 | 6861E0151C2130AB00F410C9 /* Base */, 320 | ); 321 | name = LaunchScreen.storyboard; 322 | sourceTree = ""; 323 | }; 324 | /* End PBXVariantGroup section */ 325 | 326 | /* Begin XCBuildConfiguration section */ 327 | 6861E0001C21308800F410C9 /* Debug */ = { 328 | isa = XCBuildConfiguration; 329 | buildSettings = { 330 | ALWAYS_SEARCH_USER_PATHS = NO; 331 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; 332 | CLANG_CXX_LIBRARY = "libc++"; 333 | CLANG_ENABLE_MODULES = YES; 334 | CLANG_ENABLE_OBJC_ARC = YES; 335 | CLANG_WARN_BOOL_CONVERSION = YES; 336 | CLANG_WARN_CONSTANT_CONVERSION = YES; 337 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 338 | CLANG_WARN_EMPTY_BODY = YES; 339 | CLANG_WARN_ENUM_CONVERSION = YES; 340 | CLANG_WARN_INFINITE_RECURSION = YES; 341 | CLANG_WARN_INT_CONVERSION = YES; 342 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 343 | CLANG_WARN_SUSPICIOUS_MOVE = YES; 344 | CLANG_WARN_UNREACHABLE_CODE = YES; 345 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 346 | "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; 347 | COPY_PHASE_STRIP = NO; 348 | CURRENT_PROJECT_VERSION = 1; 349 | DEBUG_INFORMATION_FORMAT = dwarf; 350 | ENABLE_STRICT_OBJC_MSGSEND = YES; 351 | ENABLE_TESTABILITY = YES; 352 | GCC_C_LANGUAGE_STANDARD = gnu99; 353 | GCC_DYNAMIC_NO_PIC = NO; 354 | GCC_NO_COMMON_BLOCKS = YES; 355 | GCC_OPTIMIZATION_LEVEL = 0; 356 | GCC_PREPROCESSOR_DEFINITIONS = ( 357 | "DEBUG=1", 358 | "$(inherited)", 359 | ); 360 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 361 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 362 | GCC_WARN_UNDECLARED_SELECTOR = YES; 363 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 364 | GCC_WARN_UNUSED_FUNCTION = YES; 365 | GCC_WARN_UNUSED_VARIABLE = YES; 366 | IPHONEOS_DEPLOYMENT_TARGET = 9.2; 367 | MTL_ENABLE_DEBUG_INFO = YES; 368 | ONLY_ACTIVE_ARCH = YES; 369 | SDKROOT = iphoneos; 370 | SWIFT_OPTIMIZATION_LEVEL = "-Onone"; 371 | SWIFT_VERSION = ""; 372 | TARGETED_DEVICE_FAMILY = "1,2"; 373 | VERSIONING_SYSTEM = "apple-generic"; 374 | VERSION_INFO_PREFIX = ""; 375 | }; 376 | name = Debug; 377 | }; 378 | 6861E0011C21308800F410C9 /* Release */ = { 379 | isa = XCBuildConfiguration; 380 | buildSettings = { 381 | ALWAYS_SEARCH_USER_PATHS = NO; 382 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; 383 | CLANG_CXX_LIBRARY = "libc++"; 384 | CLANG_ENABLE_MODULES = YES; 385 | CLANG_ENABLE_OBJC_ARC = YES; 386 | CLANG_WARN_BOOL_CONVERSION = YES; 387 | CLANG_WARN_CONSTANT_CONVERSION = YES; 388 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 389 | CLANG_WARN_EMPTY_BODY = YES; 390 | CLANG_WARN_ENUM_CONVERSION = YES; 391 | CLANG_WARN_INFINITE_RECURSION = YES; 392 | CLANG_WARN_INT_CONVERSION = YES; 393 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 394 | CLANG_WARN_SUSPICIOUS_MOVE = YES; 395 | CLANG_WARN_UNREACHABLE_CODE = YES; 396 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 397 | "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; 398 | COPY_PHASE_STRIP = NO; 399 | CURRENT_PROJECT_VERSION = 1; 400 | DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; 401 | ENABLE_NS_ASSERTIONS = NO; 402 | ENABLE_STRICT_OBJC_MSGSEND = YES; 403 | GCC_C_LANGUAGE_STANDARD = gnu99; 404 | GCC_NO_COMMON_BLOCKS = YES; 405 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 406 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 407 | GCC_WARN_UNDECLARED_SELECTOR = YES; 408 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 409 | GCC_WARN_UNUSED_FUNCTION = YES; 410 | GCC_WARN_UNUSED_VARIABLE = YES; 411 | IPHONEOS_DEPLOYMENT_TARGET = 9.2; 412 | MTL_ENABLE_DEBUG_INFO = NO; 413 | SDKROOT = iphoneos; 414 | SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; 415 | SWIFT_VERSION = ""; 416 | TARGETED_DEVICE_FAMILY = "1,2"; 417 | VALIDATE_PRODUCT = YES; 418 | VERSIONING_SYSTEM = "apple-generic"; 419 | VERSION_INFO_PREFIX = ""; 420 | }; 421 | name = Release; 422 | }; 423 | 6861E0031C21308800F410C9 /* Debug */ = { 424 | isa = XCBuildConfiguration; 425 | buildSettings = { 426 | CLANG_ENABLE_MODULES = YES; 427 | "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; 428 | DEFINES_MODULE = YES; 429 | DYLIB_COMPATIBILITY_VERSION = 1; 430 | DYLIB_CURRENT_VERSION = 1; 431 | DYLIB_INSTALL_NAME_BASE = "@rpath"; 432 | INFOPLIST_FILE = SecrecySwift/Info.plist; 433 | INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; 434 | IPHONEOS_DEPLOYMENT_TARGET = 8.0; 435 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; 436 | LIBRARY_SEARCH_PATHS = ( 437 | "$(inherited)", 438 | /usr/lib/system/, 439 | ); 440 | PRODUCT_BUNDLE_IDENTIFIER = adow.secrecy; 441 | PRODUCT_MODULE_NAME = Secrecy; 442 | PRODUCT_NAME = Secrecy; 443 | SKIP_INSTALL = YES; 444 | SWIFT_INCLUDE_PATHS = CommonCrypto; 445 | SWIFT_OPTIMIZATION_LEVEL = "-Onone"; 446 | SWIFT_VERSION = 3.0; 447 | }; 448 | name = Debug; 449 | }; 450 | 6861E0041C21308800F410C9 /* Release */ = { 451 | isa = XCBuildConfiguration; 452 | buildSettings = { 453 | CLANG_ENABLE_MODULES = YES; 454 | "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; 455 | DEFINES_MODULE = YES; 456 | DYLIB_COMPATIBILITY_VERSION = 1; 457 | DYLIB_CURRENT_VERSION = 1; 458 | DYLIB_INSTALL_NAME_BASE = "@rpath"; 459 | INFOPLIST_FILE = SecrecySwift/Info.plist; 460 | INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; 461 | IPHONEOS_DEPLOYMENT_TARGET = 8.0; 462 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; 463 | LIBRARY_SEARCH_PATHS = ( 464 | "$(inherited)", 465 | /usr/lib/system/, 466 | ); 467 | PRODUCT_BUNDLE_IDENTIFIER = adow.secrecy; 468 | PRODUCT_MODULE_NAME = Secrecy; 469 | PRODUCT_NAME = Secrecy; 470 | SKIP_INSTALL = YES; 471 | SWIFT_INCLUDE_PATHS = CommonCrypto; 472 | SWIFT_VERSION = 3.0; 473 | }; 474 | name = Release; 475 | }; 476 | 6861E0191C2130AB00F410C9 /* Debug */ = { 477 | isa = XCBuildConfiguration; 478 | buildSettings = { 479 | ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; 480 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; 481 | INFOPLIST_FILE = SecrecySwiftDemo/Info.plist; 482 | IPHONEOS_DEPLOYMENT_TARGET = 8.0; 483 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; 484 | LIBRARY_SEARCH_PATHS = /usr/lib/system/; 485 | PRODUCT_BUNDLE_IDENTIFIER = adow.SecrecySwiftDemo; 486 | PRODUCT_NAME = "$(TARGET_NAME)"; 487 | SWIFT_VERSION = 3.0; 488 | }; 489 | name = Debug; 490 | }; 491 | 6861E01A1C2130AB00F410C9 /* Release */ = { 492 | isa = XCBuildConfiguration; 493 | buildSettings = { 494 | ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; 495 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; 496 | INFOPLIST_FILE = SecrecySwiftDemo/Info.plist; 497 | IPHONEOS_DEPLOYMENT_TARGET = 8.0; 498 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; 499 | LIBRARY_SEARCH_PATHS = /usr/lib/system/; 500 | PRODUCT_BUNDLE_IDENTIFIER = adow.SecrecySwiftDemo; 501 | PRODUCT_NAME = "$(TARGET_NAME)"; 502 | SWIFT_VERSION = 3.0; 503 | }; 504 | name = Release; 505 | }; 506 | /* End XCBuildConfiguration section */ 507 | 508 | /* Begin XCConfigurationList section */ 509 | 6861DFF41C21308800F410C9 /* Build configuration list for PBXProject "SecrecySwift" */ = { 510 | isa = XCConfigurationList; 511 | buildConfigurations = ( 512 | 6861E0001C21308800F410C9 /* Debug */, 513 | 6861E0011C21308800F410C9 /* Release */, 514 | ); 515 | defaultConfigurationIsVisible = 0; 516 | defaultConfigurationName = Release; 517 | }; 518 | 6861E0021C21308800F410C9 /* Build configuration list for PBXNativeTarget "SecrecySwift" */ = { 519 | isa = XCConfigurationList; 520 | buildConfigurations = ( 521 | 6861E0031C21308800F410C9 /* Debug */, 522 | 6861E0041C21308800F410C9 /* Release */, 523 | ); 524 | defaultConfigurationIsVisible = 0; 525 | defaultConfigurationName = Release; 526 | }; 527 | 6861E0181C2130AB00F410C9 /* Build configuration list for PBXNativeTarget "SecrecySwiftDemo" */ = { 528 | isa = XCConfigurationList; 529 | buildConfigurations = ( 530 | 6861E0191C2130AB00F410C9 /* Debug */, 531 | 6861E01A1C2130AB00F410C9 /* Release */, 532 | ); 533 | defaultConfigurationIsVisible = 0; 534 | defaultConfigurationName = Release; 535 | }; 536 | /* End XCConfigurationList section */ 537 | }; 538 | rootObject = 6861DFF11C21308800F410C9 /* Project object */; 539 | } 540 | -------------------------------------------------------------------------------- /SecrecySwift.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /SecrecySwift.xcodeproj/xcshareddata/xcschemes/SecrecySwift.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 32 | 33 | 34 | 35 | 45 | 46 | 52 | 53 | 54 | 55 | 56 | 57 | 63 | 64 | 70 | 71 | 72 | 73 | 75 | 76 | 79 | 80 | 81 | -------------------------------------------------------------------------------- /SecrecySwift.xcodeproj/xcuserdata/reynoldqin.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | SecrecySwift.xcscheme_^#shared#^_ 8 | 9 | orderHint 10 | 0 11 | 12 | SecrecySwiftDemo.xcscheme 13 | 14 | orderHint 15 | 1 16 | 17 | 18 | SuppressBuildableAutocreation 19 | 20 | 6861DFF91C21308800F410C9 21 | 22 | primary 23 | 24 | 25 | 6861E0081C2130AB00F410C9 26 | 27 | primary 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /SecrecySwift/AES.swift: -------------------------------------------------------------------------------- 1 | // 2 | // AES.swift 3 | // TestCommonCrypto 4 | // 5 | // Created by 秦 道平 on 15/12/11. 6 | // Copyright © 2015年 秦 道平. All rights reserved. 7 | // 8 | // key 满足 16(AES128)/24(AES192)/32(AES256) 位 9 | // 只支持 ECB/CBC 模式, cbc 模式必须要 IV,只支持 PKCS7Padding 10 | // raw 的长度必须大于3个字符 11 | 12 | import Foundation 13 | import CommonCrypto 14 | 15 | 16 | extension Data { 17 | // MARK: cbc 18 | fileprivate func aesCBC(_ operation:CCOperation,key:String, iv:String? = nil) -> Data? { 19 | guard [16,24,32].contains(key.lengthOfBytes(using: String.Encoding.utf8)) else { 20 | return nil 21 | } 22 | let input_bytes = self.arrayOfBytes() 23 | let key_bytes = key.bytes 24 | var encrypt_length = Swift.max(input_bytes.count * 2, 16) 25 | var encrypt_bytes = [UInt8](repeating: 0, 26 | count: encrypt_length) 27 | 28 | let iv_bytes = (iv != nil) ? iv?.bytes : nil 29 | let status = CCCrypt(UInt32(operation), 30 | UInt32(kCCAlgorithmAES128), 31 | UInt32(kCCOptionPKCS7Padding), 32 | key_bytes, 33 | key.lengthOfBytes(using: String.Encoding.utf8), 34 | iv_bytes, 35 | input_bytes, 36 | input_bytes.count, 37 | &encrypt_bytes, 38 | encrypt_bytes.count, 39 | &encrypt_length) 40 | if status == Int32(kCCSuccess) { 41 | return Data(bytes: UnsafePointer(encrypt_bytes), count: encrypt_length) 42 | } 43 | return nil 44 | } 45 | /// Encrypt data in CBC Mode, iv will be filled with zero if not specificed 46 | public func aesCBCEncrypt(_ key:String,iv:String? = nil) -> Data? { 47 | return aesCBC(UInt32(kCCEncrypt), key: key, iv: iv) 48 | } 49 | /// Decrypt data in CBC Mode ,iv will be filled with zero if not specificed 50 | public func aesCBCDecrypt(_ key:String,iv:String? = nil)->Data?{ 51 | return aesCBC(UInt32(kCCDecrypt), key: key, iv: iv) 52 | } 53 | // MARK: ecb 54 | fileprivate func aesEBC(_ operation:CCOperation, key:String) -> Data? { 55 | guard [16,24,32].contains(key.lengthOfBytes(using: String.Encoding.utf8)) else { 56 | return nil 57 | } 58 | let input_bytes = self.arrayOfBytes() 59 | let key_bytes = key.bytes 60 | var encrypt_length = Swift.max(input_bytes.count * 2, 16) 61 | var encrypt_bytes = [UInt8](repeating: 0, 62 | count: encrypt_length) 63 | let status = CCCrypt(UInt32(operation), 64 | UInt32(kCCAlgorithmAES128), 65 | UInt32(kCCOptionPKCS7Padding + kCCOptionECBMode), 66 | key_bytes, 67 | key.lengthOfBytes(using: String.Encoding.utf8), 68 | nil, 69 | input_bytes, 70 | input_bytes.count, 71 | &encrypt_bytes, 72 | encrypt_bytes.count, 73 | &encrypt_length) 74 | if status == Int32(kCCSuccess) { 75 | return Data(bytes: UnsafePointer(encrypt_bytes), count: encrypt_length) 76 | } 77 | return nil 78 | } 79 | /// Encrypt data in EBC Mode 80 | public func aesEBCEncrypt(_ key:String) -> Data? { 81 | return aesEBC(UInt32(kCCEncrypt), key: key) 82 | 83 | } 84 | /// Decrypt data in EBC Mode 85 | public func aesEBCDecrypt(_ key:String) -> Data? { 86 | return aesEBC(UInt32(kCCDecrypt), key: key) 87 | } 88 | } 89 | extension String{ 90 | // MARK: cbc 91 | /// Encrypt string in CBC mode, iv will be filled with Zero if not specificed 92 | public func aesCBCEncrypt(_ key:String,iv:String? = nil) -> Data? { 93 | let data = self.data(using: String.Encoding.utf8) 94 | // print(data!.hexString) 95 | return data?.aesCBCEncrypt(key, iv: iv) 96 | } 97 | /// Decrypt a hexadecimal string in CBC Mode, iv will be filled with Zero if not specificed 98 | public func aesCBCDecryptFromHex(_ key:String,iv:String? = nil) ->String?{ 99 | let data = self.dataFromHexadecimalString() 100 | guard let raw_data = data?.aesCBCDecrypt(key, iv: iv) else{ 101 | return nil 102 | } 103 | // print(raw_data.hexString) 104 | return String(data: raw_data, encoding: String.Encoding.utf8) 105 | } 106 | /// Decrypt a base64 string in CBC mode, iv will be filled with Zero if not specificed 107 | public func aesCBCDecryptFromBase64(_ key:String, iv:String? = nil) ->String? { 108 | let data = Data(base64Encoded: self, options: NSData.Base64DecodingOptions()) 109 | guard let raw_data = data?.aesCBCDecrypt(key, iv: iv) else{ 110 | return nil 111 | } 112 | return String(data: raw_data, encoding: String.Encoding.utf8) 113 | } 114 | // MARK: ebc 115 | /// Encrypt a string in EBC Mode 116 | public func aesEBCEncrypt(_ key:String) -> Data? { 117 | let data = self.data(using: String.Encoding.utf8) 118 | return data?.aesEBCEncrypt(key) 119 | } 120 | /// Decrypt a hexadecimal string in EBC Mode 121 | public func aesEBCDecryptFromHex(_ key:String) -> String? { 122 | let data = self.dataFromHexadecimalString() 123 | guard let raw_data = data?.aesEBCDecrypt(key) else { 124 | return nil 125 | } 126 | return String(data: raw_data, encoding: String.Encoding.utf8) 127 | } 128 | /// Decrypt a base64 string in EBC Mode 129 | public func aesEBCDecryptFromBase64(_ key:String) -> String? { 130 | let data = Data(base64Encoded: self, options: NSData.Base64DecodingOptions()) 131 | guard let raw_data = data?.aesEBCDecrypt(key) else { 132 | return nil 133 | } 134 | return String(data: raw_data, encoding: String.Encoding.utf8) 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /SecrecySwift/Digest.swift: -------------------------------------------------------------------------------- 1 | // 2 | // SHA.swift 3 | // SwiftSSL 4 | // 5 | // Forked from: https://github.com/SwiftP2P/SwiftSSL/blob/master/SwiftSSL/Digest.swift 6 | // 7 | // Created by 0day on 14/10/7. 8 | // Copyright (c) 2014年 SwiftP2P. All rights reserved. 9 | // 10 | 11 | 12 | import Foundation 13 | import CommonCrypto 14 | 15 | public typealias DigestAlgorithmClosure = (_ data: UnsafePointer, _ dataLength: UInt32) -> [UInt8] 16 | 17 | public enum DigestAlgorithm: CustomStringConvertible { 18 | case md2, md4, md5, sha1, sha224, sha256, sha384, sha512 19 | 20 | func progressClosure() -> DigestAlgorithmClosure { 21 | var closure: DigestAlgorithmClosure? 22 | 23 | switch self { 24 | case .md2: 25 | closure = { 26 | var hash = [UInt8](repeating: 0, count: self.digestLength()) 27 | CC_MD2($0, $1, &hash) 28 | 29 | return hash 30 | } 31 | case .md4: 32 | closure = { 33 | var hash = [UInt8](repeating: 0, count: self.digestLength()) 34 | CC_MD4($0, $1, &hash) 35 | 36 | return hash 37 | } 38 | case .md5: 39 | closure = { 40 | var hash = [UInt8](repeating: 0, count: self.digestLength()) 41 | CC_MD5($0, $1, &hash) 42 | 43 | return hash 44 | } 45 | case .sha1: 46 | closure = { 47 | var hash = [UInt8](repeating: 0, count: self.digestLength()) 48 | CC_SHA1($0, $1, &hash) 49 | 50 | return hash 51 | } 52 | case .sha224: 53 | closure = { 54 | var hash = [UInt8](repeating: 0, count: self.digestLength()) 55 | CC_SHA224($0, $1, &hash) 56 | 57 | return hash 58 | } 59 | case .sha256: 60 | closure = { 61 | var hash = [UInt8](repeating: 0, count: self.digestLength()) 62 | CC_SHA256($0, $1, &hash) 63 | 64 | return hash 65 | } 66 | case .sha384: 67 | closure = { 68 | var hash = [UInt8](repeating: 0, count: self.digestLength()) 69 | CC_SHA384($0, $1, &hash) 70 | 71 | return hash 72 | } 73 | case .sha512: 74 | closure = { 75 | var hash = [UInt8](repeating: 0, count: self.digestLength()) 76 | CC_SHA512($0, $1, &hash) 77 | 78 | return hash 79 | } 80 | } 81 | return closure! 82 | } 83 | 84 | func digestLength() -> Int { 85 | var result: CInt = 0 86 | switch self { 87 | case .md2: 88 | result = CC_MD2_DIGEST_LENGTH 89 | case .md4: 90 | result = CC_MD4_DIGEST_LENGTH 91 | case .md5: 92 | result = CC_MD5_DIGEST_LENGTH 93 | case .sha1: 94 | result = CC_SHA1_DIGEST_LENGTH 95 | case .sha224: 96 | result = CC_SHA224_DIGEST_LENGTH 97 | case .sha256: 98 | result = CC_SHA256_DIGEST_LENGTH 99 | case .sha384: 100 | result = CC_SHA384_DIGEST_LENGTH 101 | case .sha512: 102 | result = CC_SHA512_DIGEST_LENGTH 103 | } 104 | return Int(result) 105 | } 106 | 107 | public var description: String { 108 | get { 109 | switch self { 110 | case .md2: 111 | return "Digest.MD2" 112 | case .md4: 113 | return "Digest.MD4" 114 | case .md5: 115 | return "Digest.MD5" 116 | case .sha1: 117 | return "Digest.SHA1" 118 | case .sha224: 119 | return "Digest.SHA224" 120 | case .sha256: 121 | return "Digest.SHA256" 122 | case .sha384: 123 | return "Digest.SHA384" 124 | case .sha512: 125 | return "Digest.SHA512" 126 | } 127 | } 128 | } 129 | } 130 | 131 | extension String { 132 | /// Digest to an array of UInt8 133 | public func digestBytes(_ algorithm:DigestAlgorithm)->[UInt8]{ 134 | let data = self.data(using: String.Encoding.utf8) 135 | return data!.digestBytes(algorithm) 136 | } 137 | /// Digest with an algorithm 138 | public func digestData(_ algorithm:DigestAlgorithm)->Data{ 139 | let data = self.data(using: String.Encoding.utf8) 140 | return data!.digestData(algorithm) 141 | } 142 | /// Digest with an algorithm to a hexadecimal string 143 | public func digestHex(_ algorithm:DigestAlgorithm)->String{ 144 | let data = self.data(using: String.Encoding.utf8) 145 | return data!.digestHex(algorithm) 146 | } 147 | /// Digest with an algorithm to a base64 string 148 | public func digestBase64(_ algorithm:DigestAlgorithm)->String{ 149 | let data = self.data(using: String.Encoding.utf8) 150 | return data!.digestBase64(algorithm) 151 | } 152 | } 153 | 154 | extension Data { 155 | /// Digest data to an array of UInt8 156 | public func digestBytes(_ algorithm:DigestAlgorithm)->[UInt8]{ 157 | let string = (self as NSData).bytes.bindMemory(to: UInt8.self, capacity: self.count) 158 | let stringLength = UInt32(self.count) 159 | 160 | let closure = algorithm.progressClosure() 161 | 162 | let bytes = closure(string, stringLength) 163 | return bytes 164 | } 165 | /// Digest data with an algorithm 166 | public func digestData(_ algorithm:DigestAlgorithm)->Data{ 167 | let bytes = self.digestBytes(algorithm) 168 | return Data(bytes: UnsafePointer(bytes), count: bytes.count) 169 | } 170 | /// Digest data with an algorithm to a hexadecimal string 171 | public func digestHex(_ algorithm:DigestAlgorithm)->String{ 172 | let digestLength = algorithm.digestLength() 173 | let bytes = self.digestBytes(algorithm) 174 | var hashString: String = "" 175 | for i in 0..String{ 182 | let data = self.digestData(algorithm) 183 | return data.base64String 184 | } 185 | } 186 | -------------------------------------------------------------------------------- /SecrecySwift/HMAC.swift: -------------------------------------------------------------------------------- 1 | // 2 | // SHA.swift 3 | // SwiftSSL 4 | // 5 | // Forked from: https://github.com/SwiftP2P/SwiftSSL/blob/master/SwiftSSL/HMAC.swift 6 | // 7 | // Created by 0day on 14/10/6. 8 | // Copyright (c) 2014年 SwiftP2P. All rights reserved. 9 | // 10 | 11 | import Foundation 12 | import CommonCrypto 13 | 14 | // Base: http://stackoverflow.com/a/24411522/313633 15 | public enum HMACAlgorithm: CustomStringConvertible { 16 | case md5, sha1, sha224, sha256, sha384, sha512 17 | 18 | func toCCEnum() -> CCHmacAlgorithm { 19 | var result: Int = 0 20 | switch self { 21 | case .md5: 22 | result = kCCHmacAlgMD5 23 | case .sha1: 24 | result = kCCHmacAlgSHA1 25 | case .sha224: 26 | result = kCCHmacAlgSHA224 27 | case .sha256: 28 | result = kCCHmacAlgSHA256 29 | case .sha384: 30 | result = kCCHmacAlgSHA384 31 | case .sha512: 32 | result = kCCHmacAlgSHA512 33 | } 34 | return CCHmacAlgorithm(result) 35 | } 36 | 37 | func digestLength() -> Int { 38 | var result: CInt = 0 39 | switch self { 40 | case .md5: 41 | result = CC_MD5_DIGEST_LENGTH 42 | case .sha1: 43 | result = CC_SHA1_DIGEST_LENGTH 44 | case .sha224: 45 | result = CC_SHA224_DIGEST_LENGTH 46 | case .sha256: 47 | result = CC_SHA256_DIGEST_LENGTH 48 | case .sha384: 49 | result = CC_SHA384_DIGEST_LENGTH 50 | case .sha512: 51 | result = CC_SHA512_DIGEST_LENGTH 52 | } 53 | return Int(result) 54 | } 55 | 56 | public var description: String { 57 | get { 58 | switch self { 59 | case .md5: 60 | return "HMAC.MD5" 61 | case .sha1: 62 | return "HMAC.SHA1" 63 | case .sha224: 64 | return "HMAC.SHA224" 65 | case .sha256: 66 | return "HMAC.SHA256" 67 | case .sha384: 68 | return "HMAC.SHA384" 69 | case .sha512: 70 | return "HMAC.SHA512" 71 | } 72 | } 73 | } 74 | } 75 | 76 | extension String { 77 | /// Sign to an array ot UInt8 78 | public func signBytes(_ algorithm:HMACAlgorithm, key:String) -> [UInt8] { 79 | let data = self.data(using: String.Encoding.utf8) 80 | return data!.signBytes(algorithm, key: key) 81 | } 82 | /// Sign with algorithm 83 | public func signData(_ algorithm:HMACAlgorithm, key:String) -> Data { 84 | let data = self.data(using: String.Encoding.utf8) 85 | return data!.signData(algorithm, key: key) 86 | } 87 | /// Sign and hexadecimal string will be returned 88 | public func signHex(_ algorithm:HMACAlgorithm, key:String)->String { 89 | let data = self.data(using: String.Encoding.utf8) 90 | return data!.signHex(algorithm, key: key) 91 | } 92 | /// Sign and base64 string will be returned 93 | public func signBase64(_ algorithm:HMACAlgorithm, key:String) -> String { 94 | let data = self.data(using: String.Encoding.utf8) 95 | return data!.signBase64(algorithm, key: key) 96 | } 97 | } 98 | 99 | extension Data { 100 | /// Sign data to an array of UInt8 101 | public func signBytes(_ algorithm:HMACAlgorithm, key:String) -> [UInt8]{ 102 | let string = (self as NSData).bytes.bindMemory(to: UInt8.self, capacity: self.count) 103 | let stringLength = self.count 104 | let digestLength = algorithm.digestLength() 105 | let keyString = key.cString(using: String.Encoding.utf8)! 106 | let keyLength = key.lengthOfBytes(using: String.Encoding.utf8) 107 | var result = [UInt8](repeating: 0, count: digestLength) 108 | CCHmac(algorithm.toCCEnum(), keyString, keyLength, string, stringLength, &result) 109 | return result 110 | } 111 | /// Sign with an algorithm 112 | public func signData(_ algorithm:HMACAlgorithm, key:String) -> Data { 113 | let bytes = self.signBytes(algorithm, key: key) 114 | let data = Data(bytes: UnsafePointer(bytes), count: bytes.count) 115 | return data 116 | } 117 | /// Sign a data and export to a hexadecimal string 118 | public func signHex(_ algorithm:HMACAlgorithm, key:String)->String { 119 | let bytes = self.signBytes(algorithm, key: key) 120 | let digestLength = bytes.count 121 | var hash: String = "" 122 | for i in 0.. String { 129 | let data = self.signData(algorithm, key: key) 130 | return data.base64String 131 | } 132 | 133 | } 134 | -------------------------------------------------------------------------------- /SecrecySwift/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 | FMWK 17 | CFBundleShortVersionString 18 | 0.4.2 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | $(CURRENT_PROJECT_VERSION) 23 | NSPrincipalClass 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /SecrecySwift/RSA.swift: -------------------------------------------------------------------------------- 1 | // 2 | // RSA.swift 3 | // TestCommonCrypto 4 | // 5 | // Created by 秦 道平 on 15/12/15. 6 | // Copyright © 2015年 秦 道平. All rights reserved. 7 | // 8 | 9 | import Foundation 10 | import Security 11 | public enum RSAAlgorithm:Int { 12 | case sha1 = 0, sha224, sha256, sha384, sha512, md2, md5 13 | public var padding:SecPadding { 14 | switch self { 15 | case .sha1: 16 | return SecPadding.PKCS1SHA1 17 | case .sha224: 18 | return SecPadding.PKCS1SHA224 19 | case .sha256: 20 | return SecPadding.PKCS1SHA256 21 | case .sha384: 22 | return SecPadding.PKCS1SHA384 23 | case .sha512: 24 | return SecPadding.PKCS1SHA512 25 | case .md2: 26 | // return SecPadding.PKCS1MD2 27 | return SecPadding.PKCS1 28 | case .md5: 29 | // return SecPadding.PKCS1MD5 30 | return SecPadding.PKCS1 31 | } 32 | } 33 | public var digestAlgorithm:DigestAlgorithm { 34 | switch self { 35 | case .sha1: 36 | return DigestAlgorithm.sha1 37 | case .sha224: 38 | return DigestAlgorithm.sha224 39 | case .sha256: 40 | return DigestAlgorithm.sha256 41 | case .sha384: 42 | return DigestAlgorithm.sha384 43 | case .sha512: 44 | return DigestAlgorithm.sha512 45 | case .md2: 46 | return DigestAlgorithm.md2 47 | case .md5: 48 | return DigestAlgorithm.md5 49 | } 50 | } 51 | } 52 | // MARK: - func 53 | /// encrypt 54 | private func rsa_encrypt(_ inputData:Data, withKey key:SecKey) -> Data?{ 55 | guard inputData.count > 0 && inputData.count < SecKeyGetBlockSize(key) - 11 else { 56 | return nil 57 | } 58 | let key_size = SecKeyGetBlockSize(key) 59 | var encrypt_bytes = [UInt8](repeating: 0, count: key_size) 60 | var output_size : Int = key_size 61 | if SecKeyEncrypt(key, SecPadding.PKCS1, 62 | inputData.arrayOfBytes(), inputData.count, 63 | &encrypt_bytes, &output_size) == errSecSuccess { 64 | return Data(bytes: UnsafePointer(encrypt_bytes), count: output_size) 65 | } 66 | return nil 67 | } 68 | /// decrypt 69 | private func rsa_decrypt(_ inputData:Data, withKey key:SecKey) -> Data? { 70 | guard inputData.count == SecKeyGetBlockSize(key) else { 71 | return nil 72 | } 73 | let key_size = SecKeyGetBlockSize(key) 74 | var decrypt_bytes = [UInt8](repeating: 0, count: key_size) 75 | var output_size: Int = key_size 76 | if SecKeyDecrypt(key, SecPadding.PKCS1, inputData.arrayOfBytes(), inputData.count, &decrypt_bytes, &output_size) == errSecSuccess { 77 | return Data(bytes: UnsafePointer(decrypt_bytes), count: output_size) 78 | } 79 | else { 80 | return nil 81 | } 82 | } 83 | /// sign 84 | private func rsa_sign(_ inputData:Data,withAlgorithm algorithm:RSAAlgorithm, withKey key:SecKey) -> Data? { 85 | let digestInputData = inputData.digestData(algorithm.digestAlgorithm) 86 | // print("digestInput:\(digestInputData.hexString)") 87 | guard digestInputData.count > 0 && digestInputData.count < SecKeyGetBlockSize(key) - 11 else { 88 | return nil 89 | } 90 | let key_size = SecKeyGetBlockSize(key) 91 | var sign_bytes = [UInt8](repeating: 0, count: key_size) 92 | var sign_size : Int = key_size 93 | let result = SecKeyRawSign(key, algorithm.padding, digestInputData.arrayOfBytes(), digestInputData.count, &sign_bytes, &sign_size) 94 | // print("result:\(result)") 95 | if result == errSecSuccess { 96 | return Data(bytes: UnsafePointer(sign_bytes), count: sign_size) 97 | } 98 | return nil 99 | } 100 | /// verify 101 | private func rsa_verify(_ inputData:Data, signedData:Data, 102 | withAlgorithm algorithm:RSAAlgorithm, whthKey key:SecKey) -> Bool { 103 | let digestInputData = inputData.digestData(algorithm.digestAlgorithm) 104 | // print("digestInput:\(digestInputData.hexString)") 105 | guard digestInputData.count > 0 && digestInputData.count < SecKeyGetBlockSize(key) - 11 else { 106 | return false 107 | } 108 | let result = SecKeyRawVerify(key, algorithm.padding, digestInputData.arrayOfBytes(), digestInputData.count, signedData.arrayOfBytes(), signedData.count) 109 | return result == errSecSuccess 110 | } 111 | /// publicKey 112 | private func rsa_publickey_from_data(_ keyData:Data) -> SecKey?{ 113 | if let certificate = SecCertificateCreateWithData(kCFAllocatorDefault, keyData as CFData) { 114 | let policy = SecPolicyCreateBasicX509() 115 | var trust : SecTrust? 116 | if SecTrustCreateWithCertificates(certificate, policy, &trust) == errSecSuccess { 117 | var trustResultType : SecTrustResultType = SecTrustResultType.invalid 118 | if SecTrustEvaluate(trust!, &trustResultType) == errSecSuccess { 119 | return SecTrustCopyPublicKey(trust!) 120 | } 121 | } 122 | 123 | } 124 | return nil 125 | 126 | } 127 | /// privateKey 128 | private func rsa_privatekey_from_data(_ keyData:Data, withPassword password:String) -> SecKey? { 129 | var privateKey: SecKey? = nil 130 | let options : [String:String] = [kSecImportExportPassphrase as String:password] 131 | var items : CFArray? 132 | if SecPKCS12Import(keyData as CFData, options as CFDictionary, &items) == errSecSuccess { 133 | // print("items:\(CFArrayGetCount(items))") 134 | if CFArrayGetCount(items) > 0 { 135 | let d = unsafeBitCast(CFArrayGetValueAtIndex(items, 0),to: CFDictionary.self) 136 | let k = Unmanaged.passUnretained(kSecImportItemIdentity as NSString).toOpaque() 137 | let v = CFDictionaryGetValue(d, k) 138 | // print("identity:\(identity)") 139 | let secIdentity = unsafeBitCast(v, to: SecIdentity.self) 140 | // print("secIdentity:\(secIdentity)") 141 | if SecIdentityCopyPrivateKey(secIdentity, &privateKey) == errSecSuccess { 142 | return privateKey 143 | } 144 | } 145 | } 146 | 147 | return nil 148 | } 149 | 150 | // MARK: - RSA 151 | public struct RSA { 152 | fileprivate let publicKey:SecKey! 153 | fileprivate let privateKey:SecKey! 154 | // MARK: init 155 | /// PublicKey must be in .der format and private must be in .p12 format 156 | public init(publicKey:SecKey!, privateKey:SecKey!){ 157 | self.publicKey = publicKey 158 | self.privateKey = privateKey 159 | } 160 | public init(dataOfPublicKey publicKeyData:Data, 161 | dataOfPrivateKey privateKeyData:Data, 162 | withPasswordOfPrivateKey password:String = ""){ 163 | self.publicKey = rsa_publickey_from_data(publicKeyData)! 164 | self.privateKey = rsa_privatekey_from_data(privateKeyData, withPassword: password)! 165 | } 166 | /* Generate RSA instance from file of public key and private key 167 | - parameter publicKeyFilename: filename of publicKey 168 | - parameter privateKeyFilename: filename of privateKey 169 | - parameter password: password or empty if not set 170 | - returns: RSA instance if succeed or nil if failed 171 | */ 172 | public init?(filenameOfPulbicKey publicKeyFilename:String, 173 | filenameOfPrivateKey privateKeyFilename:String, withPasswordOfPrivateKey password:String = ""){ 174 | let publicKeyData = try? Data(contentsOf: URL(fileURLWithPath: publicKeyFilename)) 175 | let privateKeyData = try? Data(contentsOf: URL(fileURLWithPath: privateKeyFilename)) 176 | guard let _publicKeyData = publicKeyData, let _privateKeyData = privateKeyData else { 177 | return nil 178 | } 179 | self.publicKey = rsa_publickey_from_data(_publicKeyData) 180 | self.privateKey = rsa_privatekey_from_data(_privateKeyData, withPassword: password)! 181 | } 182 | } 183 | // MARK: - encrypt 184 | extension RSA { 185 | /// Encrypt with privateKey 186 | public func encrypt(_ data:Data) -> Data? { 187 | return rsa_encrypt(data, withKey: self.publicKey) 188 | } 189 | /// Decrypt with publicKey 190 | public func decrypt(_ data:Data) -> Data? { 191 | return rsa_decrypt(data, withKey: self.privateKey) 192 | } 193 | /// Decrypt a hexadecimal string with publicKey 194 | public func decrypt(fromHexString hexString:String) -> Data? { 195 | let data = hexString.dataFromHexadecimalString() 196 | guard let _data = data else { 197 | return nil 198 | } 199 | return self.decrypt(_data as Data) 200 | } 201 | /// Decrypt a base64 string with publicKey 202 | public func decrypt(fromBase64String base64String:String) -> Data? { 203 | let data = Data(base64Encoded: base64String, options: NSData.Base64DecodingOptions()) 204 | guard let _data = data else { 205 | return nil 206 | } 207 | return self.decrypt(_data) 208 | } 209 | } 210 | // MARK: - sign 211 | extension RSA { 212 | /// Sign data with digest algorithm 213 | public func sign(_ algorithm:RSAAlgorithm,inputData:Data) -> Data? { 214 | return rsa_sign(inputData, withAlgorithm: algorithm, withKey: self.privateKey) 215 | } 216 | /// Verify signature with algorithm 217 | public func verify(_ algorithm:RSAAlgorithm,inputData:Data, signedData:Data) -> Bool { 218 | return rsa_verify(inputData, signedData: signedData, withAlgorithm: algorithm, whthKey: self.publicKey) 219 | } 220 | } 221 | -------------------------------------------------------------------------------- /SecrecySwift/SecrecyExtension.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Extension.swift 3 | // TestCommonCrypto 4 | // 5 | // Created by 秦 道平 on 15/12/11. 6 | // Copyright © 2015年 秦 道平. All rights reserved. 7 | 8 | import Foundation 9 | 10 | /** 11 | * Index 12 | */ 13 | extension Int { 14 | public subscript(digitIndex: Int) -> Int { 15 | var decimalBase = 1 16 | for _ in 1...digitIndex { 17 | decimalBase *= 10 18 | } 19 | return (self / decimalBase) % 10 20 | } 21 | } 22 | 23 | extension UInt { 24 | public subscript(digitIndex: Int) -> UInt { 25 | var decimalBase:UInt = 1 26 | for _ in 1...digitIndex { 27 | decimalBase *= 10 28 | } 29 | return (self / decimalBase) % 10 30 | } 31 | } 32 | 33 | extension UInt8 { 34 | public subscript(digitIndex: Int) -> UInt8 { 35 | var decimalBase:UInt8 = 1 36 | for _ in 1...digitIndex { 37 | decimalBase *= 10 38 | } 39 | return (self / decimalBase) % 10 40 | } 41 | } 42 | extension Data { 43 | public func hexadecimalString() -> String { 44 | let string = NSMutableString(capacity: count * 2) 45 | var byte: UInt8 = 0 46 | for i in 0 ..< count { 47 | copyBytes(to: &byte, from: i.. [UInt8] { 61 | let count = self.count / MemoryLayout.size 62 | var bytesArray = [UInt8](repeating: 0, count: count) 63 | (self as NSData).getBytes(&bytesArray, length:count * MemoryLayout.size) 64 | return bytesArray 65 | } 66 | } 67 | extension String { 68 | /// Array of UInt8 69 | public var arrayOfBytes:[UInt8] { 70 | let data = self.data(using: String.Encoding.utf8)! 71 | return data.arrayOfBytes() 72 | } 73 | public var bytes:UnsafeRawPointer{ 74 | let data = self.data(using: String.Encoding.utf8)! 75 | return (data as NSData).bytes 76 | } 77 | /// Get data from hexadecimal string 78 | func dataFromHexadecimalString() -> Data? { 79 | let trimmedString = self.trimmingCharacters(in: CharacterSet(charactersIn: "<> ")).replacingOccurrences(of: " ", with: "") 80 | 81 | // make sure the cleaned up string consists solely of hex digits, and that we have even number of them 82 | guard let regex = try? NSRegularExpression(pattern: "^[0-9a-f]*$", options: NSRegularExpression.Options.caseInsensitive) else{ 83 | return nil 84 | } 85 | let trimmedStringLength = trimmedString.lengthOfBytes(using: String.Encoding.utf8) 86 | let found = regex.firstMatch(in: trimmedString, options: NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, trimmedStringLength)) 87 | if found == nil || found?.range.location == NSNotFound || trimmedStringLength % 2 != 0 { 88 | return nil 89 | } 90 | 91 | // everything ok, so now let's build NSData 92 | 93 | // let data = NSMutableData(capacity: trimmedStringLength / 2) 94 | 95 | var data = Data(capacity: trimmedStringLength / 2) 96 | 97 | for index in trimmedString.characters.indices { 98 | let next_index = trimmedString.index(after: index) 99 | let byteString = trimmedString.substring(with: index ..< next_index) 100 | let num = UInt8(byteString.withCString { strtoul($0, nil, 16) }) 101 | // data.append([num] as [UInt8], length: 1) 102 | data.append(num) 103 | } 104 | 105 | // return data as Data? 106 | return data 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /SecrecySwift/SecrecySwift.h: -------------------------------------------------------------------------------- 1 | // 2 | // SecrecySwift.h 3 | // SecrecySwift 4 | // 5 | // Created by 秦 道平 on 15/12/16. 6 | // Copyright © 2015年 秦 道平. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | //! Project version number for SecrecySwift. 12 | FOUNDATION_EXPORT double SecrecySwiftVersionNumber; 13 | 14 | //! Project version string for SecrecySwift. 15 | FOUNDATION_EXPORT const unsigned char SecrecySwiftVersionString[]; 16 | 17 | // In this header, you should import all the public headers of your framework using statements like #import 18 | 19 | 20 | -------------------------------------------------------------------------------- /SecrecySwiftDemo/AppDelegate.swift: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.swift 3 | // SecrecySwiftDemo 4 | // 5 | // Created by 秦 道平 on 15/12/16. 6 | // Copyright © 2015年 秦 道平. All rights reserved. 7 | // 8 | 9 | import UIKit 10 | 11 | @UIApplicationMain 12 | class AppDelegate: UIResponder, UIApplicationDelegate { 13 | 14 | var window: UIWindow? 15 | 16 | 17 | func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { 18 | // Override point for customization after application launch. 19 | return true 20 | } 21 | 22 | func applicationWillResignActive(_ application: UIApplication) { 23 | // 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. 24 | // 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. 25 | } 26 | 27 | func applicationDidEnterBackground(_ application: UIApplication) { 28 | // 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. 29 | // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 30 | } 31 | 32 | func applicationWillEnterForeground(_ application: UIApplication) { 33 | // 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. 34 | } 35 | 36 | func applicationDidBecomeActive(_ application: UIApplication) { 37 | // 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. 38 | } 39 | 40 | func applicationWillTerminate(_ application: UIApplication) { 41 | // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. 42 | } 43 | 44 | 45 | } 46 | 47 | -------------------------------------------------------------------------------- /SecrecySwiftDemo/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 | } -------------------------------------------------------------------------------- /SecrecySwiftDemo/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 | -------------------------------------------------------------------------------- /SecrecySwiftDemo/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 | -------------------------------------------------------------------------------- /SecrecySwiftDemo/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 | -------------------------------------------------------------------------------- /SecrecySwiftDemo/ViewController.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ViewController.swift 3 | // TestCommonCrypto 4 | // 5 | // Created by 秦 道平 on 15/12/10. 6 | // Copyright © 2015年 秦 道平. All rights reserved. 7 | // 8 | 9 | import UIKit 10 | import Secrecy 11 | 12 | class ViewController: UIViewController { 13 | 14 | override func viewDidLoad() { 15 | super.viewDidLoad() 16 | // Do any additional setup after loading the view, typically from a nib. 17 | test_aes() 18 | test_rsa() 19 | test_rsa_signature() 20 | 21 | 22 | } 23 | 24 | override func didReceiveMemoryWarning() { 25 | super.didReceiveMemoryWarning() 26 | // Dispose of any resources that can be recreated. 27 | } 28 | } 29 | extension ViewController { 30 | fileprivate func test_rsa(){ 31 | let path_public = Bundle.main.path(forResource: "cert", ofType: "der")! 32 | let path_private = Bundle.main.path(forResource: "cert", ofType: "p12")! 33 | let raw = "0123456789abcdefg" 34 | let raw_data = raw.data(using: String.Encoding.utf8)! 35 | let rsa = RSA(filenameOfPulbicKey: path_public, filenameOfPrivateKey: path_private) 36 | guard let _rsa = rsa else { 37 | return 38 | } 39 | let encrypt_data = _rsa.encrypt(raw_data) 40 | // let hex_string = encrypt_data!.hexString 41 | // print(hex_string) 42 | // let old_data = _rsa.decrypt(fromHexString: hex_string) 43 | let base64_string = encrypt_data!.base64String 44 | print(base64_string) 45 | let old_data = _rsa.decrypt(fromBase64String: base64_string) 46 | let old_string = String(data: old_data!, encoding: String.Encoding.utf8) 47 | print("old_string:\(old_string)") 48 | 49 | } 50 | fileprivate func test_rsa_signature(){ 51 | let path_public = Bundle.main.path(forResource: "cert", ofType: "der")! 52 | let path_private = Bundle.main.path(forResource: "cert", ofType: "p12")! 53 | 54 | let rsa = RSA(filenameOfPulbicKey: path_public, filenameOfPrivateKey: path_private) 55 | guard let _rsa = rsa else { 56 | return 57 | } 58 | 59 | let raw = "0123456789abcdefg" 60 | // print(raw.digestBase64(DigestAlgorithm.sha1)) 61 | // print(raw.digestBase64(DigestAlgorithm.md5)) 62 | let raw_data = raw.data(using: String.Encoding.utf8)! 63 | // let sign_data = _rsa.sign(RSAAlgorithm.sha1,inputData:raw_data) 64 | let sign_data = _rsa.sign(RSAAlgorithm.md5,inputData:raw_data) 65 | // let sign_data = _rsa.sign(RSAAlgorithm.sha256,inputData:raw_data) 66 | // print(sign_data!.hexString) 67 | print(sign_data!.base64String) 68 | 69 | let raw_test = "0123456789abcdefg" 70 | let raw_test_data = raw_test.data(using: String.Encoding.utf8)! 71 | // let verified = _rsa.verify(RSAAlgorithm.sha1,inputData: raw_test_data, signedData: sign_data!) 72 | let verified = _rsa.verify(RSAAlgorithm.md5,inputData: raw_test_data, signedData: sign_data!) 73 | // let verified = _rsa.verify(RSAAlgorithm.sha256,inputData: raw_test_data, signedData: sign_data!) 74 | print("\(verified)") 75 | } 76 | 77 | } 78 | extension ViewController{ 79 | fileprivate func test_aes(){ 80 | let key = "0000000000000000" 81 | // let raw = "0123456789abcdef" 82 | let raw = "0123456" 83 | // let raw = "123你好把呵呵" 84 | // let raw = "你好!a" 85 | let encrypt_1 = raw.aesEBCEncrypt(key) 86 | print("aes encrypt hexString:\(encrypt_1!.hexString)") 87 | print("aes decrypt from hexString: \(encrypt_1!.hexString.aesEBCDecryptFromHex(key))") 88 | print("aes encrypt base64String: \(encrypt_1!.base64String)") 89 | print("aes decrypt from base64String: \(encrypt_1!.base64String.aesEBCDecryptFromBase64(key))") 90 | 91 | // let iv = "1111111111111111" 92 | let iv = "0000000000000000" 93 | let encrypt = raw.aesCBCEncrypt(key,iv: iv) 94 | print("aes encrypt hexString:\(encrypt!.hexString)") 95 | print("aes decrypt from hexString:\(encrypt!.hexString.aesCBCDecryptFromHex(key,iv: iv))") 96 | print("aes encrypt base64String:\(encrypt!.base64String)") 97 | print("aes decrypt from base64String:\(encrypt!.base64String.aesCBCDecryptFromBase64(key,iv: iv))") 98 | } 99 | fileprivate func test_digest_hmac(){ 100 | let raw = "abc123" 101 | print(raw.digestHex(DigestAlgorithm.md5)) 102 | print(raw.digestBase64(DigestAlgorithm.md5)) 103 | print(raw.signHex(HMACAlgorithm.sha1, key: "abc")) 104 | print(raw.signBase64(HMACAlgorithm.sha1, key: "abc")) 105 | print(raw.signBase64(HMACAlgorithm.sha1, key: "你好")) 106 | 107 | } 108 | } 109 | 110 | -------------------------------------------------------------------------------- /SecrecySwiftDemo/cert.der: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adow/SecrecySwift/254bc17928b51219e7d09c4631f6000e12419df4/SecrecySwiftDemo/cert.der -------------------------------------------------------------------------------- /SecrecySwiftDemo/cert.p12: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adow/SecrecySwift/254bc17928b51219e7d09c4631f6000e12419df4/SecrecySwiftDemo/cert.p12 --------------------------------------------------------------------------------