RSASecKeyTests.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. //
  2. // CryptoSwift
  3. //
  4. // Copyright (C) 2014-2021 Marcin Krzyżanowski <marcin@krzyzanowskim.com>
  5. // This software is provided 'as-is', without any express or implied warranty.
  6. //
  7. // In no event will the authors be held liable for any damages arising from the use of this software.
  8. //
  9. // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
  10. //
  11. // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
  12. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  13. // - This notice may not be removed or altered from any source or binary distribution.
  14. //
  15. #if canImport(Security)
  16. import Security
  17. import XCTest
  18. @testable import CryptoSwift
  19. final class RSASecKeyTests: XCTestCase {
  20. // MARK: SecKey <-> RSA Interoperability
  21. /// From CryptoSwift RSA -> External Representation -> SecKey
  22. ///
  23. /// This test enforces that
  24. /// 1) We can export the raw external representation of a CryptoSwift RSA Public Key
  25. /// 2) And that we can import / create an RSA SecKey from that raw external representation
  26. /// 3) Proves interoperability between Apple's `Security` Framework and `CryptoSwift`
  27. func testRSAExternalRepresentationPublic() throws {
  28. // Generate a CryptoSwift RSA Key
  29. let rsaCryptoSwift = try RSA(keySize: 1024)
  30. // Get the key's rawExternalRepresentation
  31. let rsaCryptoSwiftRawRep = try rsaCryptoSwift.publicKeyDER()
  32. // We should be able to instantiate an RSA SecKey from this data
  33. let attributes: [String: Any] = [
  34. kSecAttrKeyType as String: kSecAttrKeyTypeRSA,
  35. kSecAttrKeyClass as String: kSecAttrKeyClassPublic,
  36. kSecAttrKeySizeInBits as String: 1024,
  37. kSecAttrIsPermanent as String: false
  38. ]
  39. var error: Unmanaged<CFError>?
  40. guard let rsaSecKey = SecKeyCreateWithData(Data(rsaCryptoSwiftRawRep) as CFData, attributes as CFDictionary, &error) else {
  41. XCTFail("Error constructing SecKey from raw key data: \(error.debugDescription)")
  42. return
  43. }
  44. // Get the SecKey's external representation
  45. var externalRepError: Unmanaged<CFError>?
  46. guard let rsaSecKeyRawRep = SecKeyCopyExternalRepresentation(rsaSecKey, &externalRepError) as? Data else {
  47. XCTFail("Failed to copy external representation for RSA SecKey")
  48. return
  49. }
  50. // Ensure both the CryptoSwift Ext Rep and the SecKey Ext Rep match
  51. XCTAssertEqual(rsaSecKeyRawRep, Data(rsaCryptoSwiftRawRep))
  52. XCTAssertEqual(rsaSecKeyRawRep, try rsaCryptoSwift.publicKeyExternalRepresentation())
  53. }
  54. /// From CryptoSwift RSA -> External Representation -> SecKey
  55. ///
  56. /// This test enforces that
  57. /// 1) We can export the raw external representation of a CryptoSwift RSA Private Key
  58. /// 2) And that we can import / create an RSA SecKey from that raw external representation
  59. /// 3) Proves interoperability between Apple's `Security` Framework and `CryptoSwift`
  60. func testRSAExternalRepresentationPrivate() throws {
  61. // Generate a CryptoSwift RSA Key
  62. let rsaCryptoSwift = try RSA(keySize: 1024)
  63. // Get the key's rawExternalRepresentation
  64. let rsaCryptoSwiftRawRep = try rsaCryptoSwift.privateKeyDER()
  65. // We should be able to instantiate an RSA SecKey from this data
  66. let attributes: [String: Any] = [
  67. kSecAttrKeyType as String: kSecAttrKeyTypeRSA,
  68. kSecAttrKeyClass as String: kSecAttrKeyClassPrivate,
  69. kSecAttrKeySizeInBits as String: 1024,
  70. kSecAttrIsPermanent as String: false
  71. ]
  72. var error: Unmanaged<CFError>?
  73. guard let rsaSecKey = SecKeyCreateWithData(Data(rsaCryptoSwiftRawRep) as CFData, attributes as CFDictionary, &error) else {
  74. XCTFail("Error constructing SecKey from raw key data: \(error.debugDescription)")
  75. return
  76. }
  77. // Get the SecKey's external representation
  78. var externalRepError: Unmanaged<CFError>?
  79. guard let rsaSecKeyRawRep = SecKeyCopyExternalRepresentation(rsaSecKey, &externalRepError) as? Data else {
  80. XCTFail("Failed to copy external representation for RSA SecKey")
  81. return
  82. }
  83. // Ensure both the CryptoSwift Ext Rep and the SecKey Ext Rep match
  84. XCTAssertEqual(rsaSecKeyRawRep, Data(rsaCryptoSwiftRawRep))
  85. XCTAssertEqual(rsaSecKeyRawRep, try rsaCryptoSwift.externalRepresentation())
  86. }
  87. /// From SecKey -> External Representation -> CryptoSwift RSA
  88. ///
  89. /// This test enforces that
  90. /// 1) Given the raw external representation of a Public RSA SecKey, we can import that same key into CryptoSwift
  91. /// 2) When we export the raw external representation of the RSA Key we get the exact same data
  92. /// 3) Proves interoperability between Apple's `Security` Framework and `CryptoSwift`
  93. func testSecKeyExternalRepresentationPublic() throws {
  94. // Generate a SecKey RSA Key
  95. let parameters: [CFString: Any] = [
  96. kSecAttrKeyType: kSecAttrKeyTypeRSA,
  97. kSecAttrKeySizeInBits: 1024
  98. ]
  99. var error: Unmanaged<CFError>?
  100. // Generate the RSA SecKey
  101. guard let rsaSecKey = SecKeyCreateRandomKey(parameters as CFDictionary, &error) else {
  102. XCTFail("Key Generation Error: \(error.debugDescription)")
  103. return
  104. }
  105. // Extract the public key from the private RSA SecKey
  106. guard let rsaSecKeyPublic = SecKeyCopyPublicKey(rsaSecKey) else {
  107. XCTFail("Public Key Extraction Error")
  108. return
  109. }
  110. // Lets grab the external representation of the public key
  111. var externalRepError: Unmanaged<CFError>?
  112. guard let rsaSecKeyRawRep = SecKeyCopyExternalRepresentation(rsaSecKeyPublic, &externalRepError) as? Data else {
  113. XCTFail("Failed to copy external representation for RSA SecKey")
  114. return
  115. }
  116. // Ensure we can import the private RSA key into CryptoSwift
  117. let rsaCryptoSwift = try RSA(rawRepresentation: rsaSecKeyRawRep)
  118. XCTAssertNil(rsaCryptoSwift.d)
  119. XCTAssertEqual(rsaSecKeyRawRep, try rsaCryptoSwift.externalRepresentation())
  120. }
  121. /// From SecKey -> External Representation -> CryptoSwift RSA
  122. ///
  123. /// This test enforces that
  124. /// 1) Given the raw external representation of a Private RSA SecKey, we can import that same key into CryptoSwift
  125. /// 2) When we export the raw external representation of the RSA Key we get the exact same data
  126. /// 3) Proves interoperability between Apple's `Security` Framework and `CryptoSwift`
  127. func testSecKeyExternalRepresentationPrivate() throws {
  128. // Generate a SecKey RSA Key
  129. let parameters: [CFString: Any] = [
  130. kSecAttrKeyType: kSecAttrKeyTypeRSA,
  131. kSecAttrKeySizeInBits: 1024
  132. ]
  133. var error: Unmanaged<CFError>?
  134. // Generate the RSA SecKey
  135. guard let rsaSecKey = SecKeyCreateRandomKey(parameters as CFDictionary, &error) else {
  136. XCTFail("Key Generation Error: \(error.debugDescription)")
  137. return
  138. }
  139. // Lets grab the external representation
  140. var externalRepError: Unmanaged<CFError>?
  141. guard let rsaSecKeyRawRep = SecKeyCopyExternalRepresentation(rsaSecKey, &externalRepError) as? Data else {
  142. XCTFail("Failed to copy external representation for RSA SecKey")
  143. return
  144. }
  145. // Ensure we can import the private RSA key into CryptoSwift
  146. let rsaCryptoSwift = try RSA(rawRepresentation: rsaSecKeyRawRep)
  147. XCTAssertNotNil(rsaCryptoSwift.d)
  148. XCTAssertEqual(rsaSecKeyRawRep, try rsaCryptoSwift.externalRepresentation())
  149. }
  150. /// This test generates X RSA keys and tests them between `Security` and `CryptoSwift` for interoperability
  151. ///
  152. /// For each key generated, this test enforces that
  153. /// 1) We can import the raw external representation (generated by the `Security` framework) of the RSA Key into `CryptoSwift`
  154. /// 2) When signing messages using a deterministic variant, we get the same output from both `Security` and `CryptoSwift`
  155. /// 3) We can verify a signature generated from `CryptoSwift` with `Security` and vice versa
  156. /// 4) We can encrypt and decrypt a message generated from `CryptoSwift` with `Security` and vice versa
  157. func testRSASecKeys() throws {
  158. let tests = 3
  159. let messageToSign: String = "RSA Keys!"
  160. for _ in 0..<tests {
  161. // Generate a SecKey RSA Key
  162. let parameters: [CFString: Any] = [
  163. kSecAttrKeyType: kSecAttrKeyTypeRSA,
  164. kSecAttrKeySizeInBits: 1024
  165. ]
  166. var error: Unmanaged<CFError>?
  167. // Generate the RSA SecKey
  168. guard let rsaSecKey = SecKeyCreateRandomKey(parameters as CFDictionary, &error) else {
  169. XCTFail("Key Generation Error: \(error.debugDescription)")
  170. break
  171. }
  172. // Lets grab the external representation
  173. var externalRepError: Unmanaged<CFError>?
  174. guard let rsaSecKeyRawRep = SecKeyCopyExternalRepresentation(rsaSecKey, &externalRepError) as? Data else {
  175. XCTFail("Failed to copy external representation for RSA SecKey")
  176. break
  177. }
  178. // Ensure we can import the private RSA key into CryptoSwift
  179. let rsaCryptoSwift = try RSA(rawRepresentation: rsaSecKeyRawRep)
  180. // Sign the message with both keys and ensure their the same
  181. let csSignature = try rsaCryptoSwift.sign(messageToSign.bytes, variant: .message_pkcs1v15_SHA256)
  182. let skSignature = try secKeySign(messageToSign.bytes, variant: .rsaSignatureMessagePKCS1v15SHA256, withKey: rsaSecKey)
  183. XCTAssertEqual(csSignature, skSignature.bytes, "Signature don't match!")
  184. XCTAssertTrue(try rsaCryptoSwift.verify(signature: skSignature.bytes, for: messageToSign.bytes, variant: .message_pkcs1v15_SHA256))
  185. XCTAssertTrue(try self.secKeyVerify(csSignature, forBytes: messageToSign.bytes, usingVariant: .rsaSignatureMessagePKCS1v15SHA256, withKey: rsaSecKey))
  186. // Encrypt with SecKey
  187. let skEncryption = try secKeyEncrypt(messageToSign.bytes, usingVariant: .rsaEncryptionRaw, withKey: rsaSecKey)
  188. // Decrypt with CryptoSwift Key
  189. XCTAssertEqual(try rsaCryptoSwift.decrypt(skEncryption.bytes, variant: .unsafe), messageToSign.bytes, "CryptoSwift Decryption of SecKey Encryption Failed")
  190. // Encrypt with CryptoSwift
  191. let csEncryption = try rsaCryptoSwift.encrypt(messageToSign.bytes, variant: .unsafe)
  192. // Decrypt with SecKey
  193. XCTAssertEqual(try self.secKeyDecrypt(csEncryption, usingVariant: .rsaEncryptionRaw, withKey: rsaSecKey).bytes, messageToSign.bytes, "SecKey Decryption of CryptoSwift Encryption Failed")
  194. XCTAssertEqual(csEncryption, skEncryption.bytes, "Encrypted Data Does Not Match")
  195. // Encrypt with SecKey
  196. let skEncryption2 = try secKeyEncrypt(messageToSign.bytes, usingVariant: .rsaEncryptionPKCS1, withKey: rsaSecKey)
  197. // Decrypt with CryptoSwift Key
  198. XCTAssertEqual(try rsaCryptoSwift.decrypt(skEncryption2.bytes, variant: .pksc1v15), messageToSign.bytes, "CryptoSwift Decryption of SecKey Encryption Failed")
  199. // Encrypt with CryptoSwift
  200. let csEncryption2 = try rsaCryptoSwift.encrypt(messageToSign.bytes, variant: .pksc1v15)
  201. // Decrypt with SecKey
  202. XCTAssertEqual(try self.secKeyDecrypt(csEncryption2, usingVariant: .rsaEncryptionPKCS1, withKey: rsaSecKey).bytes, messageToSign.bytes, "SecKey Decryption of CryptoSwift Encryption Failed")
  203. }
  204. }
  205. private func secKeySign(_ bytes: Array<UInt8>, variant: SecKeyAlgorithm, withKey key: SecKey) throws -> Data {
  206. var error: Unmanaged<CFError>?
  207. // Sign the data
  208. guard let signature = SecKeyCreateSignature(
  209. key,
  210. variant,
  211. Data(bytes) as CFData,
  212. &error
  213. ) as Data?
  214. else { throw NSError(domain: "Failed to sign bytes: \(bytes)", code: 0) }
  215. return signature
  216. }
  217. private func secKeyVerify(_ signature: Array<UInt8>, forBytes bytes: Array<UInt8>, usingVariant variant: SecKeyAlgorithm, withKey key: SecKey) throws -> Bool {
  218. let pubKey = SecKeyCopyPublicKey(key)!
  219. var error: Unmanaged<CFError>?
  220. // Perform the signature verification
  221. let result = SecKeyVerifySignature(
  222. pubKey,
  223. variant,
  224. Data(bytes) as CFData,
  225. Data(signature) as CFData,
  226. &error
  227. )
  228. // Throw the error if we encountered one...
  229. if let error = error { throw error.takeRetainedValue() as Error }
  230. // return the result of the verification
  231. return result
  232. }
  233. private func secKeyEncrypt(_ bytes: Array<UInt8>, usingVariant variant: SecKeyAlgorithm, withKey key: SecKey) throws -> Data {
  234. let pubKey = SecKeyCopyPublicKey(key)!
  235. var error: Unmanaged<CFError>?
  236. guard let encryptedData = SecKeyCreateEncryptedData(pubKey, variant, Data(bytes) as CFData, &error) else {
  237. throw NSError(domain: "Error Encrypting Data: \(error.debugDescription)", code: 0, userInfo: nil)
  238. }
  239. // Throw the error if we encountered one...
  240. if let error = error { throw error.takeRetainedValue() as Error }
  241. // return the result of the encryption
  242. return encryptedData as Data
  243. }
  244. private func secKeyDecrypt(_ bytes: Array<UInt8>, usingVariant variant: SecKeyAlgorithm, withKey key: SecKey) throws -> Data {
  245. var error: Unmanaged<CFError>?
  246. guard let decryptedData = SecKeyCreateDecryptedData(key, variant, Data(bytes) as CFData, &error) else {
  247. throw NSError(domain: "Error Decrypting Data: \(error.debugDescription)", code: 0, userInfo: nil)
  248. }
  249. return (decryptedData as Data).drop { $0 == 0x00 }
  250. }
  251. }
  252. extension RSASecKeyTests {
  253. static func allTests() -> [(String, (RSASecKeyTests) -> () throws -> Void)] {
  254. let tests = [
  255. ("testRSAExternalRepresentationPublic", testRSAExternalRepresentationPublic),
  256. ("testRSAExternalRepresentationPrivate", testRSAExternalRepresentationPrivate),
  257. ("testSecKeyExternalRepresentationPublic", testSecKeyExternalRepresentationPublic),
  258. ("testSecKeyExternalRepresentationPrivate", testSecKeyExternalRepresentationPrivate),
  259. ("testRSASecKeys", testRSASecKeys)
  260. ]
  261. return tests
  262. }
  263. }
  264. // - MARK: Test Fixture Generation Code
  265. extension RSASecKeyTests {
  266. /// This 'Test' generates an RSA Key and uses that key to sign and encrypt a series of messages that we can test against.
  267. ///
  268. /// It prints a `Fixture` object that can be copy and pasted / used in other tests.
  269. func testCreateTestFixture() throws {
  270. let keySize = 1024
  271. let messages = [
  272. "",
  273. "👋",
  274. "RSA Keys",
  275. "CryptoSwift RSA Keys!",
  276. "CryptoSwift RSA Keys are really cool! They support encrypting / decrypting messages, signing and verifying signed messages, and importing and exporting encrypted keys for use between sessions 🔐"
  277. ]
  278. print(messages.map { $0.bytes.count })
  279. /// Generate a SecKey RSA Key
  280. let parameters: [CFString: Any] = [
  281. kSecAttrKeyType: kSecAttrKeyTypeRSA,
  282. kSecAttrKeySizeInBits: keySize
  283. ]
  284. var error: Unmanaged<CFError>?
  285. // Generate the RSA SecKey
  286. guard let rsaSecKey = SecKeyCreateRandomKey(parameters as CFDictionary, &error) else {
  287. XCTFail("Key Generation Error: \(error.debugDescription)")
  288. return
  289. }
  290. // Extract the public key from the private RSA SecKey
  291. guard let rsaSecKeyPublic = SecKeyCopyPublicKey(rsaSecKey) else {
  292. XCTFail("Public Key Extraction Error")
  293. return
  294. }
  295. /// Lets grab the external representation of the public key
  296. var publicExternalRepError: Unmanaged<CFError>?
  297. guard let publicRSASecKeyRawRep = SecKeyCopyExternalRepresentation(rsaSecKeyPublic, &publicExternalRepError) as? Data else {
  298. XCTFail("Failed to copy external representation for RSA SecKey")
  299. return
  300. }
  301. /// Lets grab the external representation of the public key
  302. var privateExternalRepError: Unmanaged<CFError>?
  303. guard let privateRSASecKeyRawRep = SecKeyCopyExternalRepresentation(rsaSecKey, &privateExternalRepError) as? Data else {
  304. XCTFail("Failed to copy external representation for RSA SecKey")
  305. return
  306. }
  307. var template = RSASecKeyTests.FixtureTemplate
  308. template = template.replacingOccurrences(of: "{{KEY_SIZE}}", with: "\(keySize)")
  309. template = template.replacingOccurrences(of: "{{PUBLIC_DER}}", with: "\(publicRSASecKeyRawRep.base64EncodedString())")
  310. template = template.replacingOccurrences(of: "{{PRIVATE_DER}}", with: "\(privateRSASecKeyRawRep.base64EncodedString())")
  311. var messageEntries: [String] = []
  312. for message in messages {
  313. var messageTemplate = RSASecKeyTests.MessageTemplate
  314. messageTemplate = messageTemplate.replacingOccurrences(of: "{{PLAINTEXT_MESSAGE}}", with: message)
  315. let encryptedMessages = try encrypt(data: message.data(using: .utf8)!, with: rsaSecKeyPublic)
  316. messageTemplate = messageTemplate.replacingOccurrences(of: "{{ENCRYPTED_MESSAGES}}", with: encryptedMessages.joined(separator: ",\n\t\t "))
  317. let signedMessages = try sign(message: message.data(using: .utf8)!, using: rsaSecKey)
  318. messageTemplate = messageTemplate.replacingOccurrences(of: "{{SIGNED_MESSAGES}}", with: signedMessages.joined(separator: ",\n\t\t "))
  319. messageEntries.append(messageTemplate)
  320. }
  321. template = template.replacingOccurrences(of: "{{MESSAGE_TEMPLATES}}", with: "\(messageEntries.joined(separator: ",\n\t"))")
  322. print("\n**************************")
  323. print(" Test Fixture Output")
  324. print("**************************\n")
  325. print(template)
  326. print("\n**************************")
  327. }
  328. private static let FixtureTemplate = """
  329. static let RSA_{{KEY_SIZE}} = Fixture(
  330. keySize: {{KEY_SIZE}},
  331. publicDER: \"\"\"
  332. {{PUBLIC_DER}}
  333. \"\"\",
  334. privateDER: \"\"\"
  335. {{PRIVATE_DER}}
  336. \"\"\",
  337. messages: [
  338. {{MESSAGE_TEMPLATES}}
  339. ]
  340. )
  341. """
  342. private static let MessageTemplate = """
  343. "{{PLAINTEXT_MESSAGE}}": (
  344. encryptedMessage: [
  345. {{ENCRYPTED_MESSAGES}}
  346. ],
  347. signedMessage: [
  348. {{SIGNED_MESSAGES}}
  349. ]
  350. )
  351. """
  352. private func initSecKey(rawRepresentation unsafe: Data) throws -> SecKey {
  353. let attributes: [String: Any] = [
  354. kSecAttrKeyType as String: kSecAttrKeyTypeRSA,
  355. kSecAttrKeyClass as String: kSecAttrKeyClassPrivate,
  356. kSecAttrKeySizeInBits as String: 1024,
  357. kSecAttrIsPermanent as String: false
  358. ]
  359. var error: Unmanaged<CFError>?
  360. guard let secKey = SecKeyCreateWithData(unsafe as CFData, attributes as CFDictionary, &error) else {
  361. throw NSError(domain: "Error constructing SecKey from raw key data: \(error.debugDescription)", code: 0, userInfo: nil)
  362. }
  363. return secKey
  364. }
  365. // We don't support PSS yet so we skip these variants
  366. private func sign(message: Data, using key: SecKey) throws -> [String] {
  367. let algorithms: [SecKeyAlgorithm] = [
  368. .rsaSignatureRaw,
  369. //.rsaSignatureDigestPSSSHA1,
  370. //.rsaSignatureDigestPSSSHA224,
  371. //.rsaSignatureDigestPSSSHA256,
  372. //.rsaSignatureDigestPSSSHA384,
  373. //.rsaSignatureDigestPSSSHA512,
  374. .rsaSignatureDigestPKCS1v15Raw,
  375. .rsaSignatureDigestPKCS1v15SHA1,
  376. .rsaSignatureDigestPKCS1v15SHA224,
  377. .rsaSignatureDigestPKCS1v15SHA256,
  378. .rsaSignatureDigestPKCS1v15SHA384,
  379. .rsaSignatureDigestPKCS1v15SHA512,
  380. //.rsaSignatureMessagePSSSHA1,
  381. //.rsaSignatureMessagePSSSHA224,
  382. //.rsaSignatureMessagePSSSHA256,
  383. //.rsaSignatureMessagePSSSHA384,
  384. //.rsaSignatureMessagePSSSHA512,
  385. .rsaSignatureMessagePKCS1v15SHA1,
  386. .rsaSignatureMessagePKCS1v15SHA224,
  387. .rsaSignatureMessagePKCS1v15SHA256,
  388. .rsaSignatureMessagePKCS1v15SHA384,
  389. .rsaSignatureMessagePKCS1v15SHA512,
  390. ]
  391. var sigs: [String] = []
  392. for algo in algorithms {
  393. var error: Unmanaged<CFError>?
  394. // Sign the data
  395. guard let signature = SecKeyCreateSignature(
  396. key,
  397. algo,
  398. message as CFData,
  399. &error
  400. ) as Data?
  401. else {
  402. print("\"\(algo.rawValue)\": \"nil\",")
  403. sigs.append("\"\(algo.rawValue)\": \"\"")
  404. continue
  405. }
  406. // Throw the error if we encountered one
  407. if let error = error { print("\"\(algo.rawValue)\": \"\(error.takeRetainedValue())\","); continue }
  408. // Append the signature
  409. sigs.append("\"\(algo.rawValue)\": \"\(signature.base64EncodedString())\"")
  410. }
  411. return sigs
  412. }
  413. private func encrypt(data: Data, with key: SecKey) throws -> [String] {
  414. let algorithms: [SecKeyAlgorithm] = [
  415. .rsaEncryptionRaw,
  416. .rsaEncryptionPKCS1
  417. ]
  418. var encryptions: [String] = []
  419. for algo in algorithms {
  420. var error: Unmanaged<CFError>?
  421. guard let encryptedData = SecKeyCreateEncryptedData(key, algo, data as CFData, &error) as? Data else {
  422. print("\"\(algo.rawValue)\": \"\(error?.takeRetainedValue().localizedDescription ?? "nil")\",")
  423. encryptions.append("\"\(algo.rawValue)\": \"\"")
  424. continue
  425. }
  426. encryptions.append("\"\(algo.rawValue)\": \"\(encryptedData.base64EncodedString())\"")
  427. }
  428. return encryptions
  429. }
  430. }
  431. #endif