General:
Apple Platform Security support document
Security Overview
Cryptography:
DevForums tags: Security, Apple CryptoKit
Security framework documentation
Apple CryptoKit framework documentation
Common Crypto man pages — For the full list of pages, run:
% man -k 3cc
For more information about man pages, see Reading UNIX Manual Pages.
On Cryptographic Key Formats DevForums post
SecItem attributes for keys DevForums post
CryptoCompatibility sample code
Keychain:
DevForums tags: Security
Security > Keychain Items documentation
TN3137 On Mac keychain APIs and implementations
SecItem Fundamentals DevForums post
SecItem Pitfalls and Best Practices DevForums post
Investigating hard-to-reproduce keychain problems DevForums post
Smart cards and other secure tokens:
DevForums tag: CryptoTokenKit
CryptoTokenKit framework documentation
Mac-specific resources:
DevForums tags: Security Foundation, Security Interface
Security Foundation framework documentation
Security Interface framework documentation
BSD Privilege Escalation on macOS
Related:
Networking Resources — This covers high-level network security, including HTTPS and TLS.
Network Extension Resources — This covers low-level network security, including VPN and content filters.
Code Signing Resources
Notarisation Resources
Trusted Execution Resources — This includes Gatekeeper.
App Sandbox Resources
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
Security
RSS for tagSecure the data your app manages and control access to your app using the Security framework.
Posts under Security tag
200 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
I regularly help developers with keychain problems, both here on DevForums and for my Day Job™ in DTS. Many of these problems are caused by a fundamental misunderstanding of how the keychain works. This post is my attempt to explain that. I wrote it primarily so that Future Quinn™ can direct folks here rather than explain everything from scratch (-:
If you have questions or comments about any of this, put them in a new thread and apply the Security tag so that I see it.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
SecItem: Fundamentals
or How I Learned to Stop Worrying and Love the SecItem API
The SecItem API seems very simple. After all, it only has four function calls, how hard can it be? In reality, things are not that easy. Various factors contribute to making this API much trickier than it might seem at first glance.
This post explains the fundamental underpinnings of the keychain. For information about specific issues, see its companion post, SecItem: Pitfalls and Best Practices.
Keychain Documentation
Your basic starting point should be Keychain Items.
If your code runs on the Mac, also read TN3137 On Mac keychain APIs and implementations.
Read the doc comments in <Security/SecItem.h>. In many cases those doc comments contain critical tidbits.
When you read keychain documentation [1] and doc comments, keep in mind that statements specific to iOS typically apply to iPadOS, tvOS, and watchOS as well (r. 102786959). Also, they typically apply to macOS when you target the data protection keychain. Conversely, statements specific to macOS may not apply when you target the data protection keychain.
[1] Except TN3137, which is very clear about this (-:
Caveat Mac Developer
macOS supports two different implementations: the original file-based keychain and the iOS-style data protection keychain. If you’re able to use the data protection keychain, do so. It’ll make your life easier.
TN3137 On Mac keychain APIs and implementations explains this distinction in depth.
The Four Freedoms^H^H^H^H^H^H^H^H Functions
The SecItem API contains just four functions:
SecItemAdd(_:_:)
SecItemCopyMatching(_:_:)
SecItemUpdate(_:_:)
SecItemDelete(_:)
These directly map to standard SQL database operations:
SecItemAdd(_:_:) maps to INSERT.
SecItemCopyMatching(_:_:) maps to SELECT.
SecItemUpdate(_:_:) maps to UPDATE.
SecItemDelete(_:) maps to DELETE.
You can think of each keychain item class (generic password, certificate, and so on) as a separate SQL table within the database. The rows of that table are the individual keychain items for that class and the columns are the attributes of those items.
Note Except for the digital identity class, kSecClassIdentity, where the values are split across the certificate and key tables. See Digital Identities Aren’t Real in SecItem: Pitfalls and Best Practices.
This is not an accident. The data protection keychain is actually implemented as an SQLite database. If you’re curious about its structure, examine it on the Mac by pointing your favourite SQLite inspection tool — for example, the sqlite3 command-line tool — at the keychain database in ~/Library/Keychains/UUU/keychain-2.db, where UUU is a UUID.
WARNING Do not depend on the location and structure of this file. These have changed in the past and are likely to change again in the future. If you embed knowledge of them into a shipping product, it’s likely that your product will have binary compatibility problems at some point in the future. The only reason I’m mentioning them here is because I find it helpful to poke around in the file to get a better understanding of how the API works.
For information about which attributes are supported by each keychain item class — that is, what columns are in each table — see the Note box at the top of Item Attribute Keys and Values. Alternatively, look at the Attribute Key Constants doc comment in <Security/SecItem.h>.
Uniqueness
A critical part of the keychain model is uniqueness. How does the keychain determine if item A is the same as item B? It turns out that this is class dependent. For each keychain item class there is a set of attributes that form the uniqueness constraint for items of that class. That is, if you try to add item A where all of its attributes are the same as item B, the add fails with errSecDuplicateItem. For more information, see the errSecDuplicateItem page. It has lists of attributes that make up this uniqueness constraint, one for each class.
These uniqueness constraints are a major source of confusion, as discussed in the Queries and the Uniqueness Constraints section of SecItem: Pitfalls and Best Practices.
Parameter Blocks Understanding
The SecItem API is a classic ‘parameter block’ API. All of its inputs are dictionaries, and you have to know which properties to set in each dictionary to achieve your desired result. Likewise for when you read properties in output dictionaries.
There are five different property groups:
The item class property, kSecClass, determines the class of item you’re operating on: kSecClassGenericPassword, kSecClassCertificate, and so on.
The item attribute properties, like kSecAttrAccessGroup, map directly to keychain item attributes.
The search properties, like kSecMatchLimit, control how the system runs a query.
The return type properties, like kSecReturnAttributes, determine what values the query returns.
The value type properties, like kSecValueRef perform multiple duties, as explained below.
There are other properties that perform a variety of specific functions. For example, kSecUseDataProtectionKeychain tells macOS to use the data protection keychain instead of the file-based keychain. These properties are hard to describe in general; for the details, see the documentation for each such property.
Inputs
Each of the four SecItem functions take dictionary input parameters of the same type, CFDictionary, but these dictionaries are not the same. Different dictionaries support different property groups:
The first parameter of SecItemAdd(_:_:) is an add dictionary. It supports all property groups except the search properties.
The first parameter of SecItemCopyMatching(_:_:) is a query and return dictionary. It supports all property groups.
The first parameter of SecItemUpdate(_:_:) is a pure query dictionary. It supports all property groups except the return type properties.
Likewise for the only parameter of SecItemDelete(_:).
The second parameter of SecItemUpdate(_:_:) is an update dictionary. It supports the item attribute and value type property groups.
Outputs
Two of the SecItem functions, SecItemAdd(_:_:) and SecItemCopyMatching(_:_:), return values. These output parameters are of type CFTypeRef because the type of value you get back depends on the return type properties you supply in the input dictionary:
If you supply a single return type property, except kSecReturnAttributes, you get back a value appropriate for that return type.
If you supply multiple return type properties or kSecReturnAttributes, you get back a dictionary. This supports the item attribute and value type property groups. To get a non-attribute value from this dictionary, use the value type property that corresponds to its return type property. For example, if you set kSecReturnPersistentRef in the input dictionary, use kSecValuePersistentRef to get the persistent reference from the output dictionary.
In the single item case, the type of value you get back depends on the return type property and the keychain item class:
For kSecReturnData you get back the keychain item’s data. This makes most sense for password items, where the data holds the password. It also works for certificate items, where you get back the DER-encoded certificate. Using this for key items is kinda sketchy. If you want to export a key, called SecKeyCopyExternalRepresentation. Using this for digital identity items is nonsensical.
For kSecReturnRef you get back an object reference. This only works for keychain item classes that have an object representation, namely certificates, keys, and digital identities. You get back a SecCertificate, a SecKey, or a SecIdentity, respectively.
For kSecReturnPersistentRef you get back a data value that holds the persistent reference.
Value Type Subtleties
There are three properties in the value type property group:
kSecValueData
kSecValueRef
kSecValuePersistentRef
Their semantics vary based on the dictionary type.
For kSecValueData:
In an add dictionary, this is the value of the item to add. For example, when adding a generic password item (kSecClassGenericPassword), the value of this key is a Data value containing the password.
This is not supported in a query dictionary.
In an update dictionary, this is the new value for the item.
For kSecValueRef:
In add and query dictionaries, the system infers the class property and attribute properties from the supplied object. For example, if you supply a certificate object (SecCertificate, created using SecCertificateCreateWithData), the system will infer a kSecClass value of kSecClassCertificate and various attribute values, like kSecAttrSerialNumber, from that certificate object.
This is not supported in an update dictionary.
For kSecValuePersistentRef:
For query dictionaries, this uniquely identifies the item to operate on.
This is not supported in add and update dictionaries.
Revision History
2023-09-12 Fixed various bugs in the revision history. Added a paragraph explaining how to determine which attributes are supported by each keychain item class.
2023-02-22 Made minor editorial changes.
2023-01-28 First posted.
I have my custom Authplugin implemented at login (system.login.console), and I want to remove password requirement validation/authentication from system.login.console authorization right. Do you see any functionality loss in completely removing password need at login. And is there any reference which can help me here to acheive this?
Hi,
I have a couple of questions about how to proceed and prepare the implementation for the DeviceLock MDM command for macOS in a secure and proper manner.
https://developer.apple.com/documentation/devicemanagement/device-lock-command
In documentation "PIN" is "(string) The six-character PIN for Find My. This value is available in macOS 10.8 and later." - is this the PIN that is used to unlock the device?
Is there any video online that I can see how the process would look like for the end user with locking and unlocking a device?
What should be done before sending a DeviceLock command? What should be done to safely test the command without bricking a device.
How to unlock a device that was locked with a DeviceLock command? Is there any Unlock command or can the user unlock device with the provided PIN earlier?
Thank you for any help!
Hi everyone,
I’m currently facing an issue while trying to submit an update for my app to the App Store. The review process is blocking the update due to a "Privacy - Data Use and Sharing" warning, stating that our app requests "tracking purchase history for tracking purposes."
However, we have already removed this functionality and deleted the NSUserTrackingUsageDescription key from our latest build. Despite this, the warning persists, and we are unable to proceed with the update.
I have already contacted Apple Support, but in the meantime, I wanted to ask the community:
Has anyone else encountered this issue, and if so, how did you resolve it?
Is there a way to force a refresh of privacy-related settings in App Store Connect?
Are there any additional steps we need to take to completely remove this tracking flag from our app submission?
Any insights or guidance would be greatly appreciated! Thanks in advance for your help.
The problem only happened on iOS system is 18.3.
We save the data about user after user login,so when user login successful ,we save users info in NSUserdefault ,then user delete app,and reinstall the app,when launch the app,it is already logged in.
I am working on improving Keychain item storage secured with Face ID using SecAccessControlCreateWithFlags. The implementation uses the .biometryAny flag as shown below:
SecAccessControlCreateWithFlags(
kCFAllocatorDefault,
kSecAttrAccessibleWhenUnlockedThisDeviceOnly,
.biometryAny,
&error
)
While this approach generally works as expected, I encountered a specific edge case during testing. On iOS 18.3.1 with Xcode 15.4, the following sequence causes the Keychain item to become inaccessible:
Navigate to Settings > Face ID & Passcode and select Reset Face ID.
Before setting up a new Face ID, tap the Back button to exit the setup process.
Reopen the Face ID setup and complete the enrollment.
Return to the app—previously stored Keychain items protected by .biometryAny are no longer available.
This behavior appears to be a change introduced in recent iOS versions. In versions prior to iOS 15, resetting or deleting Face ID entries did not invalidate existing Keychain items protected by .biometryAny.
This difference in behavior between iOS versions raises questions about the changes to biometric protection handling.
Any suggestions are welcomed that might shine a light on what the best practice to use keychain access control and prevent the data to become unavailable.
I'm looking for confirmation on the security aspects of fdesetup authrestart when used on a FileVault-enabled Mac.
As I understand it, this command temporarily stores the decryption key in memory to allow the system to restart without requiring manual entry of the FileVault password. However, I have a few security-related concerns:
Storage of the Decryption Key: Where exactly is the key stored during an authenticated restart? Is it protected within the Secure Enclave (for Apple Silicon Macs) or the T2 Security Chip on Intel Macs?
Key Lifetime & Wiping: At what point is the decryption key erased from memory? Does it persist in any form after the system has fully rebooted?
Protection Against Physical Attacks: If an attacker gains physical access to the machine before the restart completes, is there any possibility that they could extract the decryption key from memory?
Cold Boot Attack Resistance: Is there any risk that advanced forensic techniques (such as freezing RAM to retain data) could be used to recover the decryption key after issuing an authenticated restart?
Malware Resistance: Could a compromised system (e.g., root access by an attacker) intercept or misuse the decryption key before the restart?
I understand that on Apple Silicon and T2-equipped Macs, FileVault keys are tied to hardware-based encryption, making unauthorized access difficult.
However, I'd like to confirm whether Authenticated Restart introduces any new risks compared to a standard FileVault-enabled boot process.
Sometimes, when I close the lid using the MacOs version Sequoia 15.2, with the configuration to require a password for 5 seconds, the system does not ask for the password as expected.
This happens sometimes even though nothing preventing the system from sleeping when you close and open the lid, but it still seems like a security concern.
Is there some known issue related to this problem or a way to avoid it?
Result of command pmset -g:
Configuration:
Hello. I want to do the following and need your help.
I want to import a certificate (pkcs#12) into my macOS keychain with a setting that prohibits exporting the certificate.
I want to import the certificate (pkcs#12) into my login keychain or system keychain.
I was able to achieve [1] with the help of the following threads, but have the following problems.
https://developer.apple.com/forums/thread/677314?answerId=824644022#824644022
how to import into login keychain or system keychain
How to achieve this without using the deprecated API
To import into the login keychain, I could use the “SecKeychainCopyDefault” function instead of the “SecKeychainCopySearchList” function,
However, both of these functions were deprecated APIs.
https://developer.apple.com/documentation/security/seckeychaincopysearchlist(_:)
https://developer.apple.com/documentation/security/seckeychaincopydefault(_:)
I checked the following URL and it seems that using the SecItem API is correct, but I could not figure out how to use it.
https://developer.apple.com/documentation/technotes/tn3137-on-mac-keychains
Is there any way to import them into the login keychain or system keychain without using these deprecated APIs?
I have an app that captures USB storage device and sends some commands to it. The app has a privilege helper tool which captures the USB device. Everything was working fine upto macOS 15.2 but it 15.3 update broke the functionality.
When the helper tool tries to capture the USB device, it is able to capture IOUSBHostDevice but fails to capture IOUSBHostInterface. The error is
Code: 3758097097; Domain: IOUSBHostErrorDomain; Description: Failed to create IOUSBHostInterface.; Reason: Failed [super init]
I have verified the UID, EUID, GID, EGID = 0 for the helper process. So by IOUSBHost documentation it should have worked. The code that cause the error inside the helper tool is
func captureUSBInterface(interface: io_service_t) -> IOUSBHostInterface? {
let queue = DispatchQueue(label: "com.example.usbdevice.queue2")
var capturedInterface: IOUSBHostInterface?
do {
capturedInterface = try IOUSBHostInterface(__ioService: interface, options: .deviceCapture, queue: queue, interestHandler: nil)
} catch {
NSLog("Failed to capture USB interface: \(error)")
return nil
}
return capturedInterface
}
The app has sandbox=False and is distributed outside of the App Store.
Please advise (long-term, short-term solutions) on how to make this work.
i recently upgraded to sequoia, and now, more often than not, when running in the debugger, opening my database causes a hang:
When i run outside the debugger, it opens just fine.
I suspect it has to do with "full disk access"? but i've given my app full disk access.
i've also set Qt and Xcode to have "Allow apps to use developer tools" permissions. as a test i also added my app into that permission group, all to no avail.
the path to the DB being opened is in my user's Music folder, and having full disk access gives permission for everything, including things in that folder.
confused!
Current Setup:
Using Secure Enclave with userPresence access control
Foreground keychain accessibility: whenPasscodeSetThisDeviceOnly
Security Requirement:
Our security group wants us to invalidate biometrics and require a username/password if a biometric item is added (potentially by a hostile 3rd party)
Need to upgrade from userPresence to biometricCurrentSet to ensure re-authentication when biometric credentials change.
Issue:
After implementing biometricCurrentSet, authentication cancels after two failed biometric attempts instead of falling back to passcode.
Current Detection Method:
User completes initial biometric authentication
Biometric changes occur (undetectable by app)
App attempts Secure Enclave access
Access denial triggers re-authentication requirement
Cannot revoke refresh token after access is denied
Security Concern:
Current implementation allows new biometric enrollments to access existing authenticated sessions without re-verification.
Question:
What's the recommended approach to:
Implement biometricCurrentSet while maintaining passcode fallback
Properly handle refresh token invalidation when biometric credentials change
Looking for guidance on best practices for implementing these security requirements while maintaining good UX.
I must be missing something. How can an iphone that is in lockdown mode, using ONLY data, no Bluetooth connected and only one singular iPhone have seven UNLISTED items on the local network in privacy and settings?
转让app成功了之后,由于开发者账号更改,团队ID改变,导致获取不到原有的keychain中缓存的用户数据,所以在用户进行登录时,无法登录到原有的老账号,而是被识别成了一个新的用户。这种情况怎么解决。
I'm looking to integrate call / text / facetime history into my app while maintaining the necessary security for the end user. I only need date stamp and contact link or name of the person communicated with, no access to content of messages etc.
How would this be accomplished?
I have some concerns related to shortening the lifetime of certificates, as per
https://support.apple.com/en-gb/102028
Does this apply to Private CA root certificates?
And if yes:
does it apply if I use ATS and higher level API like URLSession
does it apply it I carry my root CA cert in my app payload and use low level libraries without ATS support?
This post is an extension to Importing Cryptographic Keys that covers one specific common case: importing a PEM-based RSA private key and its certificate to form a digital identity.
If you have questions or comments, start a new thread in Privacy & Security > General. Tag your thread with Security so that I see it.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
Importing a PEM-based RSA Private Key and its Certificate
I regularly see folks struggle to import an RSA private key and its corresponding certificate. Importing Cryptographic Keys outlines various options for importing keys, but in this post I want to cover one specific case, namely, a PEM-based RSA private key and its corresponding certificate. Together these form a digital identity, represented as a SecIdentity object.
IMPORTANT If you can repackage your digital identity as a PKCS#12, please do. It’s easy to import that using SecPKCS12Import. If you can switch to an elliptic curve (EC) private key, please do. It’s generally better and Apple CryptoKit has direct support for importing an EC PEM.
Assuming that’s not the case, let’s explore how to import a PEM-base RSA private key and its corresponding certificate to form a digital identity.
Note The code below was built with Xcode 16.2 and tested on the iOS 18.2 simulator. It uses the helper routines from Calling Security Framework from Swift.
This code assumes the data protection keychain. If you’re targeting macOS, add kSecUseDataProtectionKeychain to all the keychain calls. See TN3137 On Mac keychain APIs and implementations for more background to that.
Unwrap the PEM
To start, you need to get the data out of the PEM:
/// Extracts the data from a PEM.
///
/// As PEM files can contain a large range of data types, you must supply the
/// expected prefix and suffix strings. For example, for a certificate these
/// are `"-----BEGIN CERTIFICATE-----` and `-----END CERTIFICATE-----`.
///
/// - important: This assumes the simplest possible PEM format. It does not
/// handle metadata at the top of the PEM or PEMs with multiple items in them.
func dataFromPEM(_ pem: String, _ expectedPrefix: String, _ expectedSuffix: String) -> Data? {
let lines = pem.split(separator: "\n")
guard
let first = lines.first,
first == expectedPrefix,
let last = lines.last,
last == expectedSuffix
else { return nil }
let base64 = lines.dropFirst().dropLast().joined()
guard let data = Data(base64Encoded: base64) else { return nil }
return data
}
IMPORTANT Read the doc comment to learn about some important limitations with this code.
Import a Certificate
When adding a digital identity to the keychain, it’s best to import the certificate and the key separately and then add them to the keychain. That makes it easier to track down problems you encounter.
To import a PEM-based certificate, extract the data from the PEM and call SecCertificateCreateWithData:
/// Import a certificate in PEM format.
///
/// - important: See ``dataFromPEM(_:_:_:)`` for some important limitations.
func importCertificatePEM(_ pem: String) throws -> SecCertificate {
guard
let data = dataFromPEM(pem, "-----BEGIN CERTIFICATE-----", "-----END CERTIFICATE-----"),
let cert = SecCertificateCreateWithData(nil, data as NSData)
else { throw NSError(domain: NSOSStatusErrorDomain, code: Int(errSecParam), userInfo: nil) }
return cert
}
Here’s an example that shows this in action:
let benjyCertificatePEM = """
-----BEGIN CERTIFICATE-----
MIIC4TCCAcmgAwIBAgIBCzANBgkqhkiG9w0BAQsFADAfMRAwDgYDVQQDDAdNb3Vz
ZUNBMQswCQYDVQQGEwJHQjAeFw0xOTA5MzAxNDI0NDFaFw0yOTA5MjcxNDI0NDFa
MB0xDjAMBgNVBAMMBUJlbmp5MQswCQYDVQQGEwJHQjCCASIwDQYJKoZIhvcNAQEB
BQADggEPADCCAQoCggEBAOQe5ai68FQhTVIgpsDK+UOPIrgKzqJcW+wwLnJRp6GV
V9EmifJq7wjrXeqmP1XgcNtu7cVhDx+/ONKl/8hscak54HTQrgwE6mK628RThld9
BmZoOjaWWCkoU5bH7ZIYgrKF1tAO5uTAmVJB9v7DQQvKERwjQ10ZbFOW6v8j2gDL
esZQbFIC7f/viDXLsPq8dUZuyyb9BXrpEJpXpFDi/wzCV3C1wmtOUrU27xz4gBzi
3o9O6U4QmaF91xxaTk0Ot+/RLI70mR7TYa+u6q7UW/KK9q1+8LeTVs1x24VA5csx
HCAQf+xvMoKlocmUxCDBYkTFkmtyhmGRN52XucHgu0kCAwEAAaMqMCgwDgYDVR0P
AQH/BAQDAgWgMBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMCMA0GCSqGSIb3DQEBCwUA
A4IBAQAyrArH7+IyHTyEOrv/kZr3s3h4HWczSVeiO9qWD03/fVew84J524DiSBK4
mtAy3V/hqXrzrQEbsfyT7ZhQ6EqB/W0flpVYbku10cSVgoeSfjgBJLqgJRZKFonv
OQPjTf9HEDo5A1bQdnUF1y6SwdFaY16lH9mZ5B8AI57mduSg90c6Ao1GvtbAciNk
W8y4OTQp4drh18hpHegrgTIbuoWwgy8V4MX6W39XhkCUNhrQUUJk3mEfbC/yqfIG
YNds0NRI3QCTJCUbuXvDrLEn4iqRfbzq5cbulQBxBCUtLZFFjKE4M42fJh6D6oRR
yZSx4Ac3c+xYqTCjf0UdcUGxaxF/
-----END CERTIFICATE-----
"""
print(try? importCertificatePEM(benjyCertificatePEM))
If you run this it prints:
Optional(<cert(0x11e304c10) s: Benjy i: MouseCA>)
Import a Private Key
To import a PEM-base RSA private key, extract the data from the PEM and call SecKeyCreateWithData:
/// Import an 2048-bit RSA private key in PEM format.
///
/// Don’t use this code if:
///
/// * If you can switch to an EC key. EC keys are generally better and, for
/// this specific case, there’s support for importing them in Apple CryptoKit.
///
/// * You can switch to using a PKCS#12. In that case, use the system’s
/// `SecPKCS12Import` routine instead.
///
/// - important: See ``dataFromPEM(_:_:_:)`` for some important limitations.
func importRSA2048PrivateKeyPEM(_ pem: String) throws -> SecKey {
// Most private key PEMs are in PKCS#8 format. There’s no way to import
// that directly. Instead you need to strip the header to get to the
// `RSAPrivateKey` data structure encapsulated within the PKCS#8. Doing that
// in the general case is hard. In the specific case of an 2048-bit RSA
// key, the following hack works.
let rsaPrefix: [UInt8] = [
0x30, 0x82, 0x04, 0xBE, 0x02, 0x01, 0x00, 0x30,
0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7,
0x0D, 0x01, 0x01, 0x01, 0x05, 0x00, 0x04, 0x82,
0x04, 0xA8,
]
guard
let pkcs8 = dataFromPEM(pem, "-----BEGIN PRIVATE KEY-----", "-----END PRIVATE KEY-----"),
pkcs8.starts(with: rsaPrefix)
else { throw NSError(domain: NSOSStatusErrorDomain, code: Int(errSecParam), userInfo: nil) }
let rsaPrivateKey = pkcs8.dropFirst(rsaPrefix.count)
return try secCall { SecKeyCreateWithData(rsaPrivateKey as NSData, [
kSecAttrKeyType: kSecAttrKeyTypeRSA,
kSecAttrKeyClass: kSecAttrKeyClassPrivate,
] as NSDictionary, $0) }
}
IMPORTANT This code only works with 2048-bit RSA private keys. The comments explain more about that limitation.
Here’s an example that shows this in action:
let benjyPrivateKeyPEM = """
-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDkHuWouvBUIU1S
IKbAyvlDjyK4Cs6iXFvsMC5yUaehlVfRJonyau8I613qpj9V4HDbbu3FYQ8fvzjS
pf/IbHGpOeB00K4MBOpiutvEU4ZXfQZmaDo2llgpKFOWx+2SGIKyhdbQDubkwJlS
Qfb+w0ELyhEcI0NdGWxTlur/I9oAy3rGUGxSAu3/74g1y7D6vHVGbssm/QV66RCa
V6RQ4v8MwldwtcJrTlK1Nu8c+IAc4t6PTulOEJmhfdccWk5NDrfv0SyO9Jke02Gv
ruqu1FvyivatfvC3k1bNcduFQOXLMRwgEH/sbzKCpaHJlMQgwWJExZJrcoZhkTed
l7nB4LtJAgMBAAECggEBAKOPF6ED776SZgrliEog/dmXrhABB6jXybytyw+CRkuP
dXhrRmr+isZ9Y0gTzMN4+dILVgW4EozzoP0/sgZ04oWwDqQS30eU2qzRRzMbo+3k
oYsZXeu3nhxcYppwXIDsfAEd/ygMFzaadRPKYhrFykR2rA/dpLYCvW2tfm5SuULp
RxnKykFlVi8yVT64AovVm0XGOy/QTO5BBbUdftvZY9QCjGn/IEL8QFEz0rxZsb2L
s0HgVMUcB1My38RksZQRKLMWCtqLqWnez3oCnPka+dxFQj5RU//vNtRoVh1ExbmW
txHz48v00AKQvaudC4ujIspZlY8+UPdYQT0TNjhsfoUCgYEA+7yEvyCgRtYwUNm6
jHTg67LoSldHwENOry63qGZp3rCkWBkPXle7ulgRtuw+e11g4MoMMAgkIGyIGB/Z
6YvnQGmJCTMw+HHIyw3k/OvL1iz4DM+QlxDuD79Zu2j2UIL4maDG0ZDskiJujVAf
sFOy4r36TvYedmd7qgh9pgpsFl8CgYEA5/v8PZDs2I1wSDGllGfTr6aeQcxvw98I
p8l/8EV/lYpdKQMFndeFZI+dnJCcTeBbeXMmPNTAdL5gOTwDReXamIAdr93k7/x6
iKMHzBrpQZUMEhepSd8zdR1+vLvyszvUU6lvNXcfjwbu7gJQkwbA6kSoXRN+C1Cv
i5/w66t0f1cCgYBt02FWwTUrsmaB33uzq4o1SmhthoaXKsY5R3h4z7WAojAQ/13l
GwGb2rBfzdG0oJiTeZK3odWhD7iQTdUUPyU0xNY0XVEQExQ3AmjUr0rOte/CJww9
2/UAicrsKG7N0VYEMFCNPVz4pGz22e35T4rLwXZi3J2NqrgZBntK5WEioQKBgEyx
L4ii+sn0qGQVlankUUVGjhcuoNxeRZxCrzsdnrovTfEbAKZX88908yQpYqMUQul5
ufBuXVm6/lCtmF9pR8UWxbm4X9E+5Lt7Oj6tvuNhhOYOUHcNhRN4tsdqUygR5XXr
E8rXIOXF4wNoXH7ewrQwEoECyq6u8/ny3FDtE8xtAoGBALNFxRGikbQMXhUXj7FA
lLwWlNydCxCc7/YwlHfmekDaJRv59+z7SWAR15azhbjqS9oXWJUQ9uvpKF75opE7
MT0GzblkKAYu/3uhTENCjQg+9RFfu5w37E5RTWHD2hANV0YqXUlmH3d+f5uO0xN7
7bpqwYuYzSv1hBfU/yprDco6
-----END PRIVATE KEY-----
"""
print(try? importRSA2048PrivateKeyPEM(benjyPrivateKeyPEM))
If you run this it prints:
Optional(<SecKeyRef algorithm id: 1, key type: RSAPrivateKey, version: 4, 2048 bits (block size: 256), addr: 0x600000c5ce50>)
Form a Digital Identity
There are two common ways to form a digital identity:
SecPKCSImport
SecItemCopyMatching
SecPKCSImport is the most flexible because it gives you an in-memory digital identity. You can then choose to add it to the keychain or not. However, it requires a PKCS#12 as input. If you’re starting out with separate private key and certificate PEMs, you have to use SecItemCopyMatching.
Note macOS also has SecIdentityCreateWithCertificate, but it has some seriously limitations. First, it’s only available on macOS. Second, it requires the key to be in the keychain. If you’re going to add the key to the keychain anyway, you might as well use SecItemCopyMatching.
To form a digital identity from a separate private key and certificate:
Add the certificate to the keychain.
Add the private key to the keychain.
Call SecItemCopyMatching to get back a digital identity.
Here’s an example of that in action:
/// Imports a digital identity composed of separate certificate and private key PEMs.
///
/// - important: See ``dataFromPEM(_:_:_:)`` for some important limitations.
/// See ``importRSA2048PrivateKeyPEM(_:)`` for alternative strategies that are
/// much easier to deploy.
func addRSA2048DigitalIdentityPEMToKeychain(certificate: String, privateKey: String) throws -> SecIdentity {
// First import the certificate and private key. This has the advantage in
// that it triggers an early failure if the data is in the wrong format.
let certificate = try importCertificatePEM(certificate)
let privateKey = try importRSA2048PrivateKeyPEM(privateKey)
// Check that the private key matches the public key in the certificate. If
// not, someone has given you bogus credentials.
let certificatePublicKey = try secCall { SecCertificateCopyKey(certificate) }
let publicKey = try secCall { SecKeyCopyPublicKey(privateKey) }
guard CFEqual(certificatePublicKey, publicKey) else {
throw NSError(domain: NSOSStatusErrorDomain, code: Int(errSecPublicKeyInconsistent))
}
// Add the certificate first. If that fails — and the most likely error is
// `errSecDuplicateItem` — we want to stop immediately.
try secCall { SecItemAdd([
kSecValueRef: certificate,
] as NSDictionary, nil) }
// The add the private key.
do {
try secCall { SecItemAdd([
kSecValueRef: privateKey,
] as NSDictionary, nil) }
} catch let error as NSError {
// We ignore a `errSecDuplicateItem` error when adding the key. It’s
// possible to have multiple digital identities that share the same key,
// so if you try to add the key and it’s already in the keychain then
// that’s fine.
guard error.domain == NSOSStatusErrorDomain, error.code == errSecDuplicateItem else {
throw error
}
}
// Finally, search for the resulting identity.
//
// I originally tried querying for the identity based on the certificate’s
// attributes — the ones that contribute to uniqueness, namely
// `kSecAttrCertificateType`, `kSecAttrIssuer`, and `kSecAttrSerialNumber` —
// but that failed for reasons I don't fully understand (r. 144152660). So
// now I get all digital identities and find the one with our certificate.
let identities = try secCall { SecItemCopyMatching([
kSecClass: kSecClassIdentity,
kSecMatchLimit: kSecMatchLimitAll,
kSecReturnRef: true,
] as NSDictionary, $0) } as! [SecIdentity]
let identityQ = try identities.first { i in
try secCall { SecIdentityCopyCertificate(i, $0) } == certificate
}
return try secCall(Int(errSecItemNotFound)) { identityQ }
}
IMPORTANT This code is quite subtle. Read the comments for an explanation as to why it works the way it does.
Further reading
For more information about the APIs and techniques used above, see:
Importing Cryptographic Keys
On Cryptographic Keys Formats
SecItem: Fundamentals
SecItem: Pitfalls and Best Practices
Calling Security Framework from Swift
TN3137 On Mac keychain APIs and implementations
Finally, for links to documentation and other resources, see Security Resources.
Revision History
2025-02-13 Added code to check for mismatched private key and certificate.
2025-02-04 First posted.
Hi,
We're encountering an intermittent issue where certain users are unexpectedly logged out of our app and unable to log in again.
We believe we've narrrowed down the issue to the Keychain due to the following reasons:
We use a keychain item to determine if the member is logged in or not. Failure to retrieve the value leads the app to believe the member is logged out.
API error logs on the server show 3 missing values in fields that are each populated from items stored in the keychain.
Additional Notes:
The issue is hard to reproduce and seems to affect only a subset of users.
In some cases, uninstalling and reinstalling the app temporarily resolves the problem, but the issue recurs after a period of time.
The behavior appears to have coincided with the release of iOS 18.
We’re using the “kSecAttrAccessibleWhenUnlocked” accessibility attribute. Given that our app doesn’t perform background operations, we wouldn’t expect this to be an issue. We’re also considering changing this to "kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly" to see if this might resolve the issue.
We're the keychain-swift library to interact with the keychain.
We are currently adding extensive logging around our keychain implementation to confirm our findings but are looking for any additional input.
Questions:
Has anyone encountered similar keychain behavior on iOS 18?
Are there known changes or stability issues with the keychain in iOS 18 that might lead to such intermittent “item not found” errors?
Any recommended workarounds or troubleshooting steps that could help isolate the problem further?
Thanks for any help you can provide.
MacOS Version: 14.7.2
macOS SDKs:
macOS 14.5 -sdk macosx14.5
I am working on a sample program for validation Against:
Team Identifier
Developer ID
I started with validating Team Identifier, but my validation is not working and it is allowing to launch programs which are not matching the team identifier in the signature.
Below is my code:
func verifyExecutableWithLCR(executablePath: String, arguments: [String]) -> Bool {
let task = Process()
task.launchPath = executablePath
task.arguments = arguments
if #available(macOS 14.4, *) {
print("launchRequirementData is available on this system.")
do {
let req = try OnDiskCodeRequirement.allOf {
TeamIdentifier("ABCDEFGHI")
//SigningIdentifier("com.***.client.***-Client.****")
}
let encoder = PropertyListEncoder()
encoder.outputFormat = .xml
let requirementData = try encoder.encode(req)
task.launchRequirementData = requirementData
print("launchRequirementData is set.")
try task.run()
print("[SUCCESS] Executable passed the code signature verification.")
return true
} catch {
print("[ERROR] Code signature verification failed: \(error.localizedDescription)")
return false
}
} else {
print("[WARNING] launchRequirement is not available on this macOS version.")
return false
}
}
Could you please help me in identifying whay am I doing wrong here?
Hi,
My MACOS app has sensitive content and dont want user to take screenshot or to record the screen.
I tries window.sharingType=none. With this user can still record the screen.
I know that user can record with external device. But we dont want him to record using screen capture.
Can you please tell me how to detect when screen recording is active in MACOs apps? or how to prevent screen recording in MACOs apps.
Thanks
In the macOS 14.0 SDK, environment and library constraints were introduced, which made defense against common attack vectors relatively simple (especially with the LightWeightCodeRequirements framework added in 14.4).
Now, the application I'm working on must support macOS 13.0 too, so I was looking into alternatives that do work for those operating systems as well.
What I found myself is that the SecCode/SecStaticCode APIs in the Security Framework do offer very similar fashion checks as the LightWeightCodeRequirements framework does:
SecCodeCopySigningInformation can return values like signing identifier, team identifier, code requirement string and so on.
SecStaticCodeCreateWithPath can return a SecStaticCode object to an executable/app bundle on the file system.
Let's say, I would want to protect myself against launchd executable swap.
From macOS 14.0 onward, I would use a Spawn Constraint for this, directly in the launchd.plist file.
Before macOS 14.0, I would create a SecStaticCode object for the executable path found in the launchd.plist, and then examine its SecCodeCopySigningInformation dictionary. If the expectations are met, only then would I execute the launchd.plist-defined executable or connect to it via XPC.
Are these two equivalent? If not, what are the differences?