Post

Replies

Boosts

Views

Activity

Export Public Key in PEM Format
HiUsing the newer methods in the SDK for iOS 10, I can generate private and public keys, with the private key residing in the Keychain. The public key is exported.Here's my code thus far: func createKeyPair(_ keyName: String, authenticationRequired: SecAccessControlCreateFlags? = nil, completion: (_ success: Bool, _ publicKeyData: Data?) -> Void) { guard !keyName.isEmpty else { NSLog("\tNo keyname provided.") return completion(false, nil) } var error: Unmanaged<CFError>? // Private key parameters var privateKeyParams: [String: Any] = [ kSecAttrIsPermanent as String: true, kSecAttrApplicationTag as String: keyName ] // If we are using a biometric sensor to access the key, we need to create an SecAccessControl instance. if authenticationRequired != nil { guard let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, kSecAttrAccessibleWhenUnlockedThisDeviceOnly, authenticationRequired!, &error) else { NSLog("\tError: %@", error!.takeRetainedValue().localizedDescription) completion(false, nil) return } privateKeyParams[kSecAttrAccessControl as String] = accessControl } / let parameters: [String: Any] = [ kSecAttrKeyType as String: kSecAttrKeyTypeRSA, kSecAttrKeySizeInBits as String: 2048, kSecPrivateKeyAttrs as String: privateKeyParams ] // Global parameters for our key generation guard let privateKey = SecKeyCreateRandomKey(parameters as CFDictionary, &error) else { NSLog("\tError generating keypair. %@", "\(error!.takeRetainedValue().localizedDescription)") return completion(false, nil) } // Generate the keys. guard let publicKey = SecKeyCopyPublicKey(privateKey) else { NSLog("\tError obtaining public key.") return completion(false, nil) } // Get the public key. guard let privateKeyData = SecKeyCopyExternalRepresentation(privateKey, nil) else { NSLog("\tError obtaining export of private key.") return completion(false, nil) } print("\nPrivate key: \(String(describing: exportPublicKey(privateKeyData as Data)))") // Extract the public key for export. guard let publicKeyData = SecKeyCopyExternalRepresentation(publicKey, nil) else { NSLog("\tError obtaining export of public key.") return completion(false, nil) } completion(true, publicKeyData as Data) } public func exportPublicKey(_ rawPublicKeyBytes: Data, base64EncodingOptions: Data.Base64EncodingOptions = []) -> String? { return rawPublicKeyBytes.base64EncodedString(options: base64EncodingOptions) } // Call the function like so. _ = createKeyPair(keyName) { (status, data) in if status { print("exporting public key: \(String(describing: exportPublicKey(data!)))") } }If I've understood the documentation, SecKeyCopyExternalRepresentation says that the method returns data in the PCKS #1 format for an RSA key. From the various forums, I'm lead to beleive that simply base64 encoding to a string the output of SecKeyCopyExternalRepresentation is all that is required to export the public key in PEM format (without BEGIN RSA PUBLIC KEY and END RSA PUBLIC KEY)When the public key is used to validate some signed data in a Java app, the public key fails to load with invalid key errors... Anyone provide some guidance on this?Thanks
7
0
11k
Feb ’18
SecItemCopyMatching Touch ID Dialog
HiI have created a private key in the Keychain with kSecAttrAccessibleWhenUnlockedThisDeviceOnly. When I attempt to access the key to perform a signing operation, the Touch ID dialog will sometimes appear, but in most cases I have to touch the biometry sensor, then the dialog is displayed. Here's the code I'm using to create the key and access the key in a sign operation.public static func create(with name: String, authenticationRequired: SecAccessControlCreateFlags? = nil) -> Bool { guard !name.isEmpty else { return false } var error: Unmanaged<CFError>? // Private key parameters var privateKeyParams: [String: Any] = [ kSecAttrIsPermanent as String: true, kSecAttrApplicationTag as String: name ] // If we are using a biometric sensor to access the key, we need to create an SecAccessControl instance. if authenticationRequired != nil { guard let access = SecAccessControlCreateWithFlags(kCFAllocatorDefault, kSecAttrAccessibleWhenUnlockedThisDeviceOnly, authenticationRequired!, &error) else { return false } privateKeyParams[kSecAttrAccessControl as String] = access } // Global parameters for our key generation let parameters: [String: Any] = [ kSecAttrKeyType as String: kSecAttrKeyTypeRSA, kSecAttrKeySizeInBits as String: 2048, kSecPrivateKeyAttrs as String: privateKeyParams ] // Generate the keys. guard let privateKey = SecKeyCreateRandomKey(parameters as CFDictionary, &error) else { return false } // Private key created! return true }This is the code to sign the data that should prompt for the biometry sensor (Touch ID or Face ID).public static func sign(using name: String, value: String, localizedReason: String? = nil, base64EncodingOptions: Data.Base64EncodingOptions = []) -> String? { guard !name.isEmpty else { return nil } guard !value.isEmpty else { return nil } // Check if the private key exists in the chain, otherwise return guard let privateKey: SecKey = getPrivateKey(name, localizedReason: localizedReason ?? "") else { return nil } let data = value.data(using: .utf8)! var error: Unmanaged<CFError>? guard let signedData = SecKeyCreateSignature(privateKey, rsaSignatureMessagePKCS1v15SHA512, data as CFData, &error) as Data? else { return nil } return signedData.base64EncodedString(options: base64EncodingOptions) } fileprivate static func getPrivateKey(_ name: String, localizedReason: String) -> SecKey? { let query: [String: Any] = [ kSecClass as String: kSecClassKey, kSecAttrKeyType as String: kSecAttrKeyTypeRSA, kSecAttrApplicationTag as String: name, kSecReturnRef as String: true, kSecUseOperationPrompt as String : localizedReason ] var item: CFTypeRef? = nil let status = SecItemCopyMatching(query as CFDictionary, &item) guard status == errSecSuccess else { if status == errSecUserCanceled { print("\tError: Accessing private key failed: The user cancelled (%@).", "\(status)") } else if status == errSecDuplicateItem { print("\tError: The specified item already exists in the keychain (%@).", "\(status)") } else if status == errSecItemNotFound { print("\tError: The specified item could not be found in the keychain (%@).", "\(status)") } else if status == errSecInvalidItemRef { print("\tError: The specified item is no longer valid. It may have been deleted from the keychain (%@).", "\(status)") } else { print("\tError: Accessing private key failed (%@).", "\(status)") } return nil } return (item as! SecKey) }Then in my app, I would simply call guard let result = sign("mykey", "helloworld") else { print("failed to sign") return } print(result)So the getPrivateKey function is the one that calls SecKeyCopyingMatching, the 3 methods are in a helper class; what's the best approach to reliabably display the biometry dialog?Thanks
10
0
5.4k
May ’18
Checking is Biometry is Enrolled
HiWhat is the best way to determine if an iPhone or iPad has a biometry sensor? The user may or may not have registered their face or fingerprint, regardless I would like to know what biometry sensor is on the device. My app targets iOS 11, so it has to be either Touch or Face.Many thanksCraig
1
0
2.4k
Jul ’19
CryptoKit TOTP Generation
HiI'm using the new CryptoKit to generate a 6 or 8 digit TOTP code. Anyone been successful doing this?Using Xcode 11 BETA 5, targeting iOS 13 and Swift 5.1. Here is a snippet of generating an TOTP via CommonCrypto versus CryptoKit in playground (BETA). The base32Decode function returns Data.import CryptoKit import CommonCrypto import Foundation let period = TimeInterval(30) let digits = 6 let secret = base32Decode(value: "5FAA5JZ7WHO5WDNN")! var counter = UInt64(Date().timeIntervalSince1970 / period).bigEndian func cryptoKitOTP() { // Generate the key based on the counter. let key = SymmetricKey(data: Data(bytes: &counter, count: MemoryLayout.size(ofValue: counter))) let hash = HMAC<Insecure.SHA1>.authenticationCode(for: secret, using: key) var truncatedHash = hash.withUnsafeBytes { ptr -> UInt32 in let offset = ptr[hash.byteCount - 1] & 0x0f let truncatedHashPtr = ptr.baseAddress! + Int(offset) return truncatedHashPtr.bindMemory(to: UInt32.self, capacity: 1).pointee } truncatedHash = UInt32(bigEndian: truncatedHash) truncatedHash = truncatedHash & 0x7FFF_FFFF truncatedHash = truncatedHash % UInt32(pow(10, Float(digits))) print("CryptoKit OTP value: \(String(format: "%0*u", digits, truncatedHash))") } func commonCryptoOTP() { let key = Data(bytes: &counter, count: MemoryLayout.size(ofValue: counter)) let (hashAlgorithm, hashLength) = (CCHmacAlgorithm(kCCHmacAlgSHA1), Int(CC_SHA1_DIGEST_LENGTH)) let hashPtr = UnsafeMutablePointer.allocate(capacity: Int(hashLength)) defer { hashPtr.deallocate() } secret.withUnsafeBytes { secretBytes in // Generate the key from the counter value. counterData.withUnsafeBytes { counterBytes in CCHmac(hashAlgorithm, secretBytes.baseAddress, secret.count, counterBytes.baseAddress, key.count, hashPtr) } } let hash = Data(bytes: hashPtr, count: Int(hashLength)) var truncatedHash = hash.withUnsafeBytes { ptr -> UInt32 in let offset = ptr[hash.count - 1] & 0x0F let truncatedHashPtr = ptr.baseAddress! + Int(offset) return truncatedHashPtr.bindMemory(to: UInt32.self, capacity: 1).pointee } truncatedHash = UInt32(bigEndian: truncatedHash) truncatedHash = truncatedHash & 0x7FFF_FFFF truncatedHash = truncatedHash % UInt32(pow(10, Float(digits))) print("CommonCrypto OTP value: \(String(format: "%0*u", digits, truncatedHash))") } func otp() { commonCryptoOTP() cryptoKitOTP() } otp()The output based on now as in 2:28pm is: CommonCrypto OTP value: 819944 CryptoKit OTP value: 745890To confirm the OTP value, I used oathtool which you can brew install to generate an array of TOTP's. For example:oathtool --totp --base32 5FAA5JZ7WHO5WDNN -w 10Craig
7
0
5k
Aug ’19
Xcode 11 Unknown class in Interface Builder file.
HiI recently updated to Xcode 11 GM seed. However I've noticed that the dreaded "Unknown class in Interface Builder file" is crashing my app. I haven't changed any class names or storyboards. Interestingly the app runs perfectly in teh simulator, but crashed on my phone.Here is what is being printed in the output window:MyAppName[9513:4230222] Unknown class _TtC10MyApp24SlideTableViewController in Interface Builder file.Could not cast value of type 'UIViewController' (0x1ebe282b0) to 'MyApp.SlideTableViewController' (0x104d05e08).MyAppName[9513:4230222] Could not cast value of type 'UIViewController' (0x1ebe282b0) to 'MyApp.SlideTableViewController' (0x104d05e08).I've deleted the class and recreated, removed the View Controller from the story board, made sure the view controller is references correctly as is the target, but the problem persists and I'm out of ideas.Is there a "reset" of the storyboard to reference the elements? Or some other way to resolve this?Many thanksCraig
6
0
24k
Sep ’19
view sheet on first launch
HiI'm trying to display a sheet when the app first launches, similiar to when you upraded iOS to 13 and tapped say reminders.But I'm struggling to get with working with SwiftUI, here is a snippet of the code. It essentially crashes the app.import SwiftUI struct ContentView: View { @State private var showingSheet = false var body: some View { return self.sheet(isPresented: $showingSheet) { RegisterHome() } } } struct RegisterHome: View { var body: some View { NavigationView { Text("Register") .navigationBarTitle("Register") } } }Any thoughts would be very much appreciated.Thanks, Craig
3
0
1.4k
Dec ’19
Optional Protocol Type
HiI have a protocol as follows:protocol Profile: Codable, Identifiable { var id: String { get } var name: String { get } }With 2 implemenations as follows:struct Customer: Profile { let id: String let name: String let country: String } struct Contractor: Profile { let id: String let name: String let trade: String let companyName: String }I have a struct that encapsulates either the customer or contractor, but I don't what type of profile it will be at initialization time. So something like:final class UserData: ObservableObject, Codable { var account: Profile? }But the code doesn't compile with the error:Protocol 'Profile' can only be used as a generic constraint because it has Self or associated type requirements.How I'd like to use UserData is by:var user = UserData() user.account = getAccount() func getAccount() -> Profile? { // decode JSON from file, returning a Custoemr or Contractor return Customer(id: "123", name: "Bill", country: "USA") }I'm struggling to assign account to an optional protocol. Appreciate any help and guidence.Thanks
4
0
906
Feb ’20
CryptoKit SecureEnclave and LAContext
Hi I want to prompt for FaceID or TouchID before creating the private key in the Secure Enclave. And again when the key is recreated. I might be misinterpreting the documentation wrong, but I thought passing in LAContext instance to the authenticationContext parameter does this for you in both create and recreate use cases. For example: swift let authContext = LAContext() let accessControl = SecAccessControlCreateWithFlags( nil, kSecAttrAccessibleWhenUnlockedThisDeviceOnly, [.privateKeyUsage, .biometryCurrentSet], nil)! let key0 = try! SecureEnclave.P256.Signing.PrivateKey( accessControl: accessControl, authenticationContext: authContext) let key1 = try! SecureEnclave.P256.Signing.PrivateKey( dataRepresentation: key0.dataRepresentation, authenticationContext: authContext) I was expecting a biometry prompt to appear twice, on create and on recreate CryptoKit operations - no authentication prompt appears on an iPhoneX 14.3 with FaceID enrolled and enabled. Same result in the simulator. Read a few articles all suggesting the above code snippet is what you need to do, but I'm not seeing the desired result. Appreciate any help with this 🙏
1
0
1.2k
Feb ’21
Custom UIView not appearing on ViewController
Hi I have a custom UIView contained xib which is in an xcframework. The view has a timeout property which removes itself from the super view if it expiries. If the view does expiry, it fires a delegate which the function can observe using the KVC approach. What I'm experiencing is my function adds the view to the view controller ok, but doesn't display it until the function completes or throws an error. Here is a snippet of what I have described: // MARK: Contained in custom xcframework class MyView: UIView { var delegate: VerificationHandler? required init?(coder aDecoder: NSCoder) {         super.init(coder: aDecoder)         initialize()     }     override init(frame: CGRect) {         super.init(frame: frame)         initialize()     } func initialize() { let bundle = Bundle(for: type(of: self))      let uvNib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)      let uvView = uvNib.instantiate(withOwner: self, options: nil).first as! UIView addSubview(uvView) Timer.scheduledTimer(withTimeInterval: TimeInterval(10), repeats: false) { [self] timer in             timer.invalidate()             delegate?.verification(didContinue: false)             removeFromSuperview()       } } } protocol VerificationHandler { func verification(didContinue: Bool) } class VerificationResult: NSObject {     @objc dynamic var value: Bool     init(_ value: Bool) {         self.value = value     } } public enum MyEnum { } public extension MyEnum { private static var verificationResult: VerificationResult = VerificationResult(false) public static func myFunction(_ viewController: UIViewController) throws -> MyObject { if let viewController = viewController { let view = MyView(frame: viewController.view.frame) view.delegate = self as? VerificationHandler viewController.view.addSubview(view)  let semaphore = DispatchSemaphore.init(value: 0) // observe the change occurring in the view which creates the verificationResult. var result: Bool let kvc = verificationResult.observe(\.value, options: .new) { _, change in result = change.newValue! // didContinue semaphore.signal() } semaphore.wait() if !result { throw MyError.timeout } return MyObject(...) } } extension MyEnum: VerificationHandler {     func verification(didContinue: Bool) {         MyEnum.verificationResult = VerificationResult(didContinue)     } } // MARK: View controller app code class ViewController: UIViewController { override func viewDidLoad() {     super.viewDidLoad() } @IBAction func onClick(_ sender: UIButton) { do { // this call is where the custom view from the xcframework should appear       let result = try MyEnum.myFunction(self)       }       catch let error {       print(error.localizedDescription)       } } } I'm using the semaphore to wait for the timer in MyView to fire which would cause the KVC to invoke. Not sure if this is the best way, but I'm blocked and can't figure out why the view only appears after an Error is thrown from myFunc. Any guidance appreciated.
1
0
1.9k
Jun ’21
Semaphore Wait After Creating UIButton
Hi In this snippet, I've already added a button, the onDisplay action simply adds another UIButton with an addAction event to the view controller @IBAction func onDisplay(_ sender: UIButton) { let semaphore = DispatchSemaphore(value: 1)     var didComplete = false     addButton("hello world") { result in         print("result: \(result)")         didComplete = result         semaphore.signal()     }     if semaphore.wait(timeout: .now() + 5) == .timedOut {         print("timeout: \(didComplete)")     }     print("didComplete: \(didComplete)") } func addButton(_ message: String, completion: @escaping (Bool) -> Void) {     let button = UIButton(type: .system)     button.frame = CGRect(x: 100, y: 100, width: 100, height: 40)     button.backgroundColor = .systemBlue     button.setTitle(message, for: .normal)     button.titleLabel?.tintColor = .white     button.addAction(UIAction(handler: { action  in             completion(true)     }), for: .touchUpInside)     view.addSubview(button) } What I'm expecting to happen, is the new "hello world" button get created (which it does). If the user does nothing for 5 seconds (semaphore timeout), then print timeout: false. If the user tapped the button, this would print result: true in the completion closure. But what happens when I don't touch the button is didComplete: false prints out (the last line) and the semaphore.wait never gets invoked. How do I make the semaphore execute it's wait operation? Been struggling with this for days 😞
5
0
2.1k
Jun ’21
UserDefaults on App Launch
Hi On first launch (after download) of my app I display a "terms and conditions" consent screen. When the user taps agree, I set a Bool value in UserDefaults, so on next launch, the user is not prompted again. Pretty stock standard approach. I've had some users report that if the app is in the background for an extended period of time, the "terms and conditions" screen will re-appear when brought back into the foreground. But if the app was terminated after use and then re-launched, then behaviour is as expected - the "terms and conditions" screen is not shown. Is the better approach to use a file instead? Thanks
5
0
2k
Aug ’21
SecItemAdd with kSecAttrAccessControl Error
Hi I'm trying to add to the Keychain with access control flags. However the OSStatus returns -50 One or more parameters passed to a function were not valid. Here is the function I've written causing the error: public func addItem(value: Data, forKey: String, accessControlFlags: SecAccessControlCreateFlags? = nil) { guard !forKey.isEmpty else {     return    } var query: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: Bundle.main.bundleIdentifier!, kSecAttrAccount as String: forKey, kSecValueData as String: value, kSecAttrSynchronizable as String: false kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlock] // Check if any access control is to be applied. if let accessControlFlags = accessControlFlags { var error: Unmanaged<CFError>?       guard let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault, kSecAttrAccessibleWhenUnlockedThisDeviceOnly, accessControlFlags, &error) else { return } query[kSecAttrAccessControl as String] = accessControl    } let status = SecItemAdd(query as CFDictionary, nil) guard status != errSecDuplicateItem else { return } guard status == errSecSuccess else { let message = SecCopyErrorMessageString(status, nil) as String? ?? "Unknown error" print(message) return } } Any ideas why this might be occurring, if kSecAttrAccessControl is not added to the query parameter, then it works fine. Thanks
6
0
2.3k
Sep ’21
HStack Alignments
Hi First SwiftUI app and spent a few hours trying to fix the alignment with the following layout. struct ContentView: View {     var body: some View {          VStack {             Text("About My Data")                 .font(.title)                 .fontWeight(.heavy)                 .multilineTextAlignment(.center)                 .padding()                         Spacer().frame(height: 64)             HStack {                 Image(systemName: "network")                     .font(.system(size: 36.0))                     .foregroundColor(.blue)                 VStack(alignment: .leading) {                     Text("Network Support")                         .font(.headline)                         .fontWeight(.bold)                     Text("Download your data from anywhere.")                         .font(.body)                         .foregroundColor(.gray)                         .multilineTextAlignment(.leading)                 }             }.padding()             Spacer().frame(height:24)             HStack {                 Image(systemName: "hand.raised.fill")                     .font(.system(size: 36.0))                     .foregroundColor(.blue)                VStack(alignment: .leading) {                     Text("Data Privacy")                         .font(.headline)                         .fontWeight(.bold)                     Text("Scanned certificates are never stored on the device.")                         .font(.body)                         .foregroundColor(.gray)                         .multilineTextAlignment(.leading)                 }             }.padding()         }     } } struct ContentView_Previews: PreviewProvider {     static var previews: some View {         ContentView()     } } You can see that the HStack alignments are off, the first (showing the network image) seems to have a extra padding , not sure how to correct it if anyone has some suggestions. Many thanks
3
0
1.7k
Dec ’21
XCTest Ambiguous type name
Hi I've create a couple of files that are in the build target and "checked" the box to include these files in the test target. Here are the files in the build and test targets. DefaultValue+Extension.swift extension Bool { public enum False: DefaultValue { public static let defaultValue = false    }    public enum True: DefaultValue {     public static let defaultValue = true } } extension String { public enum Empty: DefaultValue {     public static let defaultValue = "" } } DefaultValuePropertyWrapper.swift public protocol DefaultValue { associatedtype Value: Decodable static var defaultValue: Value { get } } @propertyWrapper public struct Default<T: DefaultValue> { public var wrappedValue: T.Value public init() {   self.wrappedValue = T.defaultValue    } } extension Default: Decodable { public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer()   self.wrappedValue = try container.decode(T.Value.self) } } extension Default: Encodable where T.Value: Encodable { public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer()   try container.encode(self.wrappedValue) } } extension Default: Equatable where T.Value: Equatable {} extension Default: Hashable where T.Value: Hashable{} extension KeyedDecodingContainer { public func decode<T>(_ type: Default<T>.Type, forKey key: Key) throws -> Default<T> where T: DefaultValue { try decodeIfPresent(type, forKey: key) ?? .init() } } Running the unit test I encounter a several errors which I haven't been able to resolve. Here is my swift file with only the test target checked. DefaultValueTest.swift import XCTest @testable import MyFramework class DefaultValueTests: XCTestCase { override func setUpWithError() throws { } override func tearDownWithError() throws { } struct Person: Decodable { let userId: Int       let name: String       @Default<String.Empty> var nickName: String @Default<Bool.False> var isEnabled: Bool   @Default<Bool.True> var isAdmin: Bool } func testDefaultValues() throws {     let json = """       {       "userId": 1,          "name": "John" }       """ do {       let result = try JSONDecoder().decode(Person.self, from: json.data(using: .utf8)!)          XCTAssertTrue(result.nickname.isEmpty) XCTAssertFalse(result.isEnabled) XCTAssertTrue(result.isAdmin) } catch let error {       print("Error: \(error.localizedDescription)")         XCTFail() } }        The Person structure in DefaultValueTest.swift complains of the following: Type DefaultValueTests.Person does not conform to protocol Decodable nickName Ambiguous type name 'Empty' in 'String' isEnabled Ambiguous type name 'False' in 'Bool' isAdmin Ambiguous type name 'True' in 'Bool' When I build the framework and use it another project, everything works as expected... Appreciate any advice 🙏
1
0
1k
Jan ’22