Apple CryptoKit

RSS for tag

Perform cryptographic operations securely and efficiently using Apple CryptoKit.

Apple CryptoKit Documentation

Posts under Apple CryptoKit tag

37 results found
Sort by:
Post not yet marked as solved
53 Views

decrypt on swift

good morning, I saw one of your old post on decrypting on swift. can you guide me on how you achieved it. any sources will be very welcomed. thank you
Asked
by farrel.
Last updated
.
Post not yet marked as solved
281 Views

import CryptoKit seems to not work in playground Xcode 13.2.1

Can't seem to get CryptoKit to import. Is there some other configuration setting, etc. I need to fix? I though all you need to do in a playground is the import statement. My code looks like this: import UIKit import CryptoKit let string = "Hello world" let data = Data(string.utf8) let digest = SHA256.hash(data: data) let hash = digest.compactMap { String(format: "%02x", $0)}.joined() print("The hash is \(hash)") Basically, I can't use any method from CryptoKit although when I was typing the import statement, soon as I typed 'Cr' I was prompted with the fill of 'CryptoKit'. It also working in an IoS project in Swift. So I know it's there. Just won't work in the playground. I get the following error message: error: Couldn't lookup symbols:   static CryptoKit.HashFunction.hash<τ_0_0 where τ_1_0: Foundation.DataProtocol>(data: τ_1_0) -> τ_0_0.Digest   static CryptoKit.HashFunction.hash<τ_0_0 where τ_1_0: Foundation.DataProtocol>(data: τ_1_0) -> τ_0_0.Digest   static CryptoKit.HashFunction.hash<τ_0_0 where τ_1_0: Foundation.DataProtocol>(data: τ_1_0) -> τ_0_0.Digest   static CryptoKit.HashFunction.hash<τ_0_0 where τ_1_0: Foundation.DataProtocol>(data: τ_1_0) -> τ_0_0.Digest   static CryptoKit.HashFunction.hash<τ_0_0 where τ_1_0: Foundation.DataProtocol>(data: τ_1_0) -> τ_0_0.Digest Appreciate any insights. Thanks
Asked
by Khaja.
Last updated
.
Post not yet marked as solved
111 Views

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-----
Asked Last updated
.
Post not yet marked as solved
267 Views

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?
Asked Last updated
.
Post not yet marked as solved
159 Views

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...
Asked
by aruffin.
Last updated
.
Post not yet marked as solved
221 Views

Support for SHA3 algorithm

Does swift have default support for SHA3-256 hashing algorithm for all devices iOS 12 and above?
Asked Last updated
.
Post not yet marked as solved
155 Views

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.
Asked Last updated
.
Post not yet marked as solved
334 Views

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.
Asked Last updated
.
Post not yet marked as solved
552 Views

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?
Asked Last updated
.
Post not yet marked as solved
4.6k Views

macOS 11 Big Sur breaks ssh-add -s /usr/lib/ssh-keychain.dylib

I am trying to add my smart card PIV cert to ssh-agent. In macOS 10.15 Catalina, it was as simple as: ssh-add -s /usr/lib/ssh-keychain.dylib But in macOS 11.1 Big Sur, the ssh-agent debug output says: failed PKCS#11 add of "/usr/lib/ssh-keychain.dylib": realpath: No such file or directory I am aware that macOS 11 caches system libraries ... but I believe that /usr/lib/ssh-keychain.dylib is in the cache. Any help would be greatly appreciated!
Asked
by jrnphd.
Last updated
.
Post not yet marked as solved
237 Views

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?
Asked Last updated
.
Post not yet marked as solved
261 Views

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))
Asked
by chriiiiii.
Last updated
.
Post not yet marked as solved
346 Views

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
Asked
by PhilipTP.
Last updated
.
Post not yet marked as solved
479 Views

Swift AES CBC 256 Encryption With Static 32bit Key and 32bit IV

We have the below Implementation in Android and the same has to be integrated into Swift. Key :- "d95acd54b4a821ff32c52825q931c194" IV :- "687b9509c25a34b8ad076346s8353d67" Here Both the Key and IV are 32 bits and below is the android code. public class AESEncryption { private static final String key = "d95acd54c6a821ff32c52825b931c194"; private static final String initVector = "687b9509c25a14b8ad076346d8353d67"; static byte[] bte = hexToBytes(initVector); public static String encrypt(String strToEncrypt) { try { CommonCode.showLog("log", bte.toString()); IvParameterSpec iv = new IvParameterSpec(bte); SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); CommonCode.showLog("IV after logs", iv.toString()); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); byte[] encrypted = cipher.doFinal(strToEncrypt.getBytes()); if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.O) { return Base64.getEncoder().encodeToString(encrypted).trim(); } else { return android.util.Base64.encodeToString(encrypted, android.util.Base64.DEFAULT).trim(); } } catch (Exception e) { CommonCode.showLog("Error while encrypting: ", e.toString()); } return null; } public static String decrypt(String strToDecrypt) { try { IvParameterSpec iv = new IvParameterSpec(bte); SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv); if (android.os.Build.VERSION.SDK_INT &gt;= android.os.Build.VERSION_CODES.O) { return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt))); } else { return new String(cipher.doFinal(android.util.Base64.decode(strToDecrypt, android.util.Base64.DEFAULT))); } } catch (Exception e) { CommonCode.showLog("Error while decrypting: " , e.toString()); } return null; } } How can we mimic the above in Swift? Here in Android they are using static byte[] bte = hexToBytes(initVector); to convert the 32bit IV into 16 bit Bytes Array I Have Tried the same approach on Swift below are the code snippet [Contents.swift](https://developer.apple.com/forums/content/attachment/60fab4f2-1496-4003-9f37-c195de95e94a)
Asked Last updated
.
Post marked as solved
603 Views

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
Asked
by jogi.
Last updated
.