General:
Forums topic: Privacy & Security
Apple Platform Security support document
Developer > Security
Security Audit Thoughts forums post
Cryptography:
Forums 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 forums post
SecItem attributes for keys forums post
CryptoCompatibility sample code
Keychain:
Forums tags: Security
Security > Keychain Items documentation
TN3137 On Mac keychain APIs and implementations
SecItem Fundamentals forums post
SecItem Pitfalls and Best Practices forums post
Investigating hard-to-reproduce keychain problems forums post
App ID Prefix Change and Keychain Access forums post
Smart cards and other secure tokens:
Forums tag: CryptoTokenKit
CryptoTokenKit framework documentation
Mac-specific resources:
Forums 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"
General
RSS for tagPrioritize user privacy and data security in your app. Discuss best practices for data handling, user consent, and security measures to protect user information.
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
General:
Forums topic: Privacy & Security
Privacy Resources
Security Resources
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
Topic:
Privacy & Security
SubTopic:
General
When using Apple's Journal app through iPhone Mirroring, the user is allowed to authenticate via TouchID on the Mac instead of requiring you to unlock your phone, authenticate and then re-lock it to access it again in iPhone Mirroring.
Any other app that's using a call to authenticate via FaceID can't do this under iPhone Mirroring. Is there a new API call for this, or is it still a private API for Apple only?
I regularly see folks having problems importing cryptographic keys, so I thought I’d write down some hints and tips on how to recognise and import the various key formats. This post describes how to import each type of key. A companion post, On Cryptographic Keys Formats, discusses how to recognise the format of the data you have.
If you have questions about any of this stuff, put them a new thread in Privacy & Security > General. Tag your thread with Security or Apple CrytoKit, or both!, so that I see it.
Finally, if you want to see a specific example of these techniques in action, see Importing a PEM-based RSA Private Key and its Certificate.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
Importing Cryptographic Keys
Apple platforms support 5 different key types:
RSA (Security framework only)
SECG secp256r1, aka NIST P-256 (Security framework and Apple CryptoKit)
SECG secp384r1, aka NIST P-384 (Security framework and Apple CryptoKit)
SECG secp521r1, aka NIST P-521 (Security framework and Apple CryptoKit)
Curve 25519 (Apple CryptoKit only)
This post explains how to import each type of key. If you’re not sure what type of key you have, or how its encoded, or you run into weird problems and suspect that you might be using the wrong key type or encoding, read On Cryptographic Keys Formats.
Note This post focuses on APIs available on all Apple platforms. Some Mac-specific APIs can import other formats.
The Security framework uses the SecKey type for all key types that it supports.
Apple CryptoKit has a different approach: It uses different types for different key types, which helps catch common programming mistakes at compile time. There are 4 top-level enums:
P256, for SECG secp256r1
P384, for SECG secp384r1
P521, for SECG secp521r1
Curve25519, for Curve 25519
Each of those enums contains a KeyAgreement enum and a Signing enum, where you express the intended purpose for your key. In this post I always use Signing but the code will work the same if you choose KeyAgreement.
Finally, in each of those enums you’ll find both Public and Private types; these are structs that represent a specific public or private key.
Undo PEM Encoding
Writing a full-featured PEM parser is tricky. It is, however, relatively straightforward to undo the PEM encoding of a known simple PEM file. For example, if you have this file:
% cat p256-private-key.pem
-----BEGIN PRIVATE KEY-----
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgmGp6kcu19PgWNuga
r/CDWncdxmhlxAeo6ERpz2q4pHehRANCAASXR+mBqrjqcaJVzZoVYoWMQGAG8eQY
Jg0x4ad/bCs1qaMTLyMtsANR2dgANIfU7lKEeZAxPap8ch+I1LtW2pHH
-----END PRIVATE KEY-----
Decode it like so:
let u = URL(fileURLWithPath: "p256-private-key.pem")
guard let pem = try? String(contentsOf: u) else {
… handle error …
}
let pemBase64 = pem
.split(separator: "\n")
.dropFirst()
.dropLast()
.joined()
guard let pemData = Data(base64Encoded: String(pemBase64)) else {
… handle error …
}
debugPrint(pemData as NSData)
// prints:
// <30818702 01003013 06072a86 48ce3d02 0106082a 8648ce3d … d4bb56da 91c7>
Import RSA Keys
Use SecKeyCreateWithData to import an RSA key. If you have an RSAPublicKey structure like this:
% xxd -p rsa-public-key.der
3082010a0282010100cf243c324b262470131648614b62ee9c52af43319c
2498a7c16ba9790bb3a881f960f7b0303f8f49e86fedd6813be5fa888393
55d04426df0050dbb771eb683773b7dd929949695093f910c8dcdb633674
de986ada8d643e0e819b7cd5ab3bde4372103797472dc843a2711699e21a
4afddeed9f62810316903457342c345a35ebb2f06da019fed2afa56e7856
6e75a0d712849ae255155d9304348318930611b3b4f1153d77ee5970f076
299c548c8afff53157205048ade26d40930af2ecc96d4f77e8591523b767
fa3cdbc45a8a210339c4a556cea2e0dfa3ee819b62e463f75d87a53c2fbd
1bbcb8ec8fe2e8000ce37235fa903113c7b37d9c2a8b39c54b0203010001
%
% dumpasn1 -p -a rsa-public-key.der
SEQUENCE {
INTEGER
00 CF 24 3C 32 4B 26 24 70 13 16 48 61 4B 62 EE
9C 52 AF 43 31 9C 24 98 A7 C1 6B A9 79 0B B3 A8
81 F9 60 F7 B0 30 3F 8F 49 E8 6F ED D6 81 3B E5
FA 88 83 93 55 D0 44 26 DF 00 50 DB B7 71 EB 68
37 73 B7 DD 92 99 49 69 50 93 F9 10 C8 DC DB 63
36 74 DE 98 6A DA 8D 64 3E 0E 81 9B 7C D5 AB 3B
DE 43 72 10 37 97 47 2D C8 43 A2 71 16 99 E2 1A
4A FD DE ED 9F 62 81 03 16 90 34 57 34 2C 34 5A
35 EB B2 F0 6D A0 19 FE D2 AF A5 6E 78 56 6E 75
A0 D7 12 84 9A E2 55 15 5D 93 04 34 83 18 93 06
11 B3 B4 F1 15 3D 77 EE 59 70 F0 76 29 9C 54 8C
8A FF F5 31 57 20 50 48 AD E2 6D 40 93 0A F2 EC
C9 6D 4F 77 E8 59 15 23 B7 67 FA 3C DB C4 5A 8A
21 03 39 C4 A5 56 CE A2 E0 DF A3 EE 81 9B 62 E4
63 F7 5D 87 A5 3C 2F BD 1B BC B8 EC 8F E2 E8 00
0C E3 72 35 FA 90 31 13 C7 B3 7D 9C 2A 8B 39 C5
4B
INTEGER 65537
}
Import it with this code:
let u = URL(fileURLWithPath: "rsa-public-key.der")
guard let keyBytes = try? Data(contentsOf: u) else {
… handle error …
}
guard let privateKey = SecKeyCreateWithData(keyBytes as NSData, [
kSecAttrKeyType: kSecAttrKeyTypeRSA,
kSecAttrKeyClass: kSecAttrKeyClassPublic,
] as NSDictionary, nil) else {
… handle error …
}
print(privateKey)
// prints:
// <SecKeyRef algorithm id: 1, key type: RSAPublicKey, version: 4, block size: 2048 bits, exponent: {hex: 10001, decimal: 65537}, modulus: …, addr: …>
Note You don’t need to include any other attributes in the dictionary you pass to SecKeyCreateWithData. Specifically, many folks think that they need to pass in the kSecAttrKeySizeInBits attribute. This isn’t the case; SecKeyCreateWithData will work out the key size from the key data.
If you have an RSAPrivateKey structure like this:
% xxd -p rsa-private-key.der
308204a30201000282010100cf243c324b262470131648614b62ee9c52af
43319c2498a7c16ba9790bb3a881f960f7b0303f8f49e86fedd6813be5fa
88839355d04426df0050dbb771eb683773b7dd929949695093f910c8dcdb
633674de986ada8d643e0e819b7cd5ab3bde4372103797472dc843a27116
99e21a4afddeed9f62810316903457342c345a35ebb2f06da019fed2afa5
6e78566e75a0d712849ae255155d9304348318930611b3b4f1153d77ee59
70f076299c548c8afff53157205048ade26d40930af2ecc96d4f77e85915
23b767fa3cdbc45a8a210339c4a556cea2e0dfa3ee819b62e463f75d87a5
3c2fbd1bbcb8ec8fe2e8000ce37235fa903113c7b37d9c2a8b39c54b0203
0100010282010044b694716a946089fd0aeb3fbb2e3a5108ecb2b186466d
8d58904a4ba92213c7e9ddcccc5974fc275c3fa4f9ff2ccb816c3f996462
0df9870827ca7af4034f32f5e40c505121151a71bbb161b041e68b6e0159
363901a63b1fbcc6c3866da3127bf51e84125ebe452c8a7a513102dc0dfc
61331a2826fbcb4452d88aaa0f43ccfe436e1554f95bdd883c41e7e8529f
acd7556ba539af3e083e7143ddf8637f67b59eea494b02396ff5089a1964
48dc8f7eb236d2f92a3358d0d6f5af1443205400bbd2758d3ec7cb208c11
7d78d68409f987fd6e43a93a26961c10c05f85458821594d242f8106856c
393f3b971cae1bfc20319e37147b22d2d2179ed5844e8102818100f27c96
e84d6ff814c56996a0e143fa85106d74e2eaa848347d8681bbcc396d85fc
b51d318f543ad25090fe087e0e1ee0202f2ee8674e58609c22cc56e305c5
c55b016d0ca45c847ac88b59dd8a597388b09d7d5f86e2cdf60cb7660d94
a5e4e6f539506a6aacdf67fb9458b016a63d72392129eff5faa210a1739d
948ef0453b02818100daaf65e651382baed753222ab53dfb2f79ef96c6bd
ec1c2822e5b8405900cf9203b2a0e015d12042cc9e686bbf3e5d2d732ed7
45e2a1cc1787637b8f14727dd5da11261d3a7cbe3521296f269cdf2a16ea
2974a710b14f3e61484d2580fef9c5bf4965a7a9ee6055a8c27867609408
7ef1643e81ab17307ca40b79166b693f310281803ed463719ba6f87bc14f
039579e8d83fa42b084f478804f57cd4de469fbafd92eb10ae98c9cf8452
3c47e55aa3f6daaf2e07abbad211adba929a3da201bedc28afd4e5c191d0
db0ec969ba063a33c548d4a269fad7836ae467151a1f48b5d762b4857e3d
a4985866a3fc2322b52babde2dc95709730dd6f2423327d0775cf0430281
8100c4f14336c99c6992bb2e8e4da20de0c21ff14a7b4f9d6cba24bb7754
d412ebdc96e1ef09fffbe72ee172239e2d8c2f83f8008e34cce663942904
c9c8d0644fb920fb62b4ddf06ba813666a487eec67ce5d31da717e920048
b079d9a855e4caf270d3dbedc416fec1060ba53d8c77a4b31617ee46fedb
127a9d8e0b8dca4bed710281800c2fe643bfc8c81b39f1a574c751d2c5ee
0ce836a772197350f2f0a6a4d5248790a0cdf0c25a69a8834d645ea3c96e
e740d95adeea689259ac4ce36a7310c86c9c35441fdd96ff8cec89a65f8c
8666bbc2a42cd2a58e70b1e8b2269ed6307c5a2143cbd41de4682dea4a38
8a7c8d2f4088e9a2008fa986f9b0e92fa517ecc77b
%
% dumpasn1 -p -a rsa-private-key.der
SEQUENCE {
INTEGER 0
INTEGER
00 CF 24 3C 32 4B 26 24 70 13 16 48 61 4B 62 EE
9C 52 AF 43 31 9C 24 98 A7 C1 6B A9 79 0B B3 A8
81 F9 60 F7 B0 30 3F 8F 49 E8 6F ED D6 81 3B E5
FA 88 83 93 55 D0 44 26 DF 00 50 DB B7 71 EB 68
37 73 B7 DD 92 99 49 69 50 93 F9 10 C8 DC DB 63
36 74 DE 98 6A DA 8D 64 3E 0E 81 9B 7C D5 AB 3B
DE 43 72 10 37 97 47 2D C8 43 A2 71 16 99 E2 1A
4A FD DE ED 9F 62 81 03 16 90 34 57 34 2C 34 5A
35 EB B2 F0 6D A0 19 FE D2 AF A5 6E 78 56 6E 75
A0 D7 12 84 9A E2 55 15 5D 93 04 34 83 18 93 06
11 B3 B4 F1 15 3D 77 EE 59 70 F0 76 29 9C 54 8C
8A FF F5 31 57 20 50 48 AD E2 6D 40 93 0A F2 EC
C9 6D 4F 77 E8 59 15 23 B7 67 FA 3C DB C4 5A 8A
21 03 39 C4 A5 56 CE A2 E0 DF A3 EE 81 9B 62 E4
63 F7 5D 87 A5 3C 2F BD 1B BC B8 EC 8F E2 E8 00
0C E3 72 35 FA 90 31 13 C7 B3 7D 9C 2A 8B 39 C5
4B
INTEGER 65537
INTEGER
44 B6 94 71 6A 94 60 89 FD 0A EB 3F BB 2E 3A 51
08 EC B2 B1 86 46 6D 8D 58 90 4A 4B A9 22 13 C7
E9 DD CC CC 59 74 FC 27 5C 3F A4 F9 FF 2C CB 81
6C 3F 99 64 62 0D F9 87 08 27 CA 7A F4 03 4F 32
F5 E4 0C 50 51 21 15 1A 71 BB B1 61 B0 41 E6 8B
6E 01 59 36 39 01 A6 3B 1F BC C6 C3 86 6D A3 12
7B F5 1E 84 12 5E BE 45 2C 8A 7A 51 31 02 DC 0D
FC 61 33 1A 28 26 FB CB 44 52 D8 8A AA 0F 43 CC
FE 43 6E 15 54 F9 5B DD 88 3C 41 E7 E8 52 9F AC
D7 55 6B A5 39 AF 3E 08 3E 71 43 DD F8 63 7F 67
B5 9E EA 49 4B 02 39 6F F5 08 9A 19 64 48 DC 8F
7E B2 36 D2 F9 2A 33 58 D0 D6 F5 AF 14 43 20 54
00 BB D2 75 8D 3E C7 CB 20 8C 11 7D 78 D6 84 09
F9 87 FD 6E 43 A9 3A 26 96 1C 10 C0 5F 85 45 88
21 59 4D 24 2F 81 06 85 6C 39 3F 3B 97 1C AE 1B
FC 20 31 9E 37 14 7B 22 D2 D2 17 9E D5 84 4E 81
INTEGER
00 F2 7C 96 E8 4D 6F F8 14 C5 69 96 A0 E1 43 FA
85 10 6D 74 E2 EA A8 48 34 7D 86 81 BB CC 39 6D
85 FC B5 1D 31 8F 54 3A D2 50 90 FE 08 7E 0E 1E
E0 20 2F 2E E8 67 4E 58 60 9C 22 CC 56 E3 05 C5
C5 5B 01 6D 0C A4 5C 84 7A C8 8B 59 DD 8A 59 73
88 B0 9D 7D 5F 86 E2 CD F6 0C B7 66 0D 94 A5 E4
E6 F5 39 50 6A 6A AC DF 67 FB 94 58 B0 16 A6 3D
72 39 21 29 EF F5 FA A2 10 A1 73 9D 94 8E F0 45
3B
INTEGER
00 DA AF 65 E6 51 38 2B AE D7 53 22 2A B5 3D FB
2F 79 EF 96 C6 BD EC 1C 28 22 E5 B8 40 59 00 CF
92 03 B2 A0 E0 15 D1 20 42 CC 9E 68 6B BF 3E 5D
2D 73 2E D7 45 E2 A1 CC 17 87 63 7B 8F 14 72 7D
D5 DA 11 26 1D 3A 7C BE 35 21 29 6F 26 9C DF 2A
16 EA 29 74 A7 10 B1 4F 3E 61 48 4D 25 80 FE F9
C5 BF 49 65 A7 A9 EE 60 55 A8 C2 78 67 60 94 08
7E F1 64 3E 81 AB 17 30 7C A4 0B 79 16 6B 69 3F
31
INTEGER
3E D4 63 71 9B A6 F8 7B C1 4F 03 95 79 E8 D8 3F
A4 2B 08 4F 47 88 04 F5 7C D4 DE 46 9F BA FD 92
EB 10 AE 98 C9 CF 84 52 3C 47 E5 5A A3 F6 DA AF
2E 07 AB BA D2 11 AD BA 92 9A 3D A2 01 BE DC 28
AF D4 E5 C1 91 D0 DB 0E C9 69 BA 06 3A 33 C5 48
D4 A2 69 FA D7 83 6A E4 67 15 1A 1F 48 B5 D7 62
B4 85 7E 3D A4 98 58 66 A3 FC 23 22 B5 2B AB DE
2D C9 57 09 73 0D D6 F2 42 33 27 D0 77 5C F0 43
INTEGER
00 C4 F1 43 36 C9 9C 69 92 BB 2E 8E 4D A2 0D E0
C2 1F F1 4A 7B 4F 9D 6C BA 24 BB 77 54 D4 12 EB
DC 96 E1 EF 09 FF FB E7 2E E1 72 23 9E 2D 8C 2F
83 F8 00 8E 34 CC E6 63 94 29 04 C9 C8 D0 64 4F
B9 20 FB 62 B4 DD F0 6B A8 13 66 6A 48 7E EC 67
CE 5D 31 DA 71 7E 92 00 48 B0 79 D9 A8 55 E4 CA
F2 70 D3 DB ED C4 16 FE C1 06 0B A5 3D 8C 77 A4
B3 16 17 EE 46 FE DB 12 7A 9D 8E 0B 8D CA 4B ED
71
INTEGER
0C 2F E6 43 BF C8 C8 1B 39 F1 A5 74 C7 51 D2 C5
EE 0C E8 36 A7 72 19 73 50 F2 F0 A6 A4 D5 24 87
90 A0 CD F0 C2 5A 69 A8 83 4D 64 5E A3 C9 6E E7
40 D9 5A DE EA 68 92 59 AC 4C E3 6A 73 10 C8 6C
9C 35 44 1F DD 96 FF 8C EC 89 A6 5F 8C 86 66 BB
C2 A4 2C D2 A5 8E 70 B1 E8 B2 26 9E D6 30 7C 5A
21 43 CB D4 1D E4 68 2D EA 4A 38 8A 7C 8D 2F 40
88 E9 A2 00 8F A9 86 F9 B0 E9 2F A5 17 EC C7 7B
}
Import it with this code:
let u = URL(fileURLWithPath: "rsa-private-key.der")
guard let keyBytes = try? Data(contentsOf: u) else {
… handle error …
}
guard let privateKey = SecKeyCreateWithData(keyBytes as NSData, [
kSecAttrKeyType: kSecAttrKeyTypeRSA,
kSecAttrKeyClass: kSecAttrKeyClassPrivate,
] as NSDictionary, nil) else {
… handle error …
}
print(privateKey)
// prints:
// <SecKeyRef algorithm id: 1, key type: RSAPrivateKey, version: 4, block size: 2048 bits, addr: …>
Finally, an oft-forgotten feature of SecKeyCreateWithData is that it can undo a SubjectPublicKeyInfo wrapper. So, if you have an RSA public key wrapped in a SubjectPublicKeyInfo like this:
% xxd -p public-key-rsa.der
30820122300d06092a864886f70d01010105000382010f003082010a0282
010100bce736006d9b0a2a49508f32e8d66f2b26236263a476f5a2eaf6af
34f0055b12b3bea5f5a62f3aab82274c3e3b21d15cc741100c670dd7687d
9c7e5c012d95bf5177993087df441c9944d10dff0767abfd6e412df279e4
e518b905e5582f967b6b2a64eeaeef712c594268fbff9cc2e63833ebffb7
f00c61fd7224ae2328047e13bbb904899e9ad5c9f44cfff5cd9a2df5a5b6
29bec605d6ecdce5dacba40cb119695f7c3dbd19e6fcd86a13700dfe6818
d1894aca9172a1e857540641971f7d7c9533aee2047c16c1c4f125e830b2
7d5e80d445c2fe09fa5586ee0bb105800fd1e8489e44b2f123eeef1cceeb
eb1ba2d094923944181c513208c1f37fca31e50203010001
%
% dumpasn1 -p -a public-key-rsa.der
SEQUENCE {
SEQUENCE {
OBJECT IDENTIFIER rsaEncryption (1 2 840 113549 1 1 1)
NULL
}
BIT STRING, encapsulates {
SEQUENCE {
INTEGER
00 BC E7 36 00 6D 9B 0A 2A 49 50 8F 32 E8 D6 6F
2B 26 23 62 63 A4 76 F5 A2 EA F6 AF 34 F0 05 5B
12 B3 BE A5 F5 A6 2F 3A AB 82 27 4C 3E 3B 21 D1
5C C7 41 10 0C 67 0D D7 68 7D 9C 7E 5C 01 2D 95
BF 51 77 99 30 87 DF 44 1C 99 44 D1 0D FF 07 67
AB FD 6E 41 2D F2 79 E4 E5 18 B9 05 E5 58 2F 96
7B 6B 2A 64 EE AE EF 71 2C 59 42 68 FB FF 9C C2
E6 38 33 EB FF B7 F0 0C 61 FD 72 24 AE 23 28 04
7E 13 BB B9 04 89 9E 9A D5 C9 F4 4C FF F5 CD 9A
2D F5 A5 B6 29 BE C6 05 D6 EC DC E5 DA CB A4 0C
B1 19 69 5F 7C 3D BD 19 E6 FC D8 6A 13 70 0D FE
68 18 D1 89 4A CA 91 72 A1 E8 57 54 06 41 97 1F
7D 7C 95 33 AE E2 04 7C 16 C1 C4 F1 25 E8 30 B2
7D 5E 80 D4 45 C2 FE 09 FA 55 86 EE 0B B1 05 80
0F D1 E8 48 9E 44 B2 F1 23 EE EF 1C CE EB EB 1B
A2 D0 94 92 39 44 18 1C 51 32 08 C1 F3 7F CA 31
E5
INTEGER 65537
}
}
}
Import it with this code:
let u = URL(fileURLWithPath: "public-key-rsa.der")
guard let keyBytes = try? Data(contentsOf: u) else {
… handle error …
}
guard let privateKey = SecKeyCreateWithData(keyBytes as NSData, [
kSecAttrKeyType: kSecAttrKeyTypeRSA,
kSecAttrKeyClass: kSecAttrKeyClassPublic,
] as NSDictionary, nil) else {
… handle error …
}
print(privateKey)
// prints:
// <SecKeyRef algorithm id: 1, key type: RSAPublicKey, version: 4, block size: 2048 bits, exponent: {hex: 10001, decimal: 65537}, modulus: …, addr: …>
Import SECG Keys with Security Framework
If you’re working with Security framework, use SecKeyCreateWithData to import an SECG key. If you have a secp256r1 public key in X9.63 format:
% xxd p256-public-key.dat
00000000: 0497 47e9 81aa b8ea 71a2 55cd 9a15 6285 ..G.....q.U...b.
00000010: 8c40 6006 f1e4 1826 0d31 e1a7 7f6c 2b35 .@`....&.1...l+5
00000020: a9a3 132f 232d b003 51d9 d800 3487 d4ee .../#-..Q...4...
00000030: 5284 7990 313d aa7c 721f 88d4 bb56 da91 R.y.1=.|r....V..
00000040: c7 .
Import it with this code:
let u = URL(fileURLWithPath: "p256-public-key.dat")
guard let keyBytes = try? Data(contentsOf: u) else {
… handle error …
}
guard let privateKey = SecKeyCreateWithData(keyBytes as NSData, [
kSecAttrKeyType: kSecAttrKeyTypeECSECPrimeRandom,
kSecAttrKeyClass: kSecAttrKeyClassPublic,
] as NSDictionary, nil) else {
… handle error …
}
print(privateKey)
// prints:
// <SecKeyRef curve type: kSecECCurveSecp256r1, algorithm id: 3, key type: ECPublicKey, version: 4, block size: 256 bits, y: …, x: …, addr: …>
Note I’m using secp256r1 as an example. The code in this section will work for the other SECG key types, secp384r1 and secp521r1.
And if you have a secp256r1 private key in X9.63 format:
% xxd p256-private-key.dat
00000000: 0497 47e9 81aa b8ea 71a2 55cd 9a15 6285 ..G.....q.U...b.
00000010: 8c40 6006 f1e4 1826 0d31 e1a7 7f6c 2b35 .@`....&.1...l+5
00000020: a9a3 132f 232d b003 51d9 d800 3487 d4ee .../#-..Q...4...
00000030: 5284 7990 313d aa7c 721f 88d4 bb56 da91 R.y.1=.|r....V..
00000040: c798 6a7a 91cb b5f4 f816 36e8 1aaf f083 ..jz......6.....
00000050: 5a77 1dc6 6865 c407 a8e8 4469 cf6a b8a4 Zw..he....Di.j..
00000060: 77 w
Import it with this code:
let u = URL(fileURLWithPath: "p256-private-key.dat")
guard let keyBytes = try? Data(contentsOf: u) else {
… handle error …
}
guard let privateKey = SecKeyCreateWithData(keyBytes as NSData, [
kSecAttrKeyType: kSecAttrKeyTypeECSECPrimeRandom,
kSecAttrKeyClass: kSecAttrKeyClassPrivate,
] as NSDictionary, nil) else {
… handle error …
}
print(privateKey)
// prints:
// <SecKeyRef curve type: kSecECCurveSecp256r1, algorithm id: 3, key type: ECPrivateKey, version: 4, block size: 256 bits, addr: …>
Import SECG Keys with Apple CryptoKit
Apple CryptoKit can import SECG keys in three different ways:
X9.63 raw key bytes
DER encoding
PEM encoding
If you have a secp256r1 public key in X9.63 format, import it with this code:
let u = URL(fileURLWithPath: "p256-public-key.dat")
guard let keyBytes = try? Data(contentsOf: u) else {
… handle error …
}
guard let publicKey = try? P256.Signing.PublicKey(x963Representation: keyBytes) else {
… handle error …
}
print(publicKey)
// prints:
// PublicKey(impl: CryptoKit.CoreCryptoNISTCurvePublicKeyImpl<CryptoKit.P256.CurveDetails>(keyBytes: […]]))
Note I’m using secp256r1 as an example. The code in this section will work for the other SECG key types, secp384r1 and secp521r1.
If you have a secp256r1 private key in X9.63 format import it with this code:
let u = URL(fileURLWithPath: "p256-private-key.dat")
guard let keyBytes = try? Data(contentsOf: u) else {
… handle error …
}
guard let privateKey = try? P256.Signing.PrivateKey(x963Representation: keyBytes) else {
… handle error …
}
print(privateKey)
// prints:
// PrivateKey(impl: CryptoKit.CoreCryptoNISTCurvePrivateKeyImpl<CryptoKit.P256.CurveDetails>(key: CryptoKit.SecureBytes(backing: CryptoKit.SecureBytes.Backing)))
CryptoKit can also import a DER-encoded SECG key. For example, it can import the following using the init(derRepresentation:) initialiser:
% xxd -p public-key-p256.der
3059301306072a8648ce3d020106082a8648ce3d030107034200042c21f3
7049d4464afbf01813c51a4e1ef7a8101d2aa12b6a889635bc7c37e9011b
fdd54006fdebdaef0d86a6d662561347982c95276013d1c1cd2d7865aff0
23
%
% dumpasn1 -p -a public-key-p256.der
SEQUENCE {
SEQUENCE {
OBJECT IDENTIFIER ecPublicKey (1 2 840 10045 2 1)
OBJECT IDENTIFIER prime256v1 (1 2 840 10045 3 1 7)
}
BIT STRING
04 2C 21 F3 70 49 D4 46 4A FB F0 18 13 C5 1A 4E
1E F7 A8 10 1D 2A A1 2B 6A 88 96 35 BC 7C 37 E9
01 1B FD D5 40 06 FD EB DA EF 0D 86 A6 D6 62 56
13 47 98 2C 95 27 60 13 D1 C1 CD 2D 78 65 AF F0
23
}
%
% xxd -p private-key-p256.der
308187020100301306072a8648ce3d020106082a8648ce3d030107046d30
6b0201010420986a7a91cbb5f4f81636e81aaff0835a771dc66865c407a8
e84469cf6ab8a477a144034200049747e981aab8ea71a255cd9a1562858c
406006f1e418260d31e1a77f6c2b35a9a3132f232db00351d9d8003487d4
ee52847990313daa7c721f88d4bb56da91c7
%
% dumpasn1 -p -a private-key-p256.der
SEQUENCE {
INTEGER 0
SEQUENCE {
OBJECT IDENTIFIER ecPublicKey (1 2 840 10045 2 1)
OBJECT IDENTIFIER prime256v1 (1 2 840 10045 3 1 7)
}
OCTET STRING, encapsulates {
SEQUENCE {
INTEGER 1
OCTET STRING
98 6A 7A 91 CB B5 F4 F8 16 36 E8 1A AF F0 83 5A
77 1D C6 68 65 C4 07 A8 E8 44 69 CF 6A B8 A4 77
[1] {
BIT STRING
04 97 47 E9 81 AA B8 EA 71 A2 55 CD 9A 15 62 85
8C 40 60 06 F1 E4 18 26 0D 31 E1 A7 7F 6C 2B 35
A9 A3 13 2F 23 2D B0 03 51 D9 D8 00 34 87 D4 EE
52 84 79 90 31 3D AA 7C 72 1F 88 D4 BB 56 DA 91
C7
}
}
}
}
Finally, CryptoKit can import a PEM-encoded SECG. For example, it can import the following using the init(pemRepresentation:) initialiser:
% cat public-key-p256.pem
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAELCHzcEnURkr78BgTxRpOHveoEB0q
oStqiJY1vHw36QEb/dVABv3r2u8NhqbWYlYTR5gslSdgE9HBzS14Za/wIw==
-----END PUBLIC KEY-----
% cat private-key-p256.pem
-----BEGIN PRIVATE KEY-----
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgmGp6kcu19PgWNuga
r/CDWncdxmhlxAeo6ERpz2q4pHehRANCAASXR+mBqrjqcaJVzZoVYoWMQGAG8eQY
Jg0x4ad/bCs1qaMTLyMtsANR2dgANIfU7lKEeZAxPap8ch+I1LtW2pHH
-----END PRIVATE KEY-----
Mapping SECG Keys between Apple CryptoKit and Security Framework
If you need to map an SECG key from Apple CryptoKit to Security framework, or vice versa, use the X9.63 format.
Imagine that you’re working in Security framework but you need to import a PEM key. SecKeyCreateWithData will not accept an SECG key in PEM format; it requires that the key be in X9.63 format. CryptoKit can import a PEM key but you want to continue using your existing Security framework code. Fortunately there’s a way out of this bind:
Import the PEM key using Apple CryptoKit.
Get the X9.63 representation.
Create the Security framework key from that.
For example, the following routine imports a PEM secp256r1 private key and returns a SecKey object:
func createSecKeyWithPEMSecp256r1Private(_ pem: String) throws -> SecKey {
let privateKeyCK = try P256.Signing.PrivateKey(pemRepresentation: pem)
let x963Data = privateKeyCK.x963Representation
var errorQ: Unmanaged<CFError>? = nil
guard let privateKeySF = SecKeyCreateWithData(x963Data as NSData, [
kSecAttrKeyType: kSecAttrKeyTypeECSECPrimeRandom,
kSecAttrKeyClass: kSecAttrKeyClassPrivate,
] as NSDictionary, &errorQ) else {
throw errorQ!.takeRetainedValue()
}
return privateKeySF
}
To go the other way, from Security framework to CryptoKit, call SecKeyCopyExternalRepresentation to get the X9.63 representation of the key and then create a CryptoKit value using the init(x963Representation:) initialiser.
Importing Curve 25519 Keys
Apple CryptoKit supports Curve 25519 keys. If you have the raw bytes of a Curve 25519 public key:
% xxd curve25519-public-key.dat
00000000: 910b f46f 0c0d c836 878f a708 60fd de21 ...o...6....`..!
00000010: 9d5f 6265 0a83 a7c5 923d 2ab7 4b81 76c5 ._be.....=*.K.v.
Import it with this code:
let u = URL(fileURLWithPath: "curve25519-public-key.dat")
guard let keyBytes = try? Data(contentsOf: u) else {
… handle error …
}
guard let publicKey = try? Curve25519.Signing.PublicKey(rawRepresentation: keyBytes) else {
… handle error …
}
print(publicKey)
// prints:
// PublicKey(baseKey: CryptoKit.Curve25519.Signing.CoreCryptoCurve25519PublicKeyImpl(keyBytes: […]))
If you have the raw bytes of a Curve 25519 private key:
% xxd curve25519-private-key.dat
00000000: 9fd9 0805 255b ae86 a6c3 035b 2de8 37e9 ....%[.....[-.7.
00000010: 29ea 792e a11f d466 e67e d0b2 65c0 a999 ).y....f.~..e...
Import it with this code:
let u = URL(fileURLWithPath: "curve25519-private-key.dat")
guard let keyBytes = try? Data(contentsOf: u) else {
… handle error …
}
guard let privateKey = try? Curve25519.Signing.PrivateKey(rawRepresentation: keyBytes) else {
… handle error …
}
print(privateKey)
// prints:
// PrivateKey(baseKey: CryptoKit.Curve25519.Signing.CoreCryptoCurve25519PrivateKeyImpl(key: CryptoKit.SecureBytes(backing: CryptoKit.SecureBytes.Backing)))
Revision History
2025-02-04 Added a link to Importing a PEM-based RSA Private Key and its Certificate. Made other minor editorial changes.
2021-05-23 First posted.
I am experiencing an issue with Apple Sign-In on Vision Pro. When I build and run the app from Xcode, everything works fine—after signing in, the app returns to the foreground as expected.
However, when I launch the app directly on Vision Pro (not from Xcode), after completing the sign-in process, the app does not reopen from the background automatically. Instead, it closes, and I have to manually tap the app icon to reopen it.
Has anyone else encountered this issue? Is there a way to ensure the app properly resumes after sign-in without requiring manual intervention?
We are currently trying to fix a bug when using SignIn with Apple. It appears that on some occasions we are not receiving a user's profile info (name, email) when a new account is created.
After doing some investigation we believe this bug is due to the same Apple login being used as an already deleted account. ASF only appears to send profile info the very first time an Apple login is used. If that account is deleted and another is created with the same apple login we won't receive the profile info.
As a result we are not in compliance with Apple's guidelines requiring that we use the provided profile info with Apple SigIn, and need to prompt users to enter it again.
Is there a process in place to properly "clear" a user after their account is deleted in our system, so that the next time a user creates an account with the same Apple login, we receive their profile info again?
Hello! Few month ago i did get hacked on my pc and then my android and iphone. Did get at notice that payments couldent draw. lucky I only had 240kr on lunar card that it did draw 200kr to a gift card. Did get mail from skrill that a account whas created with one of my Gmail’s. Tryed to log them out but window did keep close. Gmail did flag like crazy and wanted me to change pw. how the fuck when I lost control of my phone?!?!??! Just lock it god Damn. let’s make it short! I shared network to pc from my phone With usb. I don’t just think it whas a attacker program as Gmail did flag. I think I did get mirror linked on my android and maybe my iphone. Had a real struggle to reset my pc and phones before it worked. My iPhone drains battery like crazy and feels laggy sometimes. A non registered number whas added to two Gmail’s that they did try to change pw multiple times. did notice I Linux pc activity on my fb and some other stuff. My iphone do reboot still sometimes and every second reboot wifi/bluet can’t be activated and mobile share change pw as the original one did look. Next reboot all work and are the same again. Iam scared that iam still hacked or havent removed him from everything. How can I make sure that Iam still not mirror linked and that he or she can’t access anything? Sorry for the long text but iam scared as fuck.
Topic:
Privacy & Security
SubTopic:
General
completeRequestWithTextToInsert is used to return text into an arbitrary textfield via the context menu AutoFill/Passwords from a 3rd party password manager (or presumably the Passwords App) in iOS 18.
While testing this feature in the debugger, it would often fail on the first invocation. It also appears to happen intermittently in the released app extension. Subsequent testing using the Passwords App shows it too may fail to return a value.
I have confirmed this behaviour is repeatable with the Passwords App on an iPhone running iOS 18.3.1
Reboot the iPhone.
Show the App Library, and right click Autofill.
Select Passwords
Select Passwords (App)
Select a password.
Nothing will be inserted (intermittently).
Feedback assistant report: FB16788563
Hi,
I've recently tested my custom AuthorizationPlugin on macOS 15 (Sequoia) and I'm seeing a significant change in rendering (or precisely not rendering) the control returned by my SFAuthorizationPluginView's subclass' viewForType method comparing to macOS 14. (I developed and tested my solution on macOS 14 earlier this year).
I use SFAuthorizationPluginView to present a NSView (Custom view) which contains a NSSecureTextField and a NSImageView. I show my custom plugin after the user successfully entered username and password (or only the password if the List of Users is configured in System Settings) into the builtin fields provided by loginwindow:login, so injecting my plugin:mechanism pair into the system.login.console after loginwindow:success. (I need to run my mechanism after builtin:authenticate,privileged since my plugin relies on the authentication result coming from my custom PAM module).
This setup now however doesn't seem to be working: after entering the (username and) password, the circular spinner appears and my NSView never gets rendered. I've found a workaround to place my plugin:mechanism pair after loginwindow:done, so in the end of the whole authorization chain.
I tried to run the good old NameAndPassword bundle, injecting it into the place of the loginwindow:login. Controls are being rendered correctly, but if I place it even right after loginwindow:login it doesn't get rendered as my custom plugin.
Is anybody aware if there's anything has intentionally been changed in macOS 15? Or may it be a bug? I guess the original intention of the SFAuthorizationPluginView class was to overwrite/redefine the UI instead of the builtin username + password field, so if I look at it that way it's expected that the view it contains only gets rendered if we use it instead of loginwindow:login. On the other hand this hasn't been the case until now.
Thanks for any help!
Context
We are experiencing inconsistent behaviour with "Sign in with Apple" across different environments (we have an app for "A" and "B" regions) on our web client in browsers.
Specifically, we have observed two key issues:
Missing email and email_verified Claims in ID Token
In some cases, the ID token received after successful authentication does not contain the email and email_verified claims.
Here the docs state that "Alternatively, if the managed Apple ID is in Apple School Manager, the email claim may be empty. Students, for example, often don’t have an email that the school issues.", but this was experienced with a non-student Apple ID.
This issue was observed for certain users in the "A" environment, while the same users had no issues in the "B" environment.
For one affected user, removing and re-enabling the "Sign in with Apple" integration resolved the issue (https://account.apple.com/account/manage/section/security).
However, for another user, the integration could not be removed, preventing this workaround (button was active, but did nothing).
In contrast, for some users, authentication works correctly in both environments without missing claims.
Inconsistent Display of App Icon and App Name
The app icon and app name do not always appear on the Apple login interface.
One user observed that the app icon and name were displayed in "A" but not in "B".
Another user had the opposite experience, with the app icon and name appearing in "B" but not in "A".
A third user did not see the app icon or name in either environment.
Questions
Why does the app icon and name not always appear on the "Sign in with Apple" login screen?
How is it possible that the ID token sometimes lacks email and email_verified claims when using the same Apple ID in different environments?
After registe Passkey with webauthn library, i create a passkeyRegistration with follow,
let passkeyRegistration = ASPasskeyRegistrationCredential(relyingParty: serviceIdentifier, clientDataHash: clientDataHashSign, credentialID: credentialId, attestationObject: attestationObject)
and then completeRegistrationRequest like that,
extensionContext.completeRegistrationRequest(using: passkeyRegistration)
But a bad outcome occurred from user agent. NotAllowedError:The request is not allowed by the user agent or the platform in the current context.
And the return data rawID & credentialPublicKey is empty,
Topic:
Privacy & Security
SubTopic:
General
Tags:
Autofill
Authentication Services
Passkeys in iCloud Keychain
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.
I’ve explained this point many times on the forums, so I figured I’d write it up properly once and for all.
If you have questions or comments, start a new thread in Privacy & Security > General and add the App Sandbox tag. That way I’ll be sure to see it.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
The Case for Sandboxing a Directly Distributed App
Many folks consider the App Sandbox to be a binary choice:
“My app ships in the Mac App Store, so I must sandbox it.”
“I directly distribute my app, so I’ll ignore the App Sandbox.”
However, those are not your only options. In many cases it makes sense to sandbox a directly distributed app. Sandboxing your app has at least three benefits:
It enables app container protection. See Trusted Execution Resources for a link to more info on that.
If your app includes any app extensions, it simplifies your development experience because your app and its extensions run in a similar environment.
It improves your app’s security (although the actual benefits vary based on the specifics of your app).
Sandboxing some apps can be tricky because of the additional security limits applied by the sandbox. However, in a directly distributed app you have access to two techniques that are not available to Mac App Store apps:
Temporary exception entitlements
Non-sandboxed XPC services
Temporary exception entitlements
Use temporary exception entitlements to selectively disable specific sandbox security limits.
Imagine, for example, that you’re creating a simple document-based app that’s generally compatible with the sandbox. However, that app needs to send an Apple event to Music to create a playlist. That Apple event is blocked by the sandbox. You don’t need to disable the entire App Sandbox just to get around this security limit. Instead, use the com.apple.security.temporary-exception.apple-events entitlement to open a small hole in the sandbox.
There are temporary exception entitlements to disable most sandbox security limits. For more information about them, follow the link in App Sandbox Resources.
IMPORTANT Don’t be alarmed by the temporary in temporary exception entitlements. That word makes sense when you view this from the Mac App Store perspective. Back in the early days of the Mac App Store, some apps were allowed to use temporary exception entitlements because of limitations in the App Sandbox. Once App Sandbox was sufficiently enhanced, these temporary exception entitlements were no longer allowed in the Mac App Store. However, there’s nothing temporary about the implementation of these entitlements. They work today and are expected to continue working in the future. Using them in a directly distributed app is not a problem.
Non-sandboxed XPC services
Not all sandbox security limits have a corresponding temporary exception entitlement. For example, the sandbox prevents you from sending a Unix signal to other processes, and there’s no temporary exception entitlement to allow that.
If you run into such a limit, move that code to a non-sandboxed XPC service, then have the main app request that the XPC service perform the operation on its behalf.
An XPC service can be useful even when there is a temporary exception entitlement to disable a specific sandbox security limit. Continuing the Apple event example from above, if you put the code that sends the Apple event into an XPC service, you only need to apply the temporary exception entitlement to that service, not to your app as a whole.
Conclusion
If you directly distribute your app, consider enabling the App Sandbox. It has some important benefits, and it might be more feasible than you think.
Hi,
We are trying to open an application "xyz.app"
It worked fine until 15.1.1 versions. But facing issues with 15.2 and 15.3
The application is working fine when we navigate to xyz.app/Contents/MacOS/ and run applet in this directory.
But the error ""Not authorized to send Apple events to Finder"" occurs when we are trying to open the app directly.
Could someone please help me understand what might be causing this issue and how to resolve it?
Topic:
Privacy & Security
SubTopic:
General
Our service has ended and the app has been removed from the App store.
This app supported Sign in with Apple, but even if I try to revoke the account from the iOS settings or account.apple.com on the web, but can't delete it and no error is displayed.
Does anyone know the cause of this problem or have encountered it?
I'm not sure if it's related, but this app was previously transferred from another organization.
We currently have an app that uses Sign in with Apple (SIWA), and we are planning to discontinue the SIWA feature. Specifically, we intend to disable SIWA from the app's Capabilities in the Apple Developer Center.
My question is, if we disable SIWA, can we continue to use the private email addresses of users who registered using SIWA? Or will disabling SIWA also invalidate the users' private email addresses?
We are considering asking users to change to a different, valid email address in our app. However, if the private email addresses are invalidated, we will not be able to disable SIWA until all users have completed the email address change.
If anyone has knowledge about these behaviors, please let us know.
在我的蜂窝数据中出现了一个名为BusinessExtensionsWrapper的程序组件,是个灰色的点不动,我好奇这是什么程序组件,既然是系统自带的,为什么要隐藏呢?对隐私有威胁吗?
Topic:
Privacy & Security
SubTopic:
General
I'm using the following code to store a Keychain item:
SecAccessControlCreateWithFlags(
kCFAllocatorDefault,
kSecAttrAccessibleWhenUnlockedThisDeviceOnly,
.biometryAny,
&error
)
One of my app users reported an issue:
1. The user navigated to his iPhone’s Face ID settings and click `Reset Face ID`.
2. Then, before he set new Face ID, he accidentally tapped the "Back" button and returned to the iPhone Settings page.
3. He later reopened the Face ID setup page and completed the process.
4. Upon returning to my app, the Keychain item secured by Face ID was no longer found.
I understand that .biometryAny may cause Keychain items to become invalidated when biometric data is reset. However, the user’s scenario — where the setup was temporarily interrupted — seems to have caused the item to disappear.
1. Is there a way to detect and handle such interruptions to prevent the Keychain item from being lost?
2. How can I design a better experience to guide the user in recreating the Keychain item when this occurs?
Topic:
Privacy & Security
SubTopic:
General
Hello,
We plan to remove our app from the App Store. This post aims to determine whether our company can rely on Private Relay to compensate our customers.
Our Challenge: Gift Card Refunds with Private Relay
Some customers purchased gift cards through our app using Apple's "Private Relay" during account creation. To process refunds, we need a way to identify these customers. Our system relies on email addresses, which are masked by Private Relay.
Potential Solution: Apps Using Apple ID
We're exploring "Apps Using Apple ID" as a possible solution for customers to share their Private Relay addresses for refund purposes.
Under what circumstances will an app cease to appear in the "Apps Using Apple ID" list?
What conditions must be met to initiate a new Private Relay connection for the same user and application? For example, would using the same Apple account to sign into the app on a different device trigger a new Private Relay?
Thank you for your help!
I'm currently working on a project in Swift where I need to digitally sign a PDF file. I have the following resources available:
Private Key stored in the iOS Keychain with a tag. Public Key also stored in the iOS Keychain with a tag. A valid certificate stored as a PEM string. I need to digitally sign a PDF file with the above keys and certificate, but I'm struggling to find a clear and straightforward example or guidance on how to achieve this in Swift.
Specifically, I’m looking for help with:
Creating the digital signature using the private key and certificate. Embedding this signature into the PDF file. Any considerations I should be aware of regarding the format of the signed PDF (e.g., CMS, PKCS7, etc.). If anyone has experience with digitally signing PDFs in Swift, I would greatly appreciate your guidance or code examples.
Thank you in advance!
My application is supporting hybrid transport on FIDO2 webAuthn specs to create credential and assertion. And it support legacy passkeys which only mean to save to 1 device and not eligible to backup.
However In my case, if i set the Backup Eligibility and Backup State flag to false, it fails on the completion of the registrationRequest to save the passkey credential within credential extension, the status is false instead of true.
self.extension.completeRegistrationRequest(using: passkeyRegistrationCredential)
The attestation and assertion flow only works when both flags set to true.
Can advice why its must have to set both to true in this case?
Our company developed an app that relies on the collected list to display the phone's label in the list when the user's phone receives an incoming call. However, we have been rejected. The main reason for the rejection is as follows:
“ Guideline 1.1.6 - Safety - Objectionable Content
The app still allows users to unblock and reveal blocked incoming numbers to identify the individual calling or texting, which is not appropriate. Specifically, your app claims to offer the call blocking functionality, but solely identifies numbers that the user has explicitly blocked themselves.
Since users can choose to hide their caller ID in iPhone Settings, apps should not attempt to circumvent this iOS feature to reveal the caller's number. ”
But our developers clearly stated that there is no way to bypass these settings, and CallDirectory Extensionde cannot directly "unlock hidden numbers" or bypass the built-in restrictions of IOS. We don't know how to solve this problem next, and hope to get everyone's help.
Topic:
Privacy & Security
SubTopic:
General