Apple CryptoKit

RSS for tag

Perform cryptographic operations securely and efficiently using Apple CryptoKit.

Apple CryptoKit Documentation

Pinned Posts

Posts under Apple CryptoKit tag

33 Posts
Sort by:
Post not yet marked as solved
0 Replies
2.0k Views
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 frameworks: DevForums tags: Security Foundation, Security Interface Security Foundation framework documentation Security Interface framework documentation 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"
Posted
by eskimo.
Last updated
.
Post marked as solved
2 Replies
142 Views
Is it possible? The original key was generated and stored in the Keychain using the following code: func generateSecureEnclaveProtectedSecKey(withTag tag: Data) throws -> SecKey { var error: Unmanaged<CFError>? let accessControl = SecAccessControlCreateWithFlags( kCFAllocatorDefault, kSecAttrAccessibleWhenUnlockedThisDeviceOnly, [.privateKeyUsage], &error )! let attributes = [ kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom, kSecAttrKeySizeInBits as String: 256, kSecAttrTokenID as String: kSecAttrTokenIDSecureEnclave, kSecPrivateKeyAttrs as String: [ kSecAttrCanSign as String: true, kSecAttrIsPermanent as String: true, kSecAttrApplicationTag as String: tag, kSecAttrAccessControl as String: accessControl, ] as [String: Any], ] as [String: Any] let privateKey = SecKeyCreateRandomKey(attributes as CFDictionary, &error)! return privateKey } Then I wanted to use the strongly typed interface of CryptoKit, so I naively tried to get a hold of the existing key as follows (querying for kSecReturnPersistentRef and not kSecReturnRef): func getSecureEnclaveProtectedCryptoKitKey(fromSecureEnclaveProtectedSecKeyWithTag tag: Data) throws -> SecureEnclave.P256.Signing.PrivateKey { let query: [String: Any] = [ kSecClass as String: kSecClassKey, kSecAttrApplicationTag as String: tag, kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom, kSecReturnPersistentRef as String: true, ] var item: CFTypeRef? let status = SecItemCopyMatching(query as CFDictionary, &item) let keyData = item as! CFData return try SecureEnclave.P256.Signing.PrivateKey(dataRepresentation: keyData as Data) } But that resulted in: Error Domain=CryptoTokenKit Code=-3 "corrupted objectID detected" UserInfo={NSLocalizedDescription=corrupted objectID detected} Since this is a Secure Enclave protected key, it is not possible to use SecKeyCopyExternalRepresentation (or query for kSecReturnData), but perhaps there is another way to convert a SecKey object to a SecureEnclave.P256.Signing.PrivateKey? The other way around seem to be possible using the answers to this blog post: https://developer.apple.com/forums/thread/728314
Posted
by Smed1.
Last updated
.
Post not yet marked as solved
1 Replies
159 Views
I am trying to communicate with a Java server over TCP, but I'm having issues trying to make the data secure in transit using RSA and AES. The server creates an AES key, encodes it in utf8, and sends it to the IOS Client, where it should be decoded back into a byte array as a Data object. Then, Using the Cryptokit framework, I try to create a SecKey object from it. I am stumped when trying to do so, though: func createSecKeyFromAESKeyData(aesKeyData: Data) -&gt; SecKey? { // Define the key attributes let keyAttributes: [CFString: Any] = [ kSecAttrKeyClass: kSecAttrKeyClassSymmetric, kSecAttrKeySizeInBits: 128, kSecAttrIsPermanent: false ] // Convert the AES key data into a SecKey object var error: Unmanaged&lt;CFError&gt;? guard let key = SecKeyCreateWithData(aesKeyData as CFData, keyAttributes as CFDictionary, &amp;error) else { if let error = error { print("Error creating SecKey: \(error.takeRetainedValue() as Error)") } else { print("Unknown error creating SecKey") } return nil } return key } Despite setting up my key attribute dictionary with the correct information (AES_128_GCM_SHA256, 128 bits, impermanent) based on how I generate it in the Java code, I keep getting a runtime error at the SecKeyCreateWithData call stating "Unsupported symmetric key type: 4865". I am unsure what this means and how to fix it as there doesn't seem to be any information on it online. If it helps, the Java code is using AES GCM with no padding, and we have confirmed that the data being sent is indeed 128 bits. How can I take this byte array and create a SecKey from it properly so we can pass secure data? Similarly, I have also tried using RSA encryption for some data, but with this method, I generate the key pair on the iOS client and send the parts of the public key to the Java server where it (seemingly correctly) created the cipher from the passed data. However, trying to send anything encrypted back resulted in "RSAdecrypt wrong input (err -27)" when decrypting: func decryptAESKey(encryptedKeyData: Data, privateKey: SecKey) -&gt; Data? { // Decrypt the received AES key using the private key var error: Unmanaged&lt;CFError&gt;? guard let decryptedKeyData = SecKeyCreateDecryptedData(privateKey, .rsaEncryptionOAEPSHA256, encryptedKeyData as CFData, &amp;error) as Data? else { print("Error decrypting AES key:", error!.takeRetainedValue() as Error) return nil } return decryptedKeyData } Any assistance in figuring out how to properly use SecKeys in these ways would be greatly appreciated. Additionally, the relevant Java code can be provided if necessary.
Posted
by WKUXrLab.
Last updated
.
Post not yet marked as solved
2 Replies
233 Views
Quick Summary I'm having trouble using SecKeyCreateSignature(deviceSigningKeyRef, .ecdsaSignatureMessageX962SHA256, digest, &amp;error) but when using SecureEnclave.P256.KeyAgreement.PrivateKey().signature(for: digest) the other code I'm using to verify succeeds. Full use case and code If I just initiate a SecureEnclave.P256.KeyAgreement.PrivateKey() class variable and then later use signature(for: digest).rawRepresentation to generate a signature, I get a signature value that can be passed to the verifying code class MyClass { var myPrivateKey: SecureEnclave.P256.KeyAgreement.PrivateKey? init() { myPrivateKey = SecureEnclave.P256.KeyAgreement.PrivateKey() let myPublicKey = myPrivateKey?.publicKey.rawRepresentation } func createAndSendSignature(_ digest: Data) { let signature = try? myPrivateKey?.signature(for: digest).rawRepresentation // 64 bytes sendSignatureWithDigest(signature, digest) } } But if I create my key in keychain via Secure Enclave with the way the documentation recommends (here's a few links to start Signing/Verifying, Keys for encryption), and then retrieve the key representation and use SecKeyCreateSignature, the resulting signature (which I manipulate a little more because it is DER encoded and does not comes back as 64 bytes) fails against the verifying code. class MyClass { var myKeyTag: String = "myKeyTag" func createAndStoreKey() { let access = SecAccessControlCreateWithFlags( kCFAllocatorDefault, kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly, .privateKeyUsage, nil)! // Ignore errors. let attributes: NSDictionary = [ kSecClass as String: kSecClassKey, kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom, kSecAttrKeySizeInBits as String: 256, kSecAttrTokenID: kSecAttrTokenIDSecureEnclave, kSecPrivateKeyAttrs as String: [ kSecAttrIsPermanent as String: true, kSecAttrApplicationTag as String: myKeyTag, kSecAttrAccessControl as String: access, kSecAttrCanSign as String: true, ] ] var error: Unmanaged&lt;CFError&gt;? guard let keyRef: SecKey = SecKeyCreateRandomKey(attributes as CFDictionary, &amp;error) else { throw error!.takeRetainedValue() as Error } return keyRef as SecKey! } func getKey(){ let query: [String: Any] = [ kSecClass as String: kSecClassKey, kSecAttrApplicationTag as String: myKeyTag, kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom, kSecReturnRef as String: true, ] var item: CFTypeRef? let status = SecItemCopyMatching(query as CFDictionary, &amp;item) guard status == errSecSuccess else { throw KeyStoreError("Unable to retrieve key: \(status.message)") } return (item as! SecKey) } func createAndSendSignature(_ digest: Data) { let privKey = getKey() let signature = SecKeyCreateSignature( privKey, .ecdsaSignatureMessageX962SHA256, digest as CFData, &amp;error) as Data? else { print(error) return } // bytes varry due to DER encoding and R and S values let ecdsaSignature = try P256.Signing.ECDSASignature(derRepresentation: signature) let signatureBytes = ecdsaSignature.rawRepresentation sendSignatureWithDigest(signatureBytes, digest) } } An important note: digest is not an actual digest but a message that needs to be hashed to turn into a digest? Sorry if that sounds off, my security knowledge is limited. Please forgive any syntax errors, I can't copy and paste the code and am just extracting the important elements. Anything helps, thanks!
Posted
by dlew0000.
Last updated
.
Post not yet marked as solved
2 Replies
330 Views
Hi, I have a String that I want to: encrypt it using a key. generate that key with the Secure Enclave store the key in the secure enclave next time the user opens the app: read the key from the secure enclave. decrypt the string back. Is it possible? I know the Secure Enclave can help me generate a key, but how to store or retrieve it? Is it possible to do that with CryptoKit?
Posted Last updated
.
Post not yet marked as solved
2 Replies
425 Views
My goal is: Generate a public and private key pair Add the private key to the keychain and protect it with the secure enclave Create a self-signed certificate with the public key and send it to a server Add the certificate to the keychain When I communicate with the server I want to create a SecIdentity during the client challenge which is basically a SecCertificate + SecKey combo. For the certificate generation I would like to use the swift-certificates library to not have to compose manually the certificate fields and signature. My problem is that the swift-certificates during the Certificate initialisation needs a SecureEnclave.P256.Signing.PrivateKey private key and to add a key to the keychain we need a SecKey object. And unfortunately there is no clean way to create from one of them the other one. I read several threads here about this, but I haven't found a clean solution for it. I tried to approach the problem from two directions: First: Create the key with the SecKeyCreateRandomKey, mark in the attributes that I want to protect the key with secure enclave and also mark that I want the private key to be kSecAttrIsPermanent so it is automatically saved in the keychain The SecKeyCreateRandomKey returns a SecKey which is a reference to the private key from the keychain (!) Unfortunately I haven't found a clean way to convert a SecKey to a -&gt; SecureEnclave.P256.Signing.PrivateKey There is a workaround to SecKeyCopyAttributes of the private key and to extract the bytes from the attributes["toid"], but I guess it's not safe to use an undocumented key ("toid") if there is no constant defined to it (the name could be changed in future releases) Second approach: Create a SecureEnclave.P256.Signing.PrivateKey Create the Certificate using the swift-certificates The created private key is protected by the secure enclave but it's not added automatically to the keychain so we should add it to can query after that the SecIdentity (!) Unfortunately I haven't found a way to convert the SecureEnclave.P256.Signing.PrivateKey to -&gt; SecKey. There are threads which say that the SecKeyCreateWithData(...) helps us, but unfortunately if we set the kSecAttrTokenIDSecureEnclave in the attribute dictionary, the method creates a brand new key for us, regardless the passed data. So the initial key will never be the same as the newly created SecKey. This we can see in the method's implementation. So I got stuck with both approaches because seemingly there is no clean way to switch between SecureEnclave.P256.Signing.PrivateKey and SecKey. One solution would be to compose manually the certificate, without swift-certificates because like that we would not need a SecureEnclave.P256.Signing.PrivateKey object. But I would like to avoid the manual composition and signature calculation... Anybody has any idea?
Posted
by sipi.
Last updated
.
Post not yet marked as solved
7 Replies
2.8k Views
Hi, I am trying to implement encryption and decryption with EC signing keys. in the process I am getting the following error while creating a SecKey from the private key. Error in creating a secKey Optional(Swift.Unmanaged&lt;__C.CFErrorRef&gt;(_value: Error Domain=NSOSStatusErrorDomain Code=-50 "EC private key creation from data failed" (paramErr: error in user parameter list) UserInfo={numberOfErrorsDeep=0, NSDescription=EC private key creation from data failed})) Code snippet for decryption func decrypt(data: Data, key: SecureEnclave.P256.Signing.PrivateKey) throws -&gt; Data? {     var error: Unmanaged&lt;CFError&gt;?     let privateKeyData: CFData = key.dataRepresentation as CFData     let privateKeyAttributes = [kSecAttrKeyType: kSecAttrKeyTypeECSECPrimeRandom,                                 kSecAttrKeyClass: kSecAttrKeyClassPrivate] as CFDictionary     guard let SecKey = SecKeyCreateWithData(privateKeyData, privateKeyAttributes as CFDictionary, &amp;error)     else {         print("Error in creating a secKey", error)         return nil     }          guard SecKeyIsAlgorithmSupported(SecKey, .decrypt, EncryptAndDecryptAlogrithm)     else {         print("Decryption algorithm is not supported", error)         return nil     }          guard let decryptedData = SecKeyCreateDecryptedData(SecKey, EncryptAndDecryptAlogrithm, data as CFData, &amp;error) else {         print("Error in decryption", error)         return nil     }     return decryptedData as Data } let data = Data(base64Encoded: "BNtHrb1cZuflSDZz+E3PnIkLtYUQuBDW+ONlzuAypZcQa+5oKv0L0wSIBMMseMr0roloexPwTaVV26ddewTP0+vRt9v6uLOg366cElMo6P5nh2K7xKi1PMcRyBVel+Kq9WQWT/EkRIuUkHdq2KLXy/Q=")! let alice = try SecureEnclave.P256.Signing.PrivateKey() let decryptedData = try decrypt(data: data, key:alice) Thank you in advance.
Posted Last updated
.
Post marked as solved
4 Replies
495 Views
Hello fellow developers, I'm currently working on an SDK involving the SECP256R1 standard and facing an interesting issue. My goal is to ensure the Swift implementation of SECP256R1 signatures matches that of Rust's FastCrypto implementation. The Issue: When running tests to compare signatures generated by Swift and Rust implementations, the signatures do not match. Despite this mismatch, verification tests still succeed. I've tried using both the P256 class from CryptoKit and SecKey from the Security SDK. The Swift code is being written in Xcode 15 Beta 8, Swift 5.9. Code Snippet: struct SECP256R1PrivateKey { /// Commented is P256, uncommented is SecKey // public init(key: Data) throws { // if let privateKey = try? P256.Signing.PrivateKey(rawRepresentation: key) { // self.key = privateKey // } else { // throw AccountError.invalidData // } // } public init(key: Data) throws { if let privateKeyP256 = try? P256.Signing.PrivateKey(rawRepresentation: key) { let attributes: [String: Any] = [ kSecAttrKeyClass as String: kSecAttrKeyClassPrivate, kSecAttrKeyType as String: kSecAttrKeyTypeECDSA, kSecAttrTokenID as String: kSecAttrTokenIDSecureEnclave, kSecAttrKeySizeInBits as String: 256 ] var error: Unmanaged<CFError>? guard let privateKey = SecKeyCreateWithData(privateKeyP256.rawRepresentation as CFData, attributes as CFDictionary, &error) else { throw error?.takeRetainedValue() as Error? ?? NSError(domain: NSOSStatusErrorDomain, code: Int(errSecParam), userInfo: nil) } self.key = privateKey } else { throw AccountError.invalidData } } // public func sign(data: Data) throws -> Signature { // let signature = try self.key.signature(for: data) // return Signature( // signature: signature.rawRepresentation, // publickey: try self.publicKey().key.compressedRepresentation, // signatureScheme: .SECP256R1 // ) // } public func sign(data: Data) throws -> Signature { let dataHash = Data(data.sha256) var error: Unmanaged<CFError>? guard let signature = SecKeyCreateSignature(self.key, .ecdsaSignatureMessageX962SHA256, dataHash as NSData, &error) as Data? else { throw error!.takeRetainedValue() as Error } guard let publicKey = SecKeyCopyExternalRepresentation(try self.publicKey().key, &error) as Data? else { throw AccountError.invalidData } return Signature( signature: signature, publickey: publicKey, signatureScheme: .SECP256R1 ) } } func testThatTheRustImplementationForSignaturesIsTheSame() throws { let account = try Account(privateKey: Data(self.validSecp256r1SecretKey), accountType: .secp256r1) guard let signData = "Hello, world!".data(using: .utf8) else { XCTFail("Unable to encode message"); return; } let signature = try account.sign(signData) XCTAssertEqual( try signature.hex(), "26d84720652d8bc4ddd1986434a10b3b7b69f0e35a17c6a5987e6d1cba69652f4384a342487642df5e44592d304bea0ceb0fae2e347fa3cec5ce1a8144cfbbb2" ) } The Core Question: How do I implement the R1 signature in Swift so that it matches the signature generated by Rust's FastCrypto? Any insights, suggestions, or sample code snippets that could guide me in the right direction would be immensely appreciated! Thank you in advance!
Posted Last updated
.
Post not yet marked as solved
3 Replies
505 Views
I am developing a cloud-based application and have integrated the FileProviderExtension. However, files larger than 20 MB are not downloading as it’s throwing a memory limit exception. In this process, I have downloaded the file data, but after downloading the data, I need to decrypt the data. I am getting a memory limit exception during decryption. I am using the below lines to decrypt the data. let symmetricKey = SymmetricKey(data: key) let sealedBox = try AES.GCM.SealedBox(combined: inputData) let decryptedData = try AES.GCM.open(sealedBox, using: symmetricKey) I am getting memory limit exception at AES.GCM.open(sealedBox, using: symmetricKey)
Posted Last updated
.
Post not yet marked as solved
1 Replies
386 Views
Hi there, I'm trying to do a raw signature but the SecKeyRawSign is deprecated, so I am wondering if there is any way to do it using SecKeyCreateSignature, and EC key and the kSecKeyAlgorithmECDSASignatureMessageX962SHA256 algo. I've noticed that this method applies a hash before signing the data, and I want to avoid that. Is that possible? If not, what other options do i have? Thanks in advance.
Posted
by agestaun.
Last updated
.
Post not yet marked as solved
1 Replies
405 Views
I've been reading information/signing data using keys in the file keychain without too many problems but the other day I tried to generate a private key in the file and the secure enclave keychains and I faced the -30418 error. I made sure that the entitlements were correct based on previous posts but still no luck. Code kind of based off this: https://developer.apple.com/documentation/security/certificate_key_and_trust_services/keys/protecting_keys_with_the_secure_enclave Do you actually need to pay for the $99/per year developer account to generate private keys inside the keychains ?
Posted
by n546633.
Last updated
.
Post not yet marked as solved
2 Replies
803 Views
Hi, I'm having some trouble running a shell script that worked before I updated the Xcode and my MacOS. This is probably connected to the command line tools which were updated with these upgrades. I can't switch to an older version of the command line tools to verify this theory tho... The script uses CryptoKit to decrypt some data which was encrypted using a SymmetricKey. The script: #!/bin/bash # # DecryptScript.sh # # This script decrypts encrypted data using a symmetric key. # Check for the correct number of arguments if [ "$#" -ne 2 ]; then echo "Usage: $0 <encrypted_file_path> <decrypted_file_path>" exit 1 fi # Get the input arguments encryptedFilePath="$1" decryptedFilePath="$2" # Find the path to the script's directory scriptDir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" # Check if the symmetric key file exists in the same directory symmetricKeyPath="$scriptDir/.sim.key" if [ ! -f "$symmetricKeyPath" ]; then echo "SymmetricKey file was not found in the same directory as the script." exit 1 fi # Decrypt the data swift - <<EOF import Foundation import CryptoKit let symmetricKeyURL = URL(fileURLWithPath: "$symmetricKeyPath") let encryptedDataURL = URL(fileURLWithPath: "$encryptedFilePath") let decryptedDataURL = URL(fileURLWithPath: "$decryptedFilePath") guard let symmetricKeyData = try? Data(contentsOf: symmetricKeyURL) else { fatalError("Failed to read symmetric key data") } guard let encryptedData = try? Data(contentsOf: encryptedDataURL) else { fatalError("Failed to read encrypted data") } do { // Decrypt the data using AES-GCM let decryptionKey = SymmetricKey(data: symmetricKeyData) let sealedBox = try AES.GCM.SealedBox(combined: encryptedData) let decryptedData = try AES.GCM.open(sealedBox, using: decryptionKey) // Write the decrypted data to a file try decryptedData.write(to: decryptedDataURL) print("Decryption successful. Decrypted file saved at \(decryptedDataURL)") } catch { print("Decryption failed: \(error.localizedDescription)") } EOF The code in the project which encrypts the data and retrieves the key: func encryptSymmetric(data: Data, password: String) throws -> (Data, Data) { let key = SymmetricKey(size: .bits256) guard let cipher = try? AES.GCM.seal(data, using: key).combined else { throw SomeCustomError.failedToEncryptData } let keyData = key.withUnsafeBytes { Data($0) } return (cipher, keyData) } The error I'm presented with in the terminal is JIT session error: Symbols not found: [ _$s9CryptoKit3AESO3GCMO4open_5using10Foundation4DataVAE9SealedBoxV_AA12SymmetricKeyVtKFZ, _$s9CryptoKit12SymmetricKeyVMa, _$s9CryptoKit3AESO3GCMO9SealedBoxV8combinedAGx_tKc10Foundation12DataProtocolRzlufC, _$s9CryptoKit12SymmetricKeyV4dataACx_tc10Foundation15ContiguousBytesRzlufC, _$s9CryptoKit3AESO3GCMO9SealedBoxVMa ] Failed to materialize symbols: { (main, { _$s4main16encryptedDataURL10Foundation0D0Vvp, _$s4main15symmetricKeyURL10Foundation0D0Vvp, _$s10Foundation4DataVAcA0B8ProtocolAAWL, _$s4main16decryptedDataURL10Foundation0D0Vvp, _$sSa12_endMutationyyF, _$ss5print_9separator10terminatoryypd_S2StFfA0_, _$ss27_finalizeUninitializedArrayySayxGABnlF, _main, _$s10Foundation4DataV15_RepresentationOWOe, _$sSSWOh, _$ss5print_9separator10terminatoryypd_S2StFfA1_, _$s10Foundation4DataV5write2to7optionsyAA3URLV_So20NSDataWritingOptionsVtKFfA0_, ___swift_allocate_value_buffer, __swift_FORCE_LOAD_$_swiftFoundation_$_main, _$s10Foundation4DataV10contentsOf7optionsAcA3URLVh_So20NSDataReadingOptionsVtKcfcfA0_, __swift_FORCE_LOAD_$_swiftXPC_$_main, _$s10Foundation4DataV15_RepresentationOWOy, ___swift_project_value_buffer, _$s10Foundation4DataVAcA0B8ProtocolAAWl, __swift_FORCE_LOAD_$_swiftIOKit_$_main, _$ss26DefaultStringInterpolationVWOh, __swift_FORCE_LOAD_$_swiftCoreFoundation_$_main, _$s10Foundation3URLVACs23CustomStringConvertibleAAWl, __swift_FORCE_LOAD_$_swiftDarwin_$_main, __swift_FORCE_LOAD_$_swiftObjectiveC_$_main, _$s10Foundation3URLVACs23CustomStringConvertibleAAWL, __swift_FORCE_LOAD_$_swiftDispatch_$_main }) } This leads me to believe that linking might not be working properly. I also found this thread where someone had the same issue but with a different framework. NOTE: If I try to decrypt the data in my project, it works without any issues even on Xcode 15. It only fails if I try to run this script which worked before when I had the previous version of command line tools. I even tried updating to Xcode 15.1 beta and its command line tools, without success. Any feedback is appreciated. Thank you.
Posted
by ZvoneM.
Last updated
.
Post not yet marked as solved
1 Replies
439 Views
Hello Here is a problem with creating SecKey for ios 10 after key derivation (HMAC + sha512) After derivation we get 32 bytes of private key and chainCode There is no problem to use this bytes to create P256 private key with function from iOS13 try? P256.Signing.PrivateKey(rawRepresentation: bytes) and then to get x963Representation to create a SecKey But on iOS10 - 12 we don't have an ability to use this function... So I have to convert 32 bites key to 97 somehow to represent it in ANSI x9.63 format Example of key bytes [110, 181, 159, 0, 54, 16, 25, 129, 87, 128, 85, 36, 192, 64, 195, 4, 20, 47, 243, 134, 160, 57, 30, 210, 89, 225, 223, 114, 11, 121, 57, 156] x963Representation [4, 37, 167, 241, 121, 238, 41, 22, 35, 158, 89, 144, 215, 243, 4, 91, 217, 243, 23, 42, 171, 228, 247, 89, 136, 123, 22, 71, 11, 205, 134, 29, 110, 83, 241, 239, 135, 37, 226, 40, 179, 11, 191, 193, 232, 124, 41, 160, 136, 53, 95, 33, 233, 207, 151, 83, 136, 234, 97, 4, 79, 115, 227, 69, 42, 252, 66, 68, 64, 32, 176, 11, 75, 206, 158, 228, 246, 9, 179, 36, 94, 186, 209, 125, 152, 192, 192, 141, 242, 200, 108, 181, 75, 103, 86, 171, 231] I see that x963Representation contains: header(04) + ? + ? + 32_Key_Bytes So the question is - how to count x and y to get the key form (04 || X || Y || K) to be able to create SecKey?
Posted Last updated
.
Post not yet marked as solved
0 Replies
495 Views
I try to use LAContext.evaluateAccessControl for LAAccessControlOperationUseKeyDecrypt operations using a Secure Enclave-based private key. The keys are created using SecKeyGeneratePair (ECDH + SETokenID). Access Control is then defined using kSecAccessControlBiometryAny | kSecAccessControlAnd | kSecAccessControlPrivateKeyUsage flags. By the time LAContext.evaluateAccessControl is called, SecAccessControlCreateWithFlags is used with flags kSecAccessControlBiometryAny | kSecAccessControlPrivateKeyUsage. Evaluation will fail with ACL error: Domain=com.apple.LocalAuthentication Code=-1009 "ACL operation is not allowed: 'od'" UserInfo={NSDebugDescription=ACL operation is not allowed: 'od’} The same process is fine for signature operations. I don't understand what 'od' stands for. If ACLs are the same for key creations and key usage, shouldn't it prompt TouchID and allow the operation ?
Posted Last updated
.
Post not yet marked as solved
2 Replies
618 Views
I've went through all the posts with similar info about signature or keys used not working with openssll. But I haven't been able to patch it all together. I will use some sample keys for what I tried, let privPem = """ -----BEGIN PRIVATE KEY----- MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgIUSrwhllMSminPZZ Gx0YHUsL12IWIGI+4yhejpq90HihRANCAAT6pxKtIKm4VbfXeKpQ7rxITlC6b18Q 0X+Iz1UVDolyjx79bt5vUp0mPJ6hHBnK/Ap5gXpv89wmLPp7/O2NconE -----END PRIVATE KEY----- """ let privKey = try! P256.Signing.PrivateKey(pemRepresentation: privPem) let pubKey = privKey.publicKey let challengeDev = "1122334455667788" let dataToSignDev = challengeDev.hexadecimal let digest = SHA256.hash(data: dataToSignDev!) let signatureForDigest = try! privKey.signature( for: digest) let signature1 = try! P256.Signing.ECDSASignature(derRepresentation: signatureForDigest.derRepresentation) let isValidSignature = pubKey.isValidSignature(signatureForDigest, for: digest) I have tried the same using Security framework also to no avail. What I tried is a direct application of what the openssl part does, So I have a device that will verify the signature that the iOS app will be sending. The public key is taken from a certificate I would share with the device. All data sent to the device including signature is in DER format. openssl dgst -sha256 -sign app_private.key -out %OUT_RESOURCES_DIR%\signature.der -binary device_challenge.hex openssl x509 -inform der -in cert.der -out cert.pem openssl x509 -pubkey -noout -in cert.pem &gt; public_key.pem openssl dgst -sha256 -verify public_key.pem -signature signature.der challenge.hex Here on the iOS side If I were to sign and verify everything is fine. But if the same signature is verified on OpenSSL it fails. I tried to create a DER file on the terminal but asn1parse fails on it, Test % echo 30450220198944e2a8352941036f227225940392cbd1bc720358ce29db29a2a85f2b2a30022100b4e75ceb0335e4b1955aab01edc8e7347f78dc627f8d02a78103cd9165571d57 &gt; signature1.der Test % openssl asn1parse -inform DER -in signature1.der 0:d=0 hl=2 l= 48 cons: PRINTABLESTRING Error in encoding 140704639042368:error:0DFFF09B:asn1 encoding routines:CRYPTO_internal:too long:/AppleInternal/Library/BuildRoots/97f6331a-ba75-11ed-a4bc-863efbbaf80d/Library/Caches/com.apple.xbs/Sources/libressl/libressl-3.3/crypto/asn1/asn1_lib.c:143: I'm assuming I need to manually do some changes to make them inter compatible? Like this post Can't export EC kSecAttrTokenIDSecureEnclave public key Not sure how to get there though. All help appreciated.
Posted
by Jz120.
Last updated
.
Post not yet marked as solved
2 Replies
792 Views
Hello, I am attempting to perform a Diffie Hellman Keyexchange with a server running on .Net. However, the secretKey I am creating on the client side does not match with the secretKey on the server side, which I have for testing purposes. I can import the server secret key as a SymetricKey, and if I use it to seal and open a box, it works. However, if I seal the box with my client key, I can not open it with the server shared key. I create the SymetricKey like this: let sharedHash = SHA256.self let sharedInfo = serverPublicKey.rawRepresentation let sharedLength = 32 let symetricKey = sharedSecret.x963DerivedSymmetricKey( using: sharedHash, sharedInfo: Data(), outputByteCount: sharedLength) The server key is created using .Net like this: bob.KeyDerivationFunction = ECDiffieHellmanKeyDerivationFunction.Hash; bob.HashAlgorithm = CngAlgorithm.Sha256; bobPublicKey = bob.PublicKey.ToByteArray(); bobKey = bob.DeriveKeyMaterial(CngKey.Import(Alice.alicePublicKey, CngKeyBlobFormat.EccPublicBlob)); My assumption is the keys should be the same. Is that correct? How can I find out what format the server key is in? The .Net documentation is not particularly precise on that You can find a Playground of my code, and when you google for ECDiffieHellmanCng Class, you will find an example on what .Net does. Any help is appreciated
Posted
by below.
Last updated
.
Post not yet marked as solved
1 Replies
625 Views
AES 128 CBC algorithm is not producing same results compared to Android code. We have all static strings for key, iv and salt, even then the IV we couldnt match and produce same output as android. This is the Android code, object AESEncyption { ​ fun encrypt(strToEncrypt: String) : String? { try { val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding") val factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1") val spec: KeySpec = PBEKeySpec(secretKey.toCharArray(), hex(salt), iterationCount, keySize) val key: SecretKey = SecretKeySpec(factory.generateSecret(spec).encoded, "AES") cipher.init(Cipher.ENCRYPT_MODE, key, IvParameterSpec(hex(iv))) ​ return base64(cipher.doFinal(strToEncrypt.toByteArray(Charsets.UTF_8))) } catch (e: Exception) { Log.i("Him","Error while encrypting: $e") } return null } ​ private fun base64(bytes: ByteArray?): String { return android.util.Base64.encodeToString(bytes, android.util.Base64.DEFAULT) } ​ /* fun base64(str: String?): ByteArray? { return Base64.decodeBase64(str) }*/ ​ fun hex(bytes: ByteArray?): String? { return Hex.encodeHexString(bytes) } ​ fun hex(str: String): ByteArray? { return try { Hex.decodeHex(str.toCharArray()) } catch (e: DecoderException) { throw IllegalStateException(e) } } } iOS code is let enc = try AES(key: keyVar2!.bytes, blockMode: CBC(iv: iv.base64FromHex.ivToUInt8Array), padding: .pkcs5).encrypt(value.bytes) let encryptedData = Data(enc)
Posted Last updated
.
Post not yet marked as solved
4 Replies
4.2k Views
I have a Build Phase which runs a script. The script is a swift file, which I have simplified to illustrate the crash, like so: #!/usr/bin/env xcrun --sdk macosx swift import Foundation import CryptoKit var sha256 = SHA256() // Do other stuff... All the Xcode 15 betas fail to build my app, instead throwing the error: Command PhaseScriptExecution failed with a nonzero exit code. The logs: JIT session error: Symbols not found: [ _$s9CryptoKit6SHA256VMa, _$s9CryptoKit6SHA256VACycfC ] Failed to materialize symbols: { (main, { _$s20PropertyListModifier6sha2569CryptoKit6SHA256Vvp, _main, __swift_FORCE_LOAD_$_swiftDarwin_$_PropertyListModifier, __swift_FORCE_LOAD_$_swiftIOKit_$_PropertyListModifier, ___swift_project_value_buffer, __swift_FORCE_LOAD_$_swiftFoundation_$_PropertyListModifier, ___swift_allocate_value_buffer, __swift_FORCE_LOAD_$_swiftObjectiveC_$_PropertyListModifier, __swift_FORCE_LOAD_$_swiftXPC_$_PropertyListModifier, __swift_FORCE_LOAD_$_swiftCoreFoundation_$_PropertyListModifier, __swift_FORCE_LOAD_$_swiftDispatch_$_PropertyListModifier }) } Does anyone know of a work-around or solution, or does this just look like nothing more than a bug in the betas, which I should "wait out"? It's had the same problem right from beta 1 to the current beta 5 so it's starting to look like it won't be fixed which is worrying me.
Posted
by Haggis.
Last updated
.
Post not yet marked as solved
0 Replies
680 Views
Hi guys, I need to use deterministic ECDSA (described in RFC 6979 article: https://www.rfc-editor.org/rfc/rfc6979) algorithm to calculate signature in iOS project. It is known that deterministic ECDSA is vulnerable to fault injection and side-channel attacks, so there is an updates for RFC 6979 described in following article (see section 4): https://www.ietf.org/archive/id/draft-mattsson-cfrg-det-sigs-with-noise-04.html#name-updates-to-rfc-6979-determi I tried to find any information related to deterministic ECDSA algorithm implementation and support in iOS ecosystem, but unfortunately found nothing Could you please provide me complete information whether the deterministic ECDSA with updates is implemented and provides by iOS API? Any guidance or information on this matter would be greatly appreciated. Looking forward for you soon. ))
Posted
by Hayk_KQ.
Last updated
.