|
| 1 | + |
| 2 | +import CryptoKit |
| 3 | +import Foundation |
| 4 | + |
| 5 | + |
| 6 | +class Keychain |
| 7 | +{ |
| 8 | + func retrieveOrGeneratePrivateKey(label: String, tag: String) -> P256.KeyAgreement.PrivateKey? |
| 9 | + { |
| 10 | + // Do we already have a key? |
| 11 | + let searchQuery = generateKeySearchQuery(label: label, tag: tag) |
| 12 | + if let key = retrievePrivateKey(query: searchQuery) |
| 13 | + { |
| 14 | + return key |
| 15 | + } |
| 16 | + |
| 17 | + // We don't? |
| 18 | + // Let's create some and return those |
| 19 | + let privateKey = P256.KeyAgreement.PrivateKey() |
| 20 | + |
| 21 | + // Save the key we stored |
| 22 | + let stored = storePrivateKey(privateKey, label: label) |
| 23 | + if !stored |
| 24 | + { |
| 25 | + print("😱 Failed to store our new server key.") |
| 26 | + return nil |
| 27 | + } |
| 28 | + return privateKey |
| 29 | + } |
| 30 | + |
| 31 | + func generateAndSavePrivateKey(label: String) -> P256.KeyAgreement.PrivateKey? |
| 32 | + { |
| 33 | + let privateKey = P256.KeyAgreement.PrivateKey() |
| 34 | + |
| 35 | + // Save the key we stored |
| 36 | + let stored = storePrivateKey(privateKey, label: label) |
| 37 | + if !stored |
| 38 | + { |
| 39 | + print("😱 Failed to store our new server key.") |
| 40 | + return nil |
| 41 | + } |
| 42 | + |
| 43 | + return privateKey |
| 44 | + } |
| 45 | + |
| 46 | + func storePrivateKey(_ key: P256.KeyAgreement.PrivateKey, label: String) -> Bool |
| 47 | + { |
| 48 | + let attributes = [kSecAttrKeyType: kSecAttrKeyTypeECSECPrimeRandom, |
| 49 | + kSecAttrKeyClass: kSecAttrKeyClassPrivate] as [String: Any] |
| 50 | + |
| 51 | + // Get a SecKey representation. |
| 52 | + var error: Unmanaged<CFError>? |
| 53 | + let keyData = key.x963Representation as CFData |
| 54 | + guard let secKey = SecKeyCreateWithData(keyData, |
| 55 | + attributes as CFDictionary, |
| 56 | + &error) |
| 57 | + else |
| 58 | + { |
| 59 | + print("Unable to create SecKey representation.") |
| 60 | + if let secKeyError = error |
| 61 | + { |
| 62 | + print(secKeyError) |
| 63 | + } |
| 64 | + return false |
| 65 | + } |
| 66 | + |
| 67 | + // Describe the add operation. |
| 68 | + let query = [kSecClass: kSecClassKey, |
| 69 | + kSecAttrApplicationLabel: label, |
| 70 | + kSecAttrAccessible: kSecAttrAccessibleWhenUnlocked, |
| 71 | + kSecUseDataProtectionKeychain: true, |
| 72 | + kSecValueRef: secKey] as [String: Any] |
| 73 | + |
| 74 | + // Add the key to the keychain. |
| 75 | + let status = SecItemAdd(query as CFDictionary, nil) |
| 76 | + |
| 77 | + switch status { |
| 78 | + case errSecSuccess: |
| 79 | + return true |
| 80 | + default: |
| 81 | + if let statusString = SecCopyErrorMessageString(status, nil) |
| 82 | + { |
| 83 | + print("Unable to store item: \(statusString)") |
| 84 | + } |
| 85 | + |
| 86 | + return false |
| 87 | + } |
| 88 | + } |
| 89 | + |
| 90 | + func retrievePrivateKey(query: CFDictionary) -> P256.KeyAgreement.PrivateKey? |
| 91 | + { |
| 92 | + // Find and cast the result as a SecKey instance. |
| 93 | + var item: CFTypeRef? |
| 94 | + var secKey: SecKey |
| 95 | + switch SecItemCopyMatching(query as CFDictionary, &item) { |
| 96 | + case errSecSuccess: secKey = item as! SecKey |
| 97 | + case errSecItemNotFound: return nil |
| 98 | + case let status: |
| 99 | + print("Keychain read failed: \(status)") |
| 100 | + return nil |
| 101 | + } |
| 102 | + |
| 103 | + // Convert the SecKey into a CryptoKit key. |
| 104 | + var error: Unmanaged<CFError>? |
| 105 | + guard let data = SecKeyCopyExternalRepresentation(secKey, &error) as Data? |
| 106 | + else |
| 107 | + { |
| 108 | + print(error.debugDescription) |
| 109 | + return nil |
| 110 | + } |
| 111 | + |
| 112 | + do { |
| 113 | + let key = try P256.KeyAgreement.PrivateKey(x963Representation: data) |
| 114 | + return key |
| 115 | + } |
| 116 | + catch let keyError |
| 117 | + { |
| 118 | + print("Error decoding key: \(keyError)") |
| 119 | + return nil |
| 120 | + } |
| 121 | + } |
| 122 | + |
| 123 | + func generateKeySearchQuery(label: String, tag: String) -> CFDictionary |
| 124 | + { |
| 125 | + let query: [String: Any] = [kSecClass as String: kSecClassKey, |
| 126 | + kSecAttrApplicationLabel as String: label, |
| 127 | + kSecAttrApplicationTag as String: tag, |
| 128 | + kSecMatchLimit as String: kSecMatchLimitOne, |
| 129 | + kSecReturnRef as String: true, |
| 130 | + kSecReturnAttributes as String: false, |
| 131 | + kSecReturnData as String: false] |
| 132 | + |
| 133 | + return query as CFDictionary |
| 134 | + } |
| 135 | + |
| 136 | +// func generateKeyAttributesDictionary(tag: String) -> CFDictionary |
| 137 | +// { |
| 138 | +// //FIXME: Secure Enclave |
| 139 | +// // let access = SecAccessControlCreateWithFlags(kCFAllocatorDefault, kSecAttrAccessibleAlwaysThisDeviceOnly, .privateKeyUsage, nil)! |
| 140 | +// |
| 141 | +// let privateKeyAttributes: [String: Any] = [ |
| 142 | +// kSecAttrIsPermanent as String: true, |
| 143 | +// kSecAttrApplicationTag as String: tag |
| 144 | +// //kSecAttrAccessControl as String: access |
| 145 | +// ] |
| 146 | +// |
| 147 | +// let publicKeyAttributes: [String: Any] = [ |
| 148 | +// kSecAttrIsPermanent as String: true, |
| 149 | +// kSecAttrApplicationTag as String: tag |
| 150 | +// ] |
| 151 | +// |
| 152 | +// let attributes: [String: Any] = [ |
| 153 | +// kSecClass as String: kSecClassKey, |
| 154 | +// kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom, |
| 155 | +// kSecAttrKeySizeInBits as String: 256, |
| 156 | +// //kSecAttrTokenID as String: kSecAttrTokenIDSecureEnclave, |
| 157 | +// kSecPrivateKeyAttrs as String: privateKeyAttributes, |
| 158 | +// kSecPublicKeyAttrs as String: publicKeyAttributes |
| 159 | +// ] |
| 160 | +// |
| 161 | +// return attributes as CFDictionary |
| 162 | +// } |
| 163 | + |
| 164 | + public func deriveSymmetricKey(receiverPublicKey: P256.KeyAgreement.PublicKey, senderPrivateKey:P256.KeyAgreement.PrivateKey) -> SymmetricKey? |
| 165 | + { |
| 166 | + do |
| 167 | + { |
| 168 | + let sharedSecret = try senderPrivateKey.sharedSecretFromKeyAgreement(with: receiverPublicKey) |
| 169 | + let symmetricKey = sharedSecret.x963DerivedSymmetricKey(using: SHA256.self, sharedInfo: Data(), outputByteCount: 32) |
| 170 | + |
| 171 | + return symmetricKey |
| 172 | + } |
| 173 | + catch let sharedSecretError |
| 174 | + { |
| 175 | + print("Unable to encrypt payload. Failed to generate a shared secret: \(sharedSecretError)") |
| 176 | + return nil |
| 177 | + } |
| 178 | + } |
| 179 | + |
| 180 | + func deleteKeys(tag: String) |
| 181 | + { |
| 182 | + print("\nAttempted to delete key from secure enclave.") |
| 183 | + //Remove client keys from secure enclave |
| 184 | + let query: [String: Any] = [kSecClass as String: kSecClassKey, |
| 185 | + kSecAttrApplicationTag as String: tag] |
| 186 | + let deleteStatus = SecItemDelete(query as CFDictionary) |
| 187 | + |
| 188 | + switch deleteStatus |
| 189 | + { |
| 190 | + case errSecItemNotFound: |
| 191 | + print("Could not find a client key to delete.\n") |
| 192 | + case noErr: |
| 193 | + print("Deleted client keys.\n") |
| 194 | + default: |
| 195 | + print("Unexpected status: \(deleteStatus.description)\n") |
| 196 | + } |
| 197 | + } |
| 198 | +} |
0 commit comments