Apple CryptoKit

RSS for tag

Perform cryptographic operations securely and efficiently using Apple CryptoKit.

Posts under Apple CryptoKit tag

96 Posts

Post

Replies

Boosts

Views

Activity

Convert PEM format Curve25519 ECDH Keys with long length base64 string?
let privateKey = Curve25519.KeyAgreement.PrivateKey() let publicKey = privateKey.publicKey than what I do next? my requirement keys are like Public Key: -——BEGIN PUBLIC KEY-----MIIBMTCB6gYHKoZIzj0CATCB3gIBATArBgcqhkjOPQEBAiB/////////////////////////////////////////7TBEBCAqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqYSRShRAQge0Je0Je0Je0Je0Je0Je0Je0Je0Je0Je0JgtenHcQyGQEQQQqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq0kWiCuGaG4oIa04B7dLHdI0UySPU1+bXxhsinpxaJ+ztPZAiAQAAAAAAAAAAAAAAAAAAAAFN753qL3nNZYEmMaXPXT7QIBCANCAARMyjhxmqctNgQJS5yef637I1SMM+Yg9PZ6VKF83hgCDH13bayEHj8I1nEPVO5pfyqATxOcOQS110iA9QJTEpsI-----END PUBLIC KEY----- Private Key: -----BEGIN PRIVATE KEY-----MIICRwIBADCB6gYHKoZIzj0CATCB3gIBATArBgcqhkjOPQEBAiB/////////////////////////////////////////7TBEBCAqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqYSRShRAQge0Je0Je0Je0Je0Je0Je0Je0Je0Je0Je0JgtenHcQyGQEQQQqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq0kWiCuGaG4oIa04B7dLHdI0UySPU1+bXxhsinpxaJ+ztPZAiAQAAAAAAAAAAAAAAAAAAAAFN753qL3nNZYEmMaXPXT7QIBCASCAVMwggFPAgEBBCAOeSuzq+O1tPlhPZj4KZdfAq5Z0+yca15ukbUuwsyJQKCB4TCB3gIBATArBgcqhkjOPQEBAiB/////////////////////////////////////////7TBEBCAqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqYSRShRAQge0Je0Je0Je0Je0Je0Je0Je0Je0Je0Je0JgtenHcQyGQEQQQqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq0kWiCuGaG4oIa04B7dLHdI0UySPU1+bXxhsinpxaJ+ztPZAiAQAAAAAAAAAAAAAAAAAAAAFN753qL3nNZYEmMaXPXT7QIBCKFEA0IABG56w6jtAyb2T6oguKNN6HvLPQdT0Mms8gCepW51pobrDT/WfXJKfFr5fRuNalS+YkDQggoc7xtpYFin0ELidYw=-----END PRIVATE KEY-----
3
0
1.7k
Jan ’22
How to generate Curve 25519 key pair with ECDH swift iOS?
I want to generate a Curve25519 key pair with ECDH for the encryption and decryption. I'm using the CryptoKit to generates a keypair. But, I failed to generate a keypair with the ECDH algorithm. func generateKeys() -> (publicKey: String, privateKey: String){ let privateKey = Curve25519.KeyAgreement.PrivateKey() let publicKey = privateKey.publicKey let publicKeyString = "-----BEGIN PUBLIC KEY-----\(publicKey.rawRepresentation.base64EncodedString())-----END PUBLIC KEY-----" print(publicKeyString) let privateKeyString = "-----BEGIN PRIVATE KEY-----\(privateKey.rawRepresentation.base64EncodedString(options: .lineLength64Characters))-----END PRIVATE KEY-----\r\n" print(privateKeyString) return (publicKeyString, [rivateKeyString) } Output: -----BEGIN PUBLIC KEY-----WSOOXYN/FaCOn4SAlvrW3q4IYueiS8Io+WqL64T2QQA=-----END PUBLIC KEY----- -----BEGIN PRIVATE KEY-----AAlH4v1vcnmjEKVJrhbarMqCrcNWYZgFwnhReduEokk=-----END PRIVATE KEY----- Here is one of the Java code using bouncycastle { "privateKey": "-----BEGIN PRIVATE KEY-----MIICRwIBADCB6gYHKoZIzj0CATCB3gIBATArBgcqhkjOPQEBAiB/////////////////////////////////////////7TBEBCAqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqYSRShRAQge0Je0Je0Je0Je0Je0Je0Je0Je0Je0Je0JgtenHcQyGQEQQQqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq0kWiCuGaG4oIa04B7dLHdI0UySPU1+bXxhsinpxaJ+ztPZAiAQAAAAAAAAAAAAAAAAAAAAFN753qL3nNZYEmMaXPXT7QIBCASCAVMwggFPAgEBBCAOeSuzq+O1tPlhPZj4KZdfAq5Z0+yca15ukbUuwsyJQKCB4TCB3gIBATArBgcqhkjOPQEBAiB/////////////////////////////////////////7TBEBCAqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqYSRShRAQge0Je0Je0Je0Je0Je0Je0Je0Je0Je0Je0JgtenHcQyGQEQQQqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq0kWiCuGaG4oIa04B7dLHdI0UySPU1+bXxhsinpxaJ+ztPZAiAQAAAAAAAAAAAAAAAAAAAAFN753qL3nNZYEmMaXPXT7QIBCKFEA0IABG56w6jtAyb2T6oguKNN6HvLPQdT0Mms8gCepW51pobrDT/WfXJKfFr5fRuNalS+YkDQggoc7xtpYFin0ELidYw=-----END PRIVATE KEY-----", "errorInfo": null, "KeyMaterials": { "cryptoAlg": "ECDH", "curve": "curve25519", "params": "", "DHPublicKey": { "expiry": "2021-12-15T11:29:20.848Z", "Parameter": "", "KeyValue": "-----BEGIN PUBLIC KEY-----MIIBMTCB6gYHKoZIzj0CATCB3gIBATArBgcqhkjOPQEBAiB/////////////////////////////////////////7TBEBCAqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqYSRShRAQge0Je0Je0Je0Je0Je0Je0Je0Je0Je0Je0JgtenHcQyGQEQQQqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq0kWiCuGaG4oIa04B7dLHdI0UySPU1+bXxhsinpxaJ+ztPZAiAQAAAAAAAAAAAAAAAAAAAAFN753qL3nNZYEmMaXPXT7QIBCANCAARuesOo7QMm9k+qILijTeh7yz0HU9DJrPIAnqVudaaG6w0/1n1ySnxa+X0bjWpUvmJA0IIKHO8baWBXp9BC4mMW-----END PUBLIC KEY-----" } } } Can anyone guide me for the same keys like java?
3
0
3.3k
Jan ’22
How to get a Digest object from raw Data
Hi there TL;DR : I have a Data object which contains data that is already hashed. I need a Digest object, how should I proceed ? I am developing an OSX Smart Card Token Extension to handle certificates linked to private keys in the Secure Enclave (using CryptoKit). So far my first tests are pretty successful as my extension already answered to various signature requests successfully... until now. So far I was receiving signature requests for ecdsaSignatureMessageX962SHA256 algorithm. All I had to do with was something like this: func tokenSession(_ session: TKTokenSession, sign dataToSign: Data, keyObjectID: Any, algorithm: TKTokenKeyAlgorithm) throws -> Data { if let privateKey = try? SecureEnclave.P256.Signing.PrivateKey.init(dataRepresentation: keyObjectID as! Data) {       let rawsignature = try? privateKey.signature(for: dataToSign)       return rawsignature!.derRepresentation     } } Now I receive requests for ecdsaSignatureDigestX962SHA256 signatures. I noticed that there is a public func signature<D>(for digest: D) throws -> P256.Signing.ECDSASignature where D : Digest function that can be called but in the tokenSession i am only given Data... Looking at SHA256Digest documentation I can't find anything to create the digest from bytes. It seems that it can only be the result of a SHA256.hash operation. I thought of using older API like SecKeyCreateSignature but I don't think I can retrieve a SecKey from a private key generated with CryptoKit SecureEnclave.P256.Signing.PrivateKey.init I feel like I may be missing something really simple...
2
0
1.7k
Jan ’22
is private key extraction allowed?
As I read the apple documentation on secure enclave and key chain, extraction of private key is not allowed. following is the reference: "Can’t import preexisting keys. You must create keys directly inside the Secure Enclave. Not having a mechanism to transfer key data into or out of the Secure Enclave is fundamental to its security." Link: https://developer.apple.com/documentation/security/certificate_key_and_trust_services/keys/storing_keys_in_the_secure_enclave But after loading the key using "SecItemCopyMatching" and then passing the object into "SecKeyCopyAttributes" gives us a dictionary of key value pairs. I believe that the private key was part of the value for key "toid" of that dictionary. is my understanding correct or, am I missing something? I couldn't find the documentation describing the meaning of the key value pairs of the dictionary returned by "SecKeyCopyAttributes". I'll appreciate if somebody can guide me to that documentation. Note: I am creating EC key pair.
1
0
951
Nov ’21
App crashes when trying to get signature using private key
Hi, for some of our users the app crashes when we try to get the EdDSA signature using the private key. We use the following method from CryptoKit in the Curve25519.Signing.PrivateKey extension: public func signature<D>(for data: D) throws -> Data where D : DataProtocol The data that we want to sign is a string that is converted using the algorithm SHA256 Our implementation looks something like this: func foo(text: String) throws -> String { var algorithm = SHA256() algorithm.update(data: text.data(using: .utf8)!) guard self.hasPrivateKey else { // Error handling } do { let signature = try self.privateKey.signature(for: algorithm.finalize()) // App crashes here if not using do-catch statement // signature will be used and transformed to return String... } catch { // Error handling } } I would appreciate any hints on how to solve or inspect this. Many thanks.
3
0
1.1k
Oct ’21
No such Module Found on line -> "import Cryptokit"
I have used Apple API - Apple CryptoKit | Apple Developer Documentation in my project . While Archieving the Project , I gives out an error ,And build Fails . The Same Project works well in Xcode 12_4 . Only after I updated my Xcode to Xcode13. This Error Started Occurring . Xcode12_4 - Catalina Mac Xcode 13 - BigSur Mac. Whether It may be due to Bigsur ? Does Any other reproduces this Error? Can Anyone Help me in this?
2
0
3.0k
Oct ’21
P521.Signing
So, I've been trying to inter-operate with CryptoKit, and my backend running on Linux, and it appears that the documentation here is incorrect. It claims that the data is first digested with SHA256, but my testing seems to say that the convenience Data functions is actually done with SHA512 import CryptoKit import Foundation typealias Key = P521.Signing.PrivateKey func verify1() throws {     let key = Key()     let data = "1 2 3 4 5 6 7 8 9 0".data(using: .ascii)!     let digest = SHA256.hash(data: data)     let signature = try key.signature(for: digest)     let verified = key.publicKey.isValidSignature(signature, for: data)     print("verified \(verified)") } func verify2() throws {     let key = Key()     let data = "1 2 3 4 5 6 7 8 9 0".data(using: .ascii)!     let digest = SHA512.hash(data: data)     let signature = try key.signature(for: digest)     let verified = key.publicKey.isValidSignature(signature, for: data)     print("verified \(verified)") } func main() {     do {         try verify1()         try verify2()     }     catch {         print(error.localizedDescription)     } } main() (My Generic-Fu was insufficient to avoid the copy paste) When the above is run on my machine I get: % swift test.swift verified false verified true Is my diagnosis correct?
2
0
691
Sep ’21
Best practices for porting existing software to the Secure Enclave keystore
Hi, I was reading Storing Keys in the Secure Enclave and was thinking, "that's great if you're writing new code from scratch, or updating an iOS-only code base...", but how do people integrate this functionality into well-worn packages, such as Openssl? What's the best practice for representing the Secure Enclave keystore in software? Is it closest to an HSM (hardware security module)? Or to a PKCS11 crypto-token like a smart card? Or maybe it's sufficiently unlike anything else. We have some management scripting that uses Openssl and I'd like to be able to make it "just work" with Secure Enclave keystore, but don't see any guidance on how best to do that. What is the developer community's collective experience and wisdom here? Thanks, -Philip
1
0
1.2k
Aug ’21
AES-GCM 256 Encrypt & Decrypt in iOS Swift Sync with .Net output
I want to use AES-GCM encryption of a plaintext with 'key' only. The 'key' will be received from backend (.net), in webservice response. The same key will be used later in backend as well to decrypt the encrypted value. I have used extension as follwoing To generate string to Symetric key extension SymmetricKey { init(string keyString: String, size: SymmetricKeySize = .bits256) throws { guard var keyData = keyString.data(using: .utf8) else { print("Could not create base64 encoded Data from String.") throw CryptoKitError.incorrectParameterSize } let keySizeBytes = size.bitCount / 8 keyData = keyData.subdata(in: 0..<keySizeBytes) guard keyData.count >= keySizeBytes else { throw CryptoKitError.incorrectKeySize } self.init(data: keyData) } } Encryption & Decryption code snipet: func aesgcmEncryptDecrypt() { let str : String = "FwhXRYJ$xLf?^Kh6_&YfTJ%RuG+EqcTY" var key : SymmetricKey = SymmetricKey(size: .bits256) do{ key = try SymmetricKey(string: str) }catch{ } let plain = "HOW ARE YOU?" let nonce = try! AES.GCM.Nonce(data: Data(base64Encoded: "fv1nixTVoYpSvpdA")!) let tag = Data(base64Encoded: "e1eIgoB4+lA/j3KDHhY4BQ==")! // Encrypt let sealedBox = try! AES.GCM.seal(plain.data(using: .utf8)!, using: key, nonce: nonce, authenticating: tag) // Decrypt let sealedBoxRestored = try! AES.GCM.SealedBox(combined: sealedBox.combined!) let decrypted = try! AES.GCM.open(sealedBoxRestored, using: key, authenticating: tag) Swift.print("Combined:\n(sealedBox.combined!.base64EncodedString())\n") Swift.print("Cipher:\n(sealedBox.ciphertext.base64EncodedString())\n") Swift.print("Nonce:\n(nonce.withUnsafeBytes { Data(Array($0)).base64EncodedString() })\n") Swift.print("Tag:\n(tag.base64EncodedString())\n") Swift.print("Decrypted:\n(String(data: decrypted, encoding: .utf8)!)\n") } Our(generated from this code & .Net code) encrypted text is not matching. Anyone can help me, what I am doing wrong, detailing will be more helpful. Basically I was looking for saloution in Objective-C but I did not get any supported library for Objective-C. Using the AesGcm class
1
0
1.3k
Jul ’21
AES-GCM 256 Encrypt & Decrypt in iOS Swift Sync with .Net output
Hi I want to use AES-GCM encryption of a plaintext with 'key' only. The 'key' will be received from backend (.net), in webservice response. The same key will be used later in backend as well to decrypt the encrypted value. I have used extension as follwoing To generate string to Symetric key extension SymmetricKey { init(string keyString: String, size: SymmetricKeySize = .bits256) throws { guard var keyData = keyString.data(using: .utf8) else { print("Could not create base64 encoded Data from String.") throw CryptoKitError.incorrectParameterSize } let keySizeBytes = size.bitCount / 8 keyData = keyData.subdata(in: 0..<keySizeBytes) guard keyData.count >= keySizeBytes else { throw CryptoKitError.incorrectKeySize } self.init(data: keyData) } } Encryption & Decryption code snipet: func aesgcmEncryptDecrypt() { let str : String = "FwhXRYJ$xLf?^Kh6_&YfTJ%RuG+EqcTY" var key : SymmetricKey = SymmetricKey(size: .bits256) do{ key = try SymmetricKey(string: str) }catch{ } let plain = "HOW ARE YOU?" let nonce = try! AES.GCM.Nonce(data: Data(base64Encoded: "fv1nixTVoYpSvpdA")!) let tag = Data(base64Encoded: "e1eIgoB4+lA/j3KDHhY4BQ==")! // Encrypt let sealedBox = try! AES.GCM.seal(plain.data(using: .utf8)!, using: key, nonce: nonce, authenticating: tag) // Decrypt let sealedBoxRestored = try! AES.GCM.SealedBox(combined: sealedBox.combined!) let decrypted = try! AES.GCM.open(sealedBoxRestored, using: key, authenticating: tag) Swift.print("Combined:\n(sealedBox.combined!.base64EncodedString())\n") Swift.print("Cipher:\n(sealedBox.ciphertext.base64EncodedString())\n") Swift.print("Nonce:\n(nonce.withUnsafeBytes { Data(Array($0)).base64EncodedString() })\n") Swift.print("Tag:\n(tag.base64EncodedString())\n") Swift.print("Decrypted:\n(String(data: decrypted, encoding: .utf8)!)\n") } Our(generated from this code & .Net code) encrypted text is not matching. Anyone can help me, what I am doing wrong, detailing will be more helpful. Basically I was looking for saloution in Objective-C but I did not get any supported library for Objective-C.
1
0
2.2k
Jul ’21
Mac OS 11.4 Token Sign not working
I'm having a problem accessing a site where I need to use a certificate for identification, where I used some examples to type the pin but none works, I checked an instruction to register a module in firefox as a security device but it doesn't work, it worked on macos 10.15 , but now when adding the security device , the slot does not appear in Firefox. Tank's
1
0
935
Jul ’21
SecKeyCreateWithData Returns ‘Nil’ with Error
We are trying to create a ’SecKey’ from a ‘.der’ file. But ‘SecKeyCreateWithData’ always throw ‘Nil ’ with Error. Steps Followed:: First we created a ECDSA Private & Public key pair with the below Commands , then converted the .pem file holding the private key to ‘.der’file. Finally used the ‘.der’ file to generate a ‘SecKey’ via code. Commands Used to Generate Private & Public Keys:: openssl ecparam -genkey -name prime256v1 -noout -out ec-key-pair.pem openssl ec -in ec-key-pair.pem -pubout -out ec-key-pair.pub Command Used to Generate .Der file:: openssl pkey -outform der -in ec-key-pair.pem -out ec-key-pair.der Content Inside .pem file:: -----BEGIN EC PRIVATE KEY----- MHcCAQEEIKJTc3zI8D07Myh7ZIR+wGyQgsjEeKdH0+hSiErK5AjzoAoGCCqGSM49 AwEHoUQDQgAEvbOBrM/D2fX05zKQYuJiTRP6YiUBabImrHb9s+OHimxUxX+E9jVe oQ6nxSOkfgm0H1OjLfp2xGLqkDTuF38UGQ== -----END EC PRIVATE KEY----- Error Received:: Unmanaged - _value : Error Domain=NSOSStatusErrorDomain Code=-50 "EC private key creation from data failed" UserInfo={NSDescription=EC private key creation from data failed} Minimum Deployment Target Used:: iOS 14.0 Code Used:: if let certificateData = NSData(contentsOf:Bundle.main.url(forResource: "ec-key-pair", withExtension: "der")! ) {       var error: Unmanaged<CFError>? = nil       let privateSecKey = SecKeyCreateWithData(certificateData , [           kSecAttrKeyType: kSecAttrKeyTypeEC,           kSecAttrKeyClass: kSecAttrKeyClassPrivate] as NSDictionary, &error) }
2
0
2.3k
Jul ’21
RSA Key Generating use Security, SecKeyCreateRandomKey
i want make RSA pair key to 512bit i find SecKeyCreateRandomKey, CrytoKit, another open lib.. I decided to use Security I have to give the server developer the string value of the rsa file I created I sent you an rsa string but server developer answered that the format was wrong I wonder what is wrong with my code. Or I want to be helped to generate an rsa key and chage type into a string this is my code first - make private key using SecKeyCreateRandomKey func createPrivateKey()-> SecKey?{           let privateKeyParams: [String: Any] = [       kSecAttrIsPermanent as String: true,       kSecAttrApplicationTag as String: tagName     ]           let parameters: [String: Any] = [       kSecAttrKeyType as String: kSecAttrKeyTypeRSA,       kSecAttrKeySizeInBits as String: 512,       kSecPrivateKeyAttrs as String: privateKeyParams     ]           var error: Unmanaged<CFError>?           guard let privateKey = SecKeyCreateRandomKey(parameters as CFDictionary, &error) else     {       NSLog("\tError generating keypair. %@", "\(error!.takeRetainedValue().localizedDescription)")       return nil     }     return privateKey   } second - get public key using private key of Seckey func getPublicKey(key: SecKey) -> SecKey?{     return SecKeyCopyPublicKey(key)   } third - get public key Data using public key seckey func getPublicData(key: SecKey) -> CFData?{     return SecKeyCopyExternalRepresentation(key, nil)   } fouth - string of public key using public key of Data  public func exportPublicKey(_ rawPublicKeyBytes: Data, base64EncodingOptions: Data.Base64EncodingOptions = []) -> String?   {    Log.debug("exportPublicKey", rawPublicKeyBytes.base64EncodedString(options: base64EncodingOptions))     return rawPublicKeyBytes.base64EncodedString(options: base64EncodingOptions)   } last i send result of exportPublicKey() rsa string like this MEgCQQDCmgOuSGbG/Mtq2NnHlBQU5rsGnNf17h4NZy+2lyrjKGgaVpD66QHmx2Na+/QQaamEhUgkFAkj0UlkMTRWGKO5AgMBBBE= or -----BEGIN PUBLIC KEY----- MEgCQQDCmgOuSGbG/Mtq2NnHlBQU5rsGnNf17h4NZy+2lyrjKGgaVpD66QHmx2Na+/QQaamEhUgkFAkj0UlkMTRWGKO5AgMBBBE= -----END PUBLIC KEY-----
2
0
1.4k
Jul ’21
Convert PEM format Curve25519 ECDH Keys with long length base64 string?
let privateKey = Curve25519.KeyAgreement.PrivateKey() let publicKey = privateKey.publicKey than what I do next? my requirement keys are like Public Key: -——BEGIN PUBLIC KEY-----MIIBMTCB6gYHKoZIzj0CATCB3gIBATArBgcqhkjOPQEBAiB/////////////////////////////////////////7TBEBCAqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqYSRShRAQge0Je0Je0Je0Je0Je0Je0Je0Je0Je0Je0JgtenHcQyGQEQQQqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq0kWiCuGaG4oIa04B7dLHdI0UySPU1+bXxhsinpxaJ+ztPZAiAQAAAAAAAAAAAAAAAAAAAAFN753qL3nNZYEmMaXPXT7QIBCANCAARMyjhxmqctNgQJS5yef637I1SMM+Yg9PZ6VKF83hgCDH13bayEHj8I1nEPVO5pfyqATxOcOQS110iA9QJTEpsI-----END PUBLIC KEY----- Private Key: -----BEGIN PRIVATE KEY-----MIICRwIBADCB6gYHKoZIzj0CATCB3gIBATArBgcqhkjOPQEBAiB/////////////////////////////////////////7TBEBCAqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqYSRShRAQge0Je0Je0Je0Je0Je0Je0Je0Je0Je0Je0JgtenHcQyGQEQQQqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq0kWiCuGaG4oIa04B7dLHdI0UySPU1+bXxhsinpxaJ+ztPZAiAQAAAAAAAAAAAAAAAAAAAAFN753qL3nNZYEmMaXPXT7QIBCASCAVMwggFPAgEBBCAOeSuzq+O1tPlhPZj4KZdfAq5Z0+yca15ukbUuwsyJQKCB4TCB3gIBATArBgcqhkjOPQEBAiB/////////////////////////////////////////7TBEBCAqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqYSRShRAQge0Je0Je0Je0Je0Je0Je0Je0Je0Je0Je0JgtenHcQyGQEQQQqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq0kWiCuGaG4oIa04B7dLHdI0UySPU1+bXxhsinpxaJ+ztPZAiAQAAAAAAAAAAAAAAAAAAAAFN753qL3nNZYEmMaXPXT7QIBCKFEA0IABG56w6jtAyb2T6oguKNN6HvLPQdT0Mms8gCepW51pobrDT/WfXJKfFr5fRuNalS+YkDQggoc7xtpYFin0ELidYw=-----END PRIVATE KEY-----
Replies
3
Boosts
0
Views
1.7k
Activity
Jan ’22
How to generate Curve 25519 key pair with ECDH swift iOS?
I want to generate a Curve25519 key pair with ECDH for the encryption and decryption. I'm using the CryptoKit to generates a keypair. But, I failed to generate a keypair with the ECDH algorithm. func generateKeys() -> (publicKey: String, privateKey: String){ let privateKey = Curve25519.KeyAgreement.PrivateKey() let publicKey = privateKey.publicKey let publicKeyString = "-----BEGIN PUBLIC KEY-----\(publicKey.rawRepresentation.base64EncodedString())-----END PUBLIC KEY-----" print(publicKeyString) let privateKeyString = "-----BEGIN PRIVATE KEY-----\(privateKey.rawRepresentation.base64EncodedString(options: .lineLength64Characters))-----END PRIVATE KEY-----\r\n" print(privateKeyString) return (publicKeyString, [rivateKeyString) } Output: -----BEGIN PUBLIC KEY-----WSOOXYN/FaCOn4SAlvrW3q4IYueiS8Io+WqL64T2QQA=-----END PUBLIC KEY----- -----BEGIN PRIVATE KEY-----AAlH4v1vcnmjEKVJrhbarMqCrcNWYZgFwnhReduEokk=-----END PRIVATE KEY----- Here is one of the Java code using bouncycastle { "privateKey": "-----BEGIN PRIVATE KEY-----MIICRwIBADCB6gYHKoZIzj0CATCB3gIBATArBgcqhkjOPQEBAiB/////////////////////////////////////////7TBEBCAqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqYSRShRAQge0Je0Je0Je0Je0Je0Je0Je0Je0Je0Je0JgtenHcQyGQEQQQqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq0kWiCuGaG4oIa04B7dLHdI0UySPU1+bXxhsinpxaJ+ztPZAiAQAAAAAAAAAAAAAAAAAAAAFN753qL3nNZYEmMaXPXT7QIBCASCAVMwggFPAgEBBCAOeSuzq+O1tPlhPZj4KZdfAq5Z0+yca15ukbUuwsyJQKCB4TCB3gIBATArBgcqhkjOPQEBAiB/////////////////////////////////////////7TBEBCAqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqYSRShRAQge0Je0Je0Je0Je0Je0Je0Je0Je0Je0Je0JgtenHcQyGQEQQQqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq0kWiCuGaG4oIa04B7dLHdI0UySPU1+bXxhsinpxaJ+ztPZAiAQAAAAAAAAAAAAAAAAAAAAFN753qL3nNZYEmMaXPXT7QIBCKFEA0IABG56w6jtAyb2T6oguKNN6HvLPQdT0Mms8gCepW51pobrDT/WfXJKfFr5fRuNalS+YkDQggoc7xtpYFin0ELidYw=-----END PRIVATE KEY-----", "errorInfo": null, "KeyMaterials": { "cryptoAlg": "ECDH", "curve": "curve25519", "params": "", "DHPublicKey": { "expiry": "2021-12-15T11:29:20.848Z", "Parameter": "", "KeyValue": "-----BEGIN PUBLIC KEY-----MIIBMTCB6gYHKoZIzj0CATCB3gIBATArBgcqhkjOPQEBAiB/////////////////////////////////////////7TBEBCAqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqYSRShRAQge0Je0Je0Je0Je0Je0Je0Je0Je0Je0Je0JgtenHcQyGQEQQQqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq0kWiCuGaG4oIa04B7dLHdI0UySPU1+bXxhsinpxaJ+ztPZAiAQAAAAAAAAAAAAAAAAAAAAFN753qL3nNZYEmMaXPXT7QIBCANCAARuesOo7QMm9k+qILijTeh7yz0HU9DJrPIAnqVudaaG6w0/1n1ySnxa+X0bjWpUvmJA0IIKHO8baWBXp9BC4mMW-----END PUBLIC KEY-----" } } } Can anyone guide me for the same keys like java?
Replies
3
Boosts
0
Views
3.3k
Activity
Jan ’22
How to get a Digest object from raw Data
Hi there TL;DR : I have a Data object which contains data that is already hashed. I need a Digest object, how should I proceed ? I am developing an OSX Smart Card Token Extension to handle certificates linked to private keys in the Secure Enclave (using CryptoKit). So far my first tests are pretty successful as my extension already answered to various signature requests successfully... until now. So far I was receiving signature requests for ecdsaSignatureMessageX962SHA256 algorithm. All I had to do with was something like this: func tokenSession(_ session: TKTokenSession, sign dataToSign: Data, keyObjectID: Any, algorithm: TKTokenKeyAlgorithm) throws -> Data { if let privateKey = try? SecureEnclave.P256.Signing.PrivateKey.init(dataRepresentation: keyObjectID as! Data) {       let rawsignature = try? privateKey.signature(for: dataToSign)       return rawsignature!.derRepresentation     } } Now I receive requests for ecdsaSignatureDigestX962SHA256 signatures. I noticed that there is a public func signature<D>(for digest: D) throws -> P256.Signing.ECDSASignature where D : Digest function that can be called but in the tokenSession i am only given Data... Looking at SHA256Digest documentation I can't find anything to create the digest from bytes. It seems that it can only be the result of a SHA256.hash operation. I thought of using older API like SecKeyCreateSignature but I don't think I can retrieve a SecKey from a private key generated with CryptoKit SecureEnclave.P256.Signing.PrivateKey.init I feel like I may be missing something really simple...
Replies
2
Boosts
0
Views
1.7k
Activity
Jan ’22
is private key extraction allowed?
As I read the apple documentation on secure enclave and key chain, extraction of private key is not allowed. following is the reference: "Can’t import preexisting keys. You must create keys directly inside the Secure Enclave. Not having a mechanism to transfer key data into or out of the Secure Enclave is fundamental to its security." Link: https://developer.apple.com/documentation/security/certificate_key_and_trust_services/keys/storing_keys_in_the_secure_enclave But after loading the key using "SecItemCopyMatching" and then passing the object into "SecKeyCopyAttributes" gives us a dictionary of key value pairs. I believe that the private key was part of the value for key "toid" of that dictionary. is my understanding correct or, am I missing something? I couldn't find the documentation describing the meaning of the key value pairs of the dictionary returned by "SecKeyCopyAttributes". I'll appreciate if somebody can guide me to that documentation. Note: I am creating EC key pair.
Replies
1
Boosts
0
Views
951
Activity
Nov ’21
App crashes when trying to get signature using private key
Hi, for some of our users the app crashes when we try to get the EdDSA signature using the private key. We use the following method from CryptoKit in the Curve25519.Signing.PrivateKey extension: public func signature<D>(for data: D) throws -> Data where D : DataProtocol The data that we want to sign is a string that is converted using the algorithm SHA256 Our implementation looks something like this: func foo(text: String) throws -> String { var algorithm = SHA256() algorithm.update(data: text.data(using: .utf8)!) guard self.hasPrivateKey else { // Error handling } do { let signature = try self.privateKey.signature(for: algorithm.finalize()) // App crashes here if not using do-catch statement // signature will be used and transformed to return String... } catch { // Error handling } } I would appreciate any hints on how to solve or inspect this. Many thanks.
Replies
3
Boosts
0
Views
1.1k
Activity
Oct ’21
No such Module Found on line -> "import Cryptokit"
I have used Apple API - Apple CryptoKit | Apple Developer Documentation in my project . While Archieving the Project , I gives out an error ,And build Fails . The Same Project works well in Xcode 12_4 . Only after I updated my Xcode to Xcode13. This Error Started Occurring . Xcode12_4 - Catalina Mac Xcode 13 - BigSur Mac. Whether It may be due to Bigsur ? Does Any other reproduces this Error? Can Anyone Help me in this?
Replies
2
Boosts
0
Views
3.0k
Activity
Oct ’21
P521.Signing
So, I've been trying to inter-operate with CryptoKit, and my backend running on Linux, and it appears that the documentation here is incorrect. It claims that the data is first digested with SHA256, but my testing seems to say that the convenience Data functions is actually done with SHA512 import CryptoKit import Foundation typealias Key = P521.Signing.PrivateKey func verify1() throws {     let key = Key()     let data = "1 2 3 4 5 6 7 8 9 0".data(using: .ascii)!     let digest = SHA256.hash(data: data)     let signature = try key.signature(for: digest)     let verified = key.publicKey.isValidSignature(signature, for: data)     print("verified \(verified)") } func verify2() throws {     let key = Key()     let data = "1 2 3 4 5 6 7 8 9 0".data(using: .ascii)!     let digest = SHA512.hash(data: data)     let signature = try key.signature(for: digest)     let verified = key.publicKey.isValidSignature(signature, for: data)     print("verified \(verified)") } func main() {     do {         try verify1()         try verify2()     }     catch {         print(error.localizedDescription)     } } main() (My Generic-Fu was insufficient to avoid the copy paste) When the above is run on my machine I get: % swift test.swift verified false verified true Is my diagnosis correct?
Replies
2
Boosts
0
Views
691
Activity
Sep ’21
CryptoKit TOTP Fails in Swift Package
I am trying to use the HMAC function in a swift package but it does not work it only works in standard view controller style packages. let hash = HMAC<Insecure.SHA1>.authenticationCode(for: counterData, using: SymmetricKey(data: secret))
Replies
2
Boosts
0
Views
928
Activity
Sep ’21
Best practices for porting existing software to the Secure Enclave keystore
Hi, I was reading Storing Keys in the Secure Enclave and was thinking, "that's great if you're writing new code from scratch, or updating an iOS-only code base...", but how do people integrate this functionality into well-worn packages, such as Openssl? What's the best practice for representing the Secure Enclave keystore in software? Is it closest to an HSM (hardware security module)? Or to a PKCS11 crypto-token like a smart card? Or maybe it's sufficiently unlike anything else. We have some management scripting that uses Openssl and I'd like to be able to make it "just work" with Secure Enclave keystore, but don't see any guidance on how best to do that. What is the developer community's collective experience and wisdom here? Thanks, -Philip
Replies
1
Boosts
0
Views
1.2k
Activity
Aug ’21
Swift RSA Public key Encryption
I would like to generate a cryptographically random key, use that to encrypt the data with a symmetric cypher (AES typically) and then encrypt the random key with RSA. How can I do it in swift? Is it possible with CryptoKit or CommonCrypto ? Thanks
Replies
1
Boosts
0
Views
4.4k
Activity
Aug ’21
AES-GCM 256 Encrypt & Decrypt in iOS Swift Sync with .Net output
I want to use AES-GCM encryption of a plaintext with 'key' only. The 'key' will be received from backend (.net), in webservice response. The same key will be used later in backend as well to decrypt the encrypted value. I have used extension as follwoing To generate string to Symetric key extension SymmetricKey { init(string keyString: String, size: SymmetricKeySize = .bits256) throws { guard var keyData = keyString.data(using: .utf8) else { print("Could not create base64 encoded Data from String.") throw CryptoKitError.incorrectParameterSize } let keySizeBytes = size.bitCount / 8 keyData = keyData.subdata(in: 0..<keySizeBytes) guard keyData.count >= keySizeBytes else { throw CryptoKitError.incorrectKeySize } self.init(data: keyData) } } Encryption & Decryption code snipet: func aesgcmEncryptDecrypt() { let str : String = "FwhXRYJ$xLf?^Kh6_&YfTJ%RuG+EqcTY" var key : SymmetricKey = SymmetricKey(size: .bits256) do{ key = try SymmetricKey(string: str) }catch{ } let plain = "HOW ARE YOU?" let nonce = try! AES.GCM.Nonce(data: Data(base64Encoded: "fv1nixTVoYpSvpdA")!) let tag = Data(base64Encoded: "e1eIgoB4+lA/j3KDHhY4BQ==")! // Encrypt let sealedBox = try! AES.GCM.seal(plain.data(using: .utf8)!, using: key, nonce: nonce, authenticating: tag) // Decrypt let sealedBoxRestored = try! AES.GCM.SealedBox(combined: sealedBox.combined!) let decrypted = try! AES.GCM.open(sealedBoxRestored, using: key, authenticating: tag) Swift.print("Combined:\n(sealedBox.combined!.base64EncodedString())\n") Swift.print("Cipher:\n(sealedBox.ciphertext.base64EncodedString())\n") Swift.print("Nonce:\n(nonce.withUnsafeBytes { Data(Array($0)).base64EncodedString() })\n") Swift.print("Tag:\n(tag.base64EncodedString())\n") Swift.print("Decrypted:\n(String(data: decrypted, encoding: .utf8)!)\n") } Our(generated from this code & .Net code) encrypted text is not matching. Anyone can help me, what I am doing wrong, detailing will be more helpful. Basically I was looking for saloution in Objective-C but I did not get any supported library for Objective-C. Using the AesGcm class
Replies
1
Boosts
0
Views
1.3k
Activity
Jul ’21
AES-GCM 256 Encrypt & Decrypt in iOS Swift Sync with .Net output
Hi I want to use AES-GCM encryption of a plaintext with 'key' only. The 'key' will be received from backend (.net), in webservice response. The same key will be used later in backend as well to decrypt the encrypted value. I have used extension as follwoing To generate string to Symetric key extension SymmetricKey { init(string keyString: String, size: SymmetricKeySize = .bits256) throws { guard var keyData = keyString.data(using: .utf8) else { print("Could not create base64 encoded Data from String.") throw CryptoKitError.incorrectParameterSize } let keySizeBytes = size.bitCount / 8 keyData = keyData.subdata(in: 0..<keySizeBytes) guard keyData.count >= keySizeBytes else { throw CryptoKitError.incorrectKeySize } self.init(data: keyData) } } Encryption & Decryption code snipet: func aesgcmEncryptDecrypt() { let str : String = "FwhXRYJ$xLf?^Kh6_&YfTJ%RuG+EqcTY" var key : SymmetricKey = SymmetricKey(size: .bits256) do{ key = try SymmetricKey(string: str) }catch{ } let plain = "HOW ARE YOU?" let nonce = try! AES.GCM.Nonce(data: Data(base64Encoded: "fv1nixTVoYpSvpdA")!) let tag = Data(base64Encoded: "e1eIgoB4+lA/j3KDHhY4BQ==")! // Encrypt let sealedBox = try! AES.GCM.seal(plain.data(using: .utf8)!, using: key, nonce: nonce, authenticating: tag) // Decrypt let sealedBoxRestored = try! AES.GCM.SealedBox(combined: sealedBox.combined!) let decrypted = try! AES.GCM.open(sealedBoxRestored, using: key, authenticating: tag) Swift.print("Combined:\n(sealedBox.combined!.base64EncodedString())\n") Swift.print("Cipher:\n(sealedBox.ciphertext.base64EncodedString())\n") Swift.print("Nonce:\n(nonce.withUnsafeBytes { Data(Array($0)).base64EncodedString() })\n") Swift.print("Tag:\n(tag.base64EncodedString())\n") Swift.print("Decrypted:\n(String(data: decrypted, encoding: .utf8)!)\n") } Our(generated from this code & .Net code) encrypted text is not matching. Anyone can help me, what I am doing wrong, detailing will be more helpful. Basically I was looking for saloution in Objective-C but I did not get any supported library for Objective-C.
Replies
1
Boosts
0
Views
2.2k
Activity
Jul ’21
Mac OS 11.4 Token Sign not working
I'm having a problem accessing a site where I need to use a certificate for identification, where I used some examples to type the pin but none works, I checked an instruction to register a module in firefox as a security device but it doesn't work, it worked on macos 10.15 , but now when adding the security device , the slot does not appear in Firefox. Tank's
Replies
1
Boosts
0
Views
935
Activity
Jul ’21
SecKeyCreateWithData Returns ‘Nil’ with Error
We are trying to create a ’SecKey’ from a ‘.der’ file. But ‘SecKeyCreateWithData’ always throw ‘Nil ’ with Error. Steps Followed:: First we created a ECDSA Private & Public key pair with the below Commands , then converted the .pem file holding the private key to ‘.der’file. Finally used the ‘.der’ file to generate a ‘SecKey’ via code. Commands Used to Generate Private & Public Keys:: openssl ecparam -genkey -name prime256v1 -noout -out ec-key-pair.pem openssl ec -in ec-key-pair.pem -pubout -out ec-key-pair.pub Command Used to Generate .Der file:: openssl pkey -outform der -in ec-key-pair.pem -out ec-key-pair.der Content Inside .pem file:: -----BEGIN EC PRIVATE KEY----- MHcCAQEEIKJTc3zI8D07Myh7ZIR+wGyQgsjEeKdH0+hSiErK5AjzoAoGCCqGSM49 AwEHoUQDQgAEvbOBrM/D2fX05zKQYuJiTRP6YiUBabImrHb9s+OHimxUxX+E9jVe oQ6nxSOkfgm0H1OjLfp2xGLqkDTuF38UGQ== -----END EC PRIVATE KEY----- Error Received:: Unmanaged - _value : Error Domain=NSOSStatusErrorDomain Code=-50 "EC private key creation from data failed" UserInfo={NSDescription=EC private key creation from data failed} Minimum Deployment Target Used:: iOS 14.0 Code Used:: if let certificateData = NSData(contentsOf:Bundle.main.url(forResource: "ec-key-pair", withExtension: "der")! ) {       var error: Unmanaged<CFError>? = nil       let privateSecKey = SecKeyCreateWithData(certificateData , [           kSecAttrKeyType: kSecAttrKeyTypeEC,           kSecAttrKeyClass: kSecAttrKeyClassPrivate] as NSDictionary, &error) }
Replies
2
Boosts
0
Views
2.3k
Activity
Jul ’21
How to convert base64 encoded private key and public key with EC with secp256r1 (curve) to SecKey using swift4 code?
I am searching for a way using swift4 code (not terminal commands) to convert base64 encoded private key and public key with EC with secp256r1 (curve) to SecKey. After I get private and public SecKey, I will be signing some data and verifying the same with SHA256withECDSA algorithm.
Replies
1
Boosts
0
Views
1.1k
Activity
Jul ’21
RSA Key Generating use Security, SecKeyCreateRandomKey
i want make RSA pair key to 512bit i find SecKeyCreateRandomKey, CrytoKit, another open lib.. I decided to use Security I have to give the server developer the string value of the rsa file I created I sent you an rsa string but server developer answered that the format was wrong I wonder what is wrong with my code. Or I want to be helped to generate an rsa key and chage type into a string this is my code first - make private key using SecKeyCreateRandomKey func createPrivateKey()-> SecKey?{           let privateKeyParams: [String: Any] = [       kSecAttrIsPermanent as String: true,       kSecAttrApplicationTag as String: tagName     ]           let parameters: [String: Any] = [       kSecAttrKeyType as String: kSecAttrKeyTypeRSA,       kSecAttrKeySizeInBits as String: 512,       kSecPrivateKeyAttrs as String: privateKeyParams     ]           var error: Unmanaged<CFError>?           guard let privateKey = SecKeyCreateRandomKey(parameters as CFDictionary, &error) else     {       NSLog("\tError generating keypair. %@", "\(error!.takeRetainedValue().localizedDescription)")       return nil     }     return privateKey   } second - get public key using private key of Seckey func getPublicKey(key: SecKey) -> SecKey?{     return SecKeyCopyPublicKey(key)   } third - get public key Data using public key seckey func getPublicData(key: SecKey) -> CFData?{     return SecKeyCopyExternalRepresentation(key, nil)   } fouth - string of public key using public key of Data  public func exportPublicKey(_ rawPublicKeyBytes: Data, base64EncodingOptions: Data.Base64EncodingOptions = []) -> String?   {    Log.debug("exportPublicKey", rawPublicKeyBytes.base64EncodedString(options: base64EncodingOptions))     return rawPublicKeyBytes.base64EncodedString(options: base64EncodingOptions)   } last i send result of exportPublicKey() rsa string like this MEgCQQDCmgOuSGbG/Mtq2NnHlBQU5rsGnNf17h4NZy+2lyrjKGgaVpD66QHmx2Na+/QQaamEhUgkFAkj0UlkMTRWGKO5AgMBBBE= or -----BEGIN PUBLIC KEY----- MEgCQQDCmgOuSGbG/Mtq2NnHlBQU5rsGnNf17h4NZy+2lyrjKGgaVpD66QHmx2Na+/QQaamEhUgkFAkj0UlkMTRWGKO5AgMBBBE= -----END PUBLIC KEY-----
Replies
2
Boosts
0
Views
1.4k
Activity
Jul ’21