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

Swift smart contracts
Hello, I came on this forum to ask if there were any other developers or teams currently working on the Swift Based Blockchain protocol for Apple to make "Dapples"? I was hoping that someone would guide me in the right direction as far as exporting my solidity based smart contract application into swift / into Xcode. I cannot find out how to connect solidity and Xcode to make Dapps, and I was wondering if anyone was working on making the official smart contract for Swift IOS? thank you, Dylan Kawalec DYLANKAWALEC@GMAIL.COM 9284990093
1
0
2.4k
Jan ’23
How to create PublicKey from PEM?
I'm pretty new to RSA Keys and Certificates and all of that. So I'm getting a PEM File from a network request, I understand the PEM file is basically the certificate without header and footer, so essentially I have a string. I need to create a PublicKey from that in order to Encrypt some text, but I think I'm doing something wrong. This is my code so far, I have talked to other teams (Android) and when they print out the Encrypted Data, they are getting a regular String and I'm getting lots of weird characters. Thanks in advance guys! (: func encryptBase64(text: String, certificateStr: String) throws -> Data { let encryptionError = EncrpytionError(message: "There has been an issue with encryption") guard let certData = Data(base64Encoded: certificateStr), let certificate = SecCertificateCreateWithData(nil, certData as CFData), let publicKey = SecCertificateCopyKey(certificate) else { throw encryptionError } let algorithm: SecKeyAlgorithm = .rsaEncryptionOAEPSHA256AESGCM guard SecKeyIsAlgorithmSupported(publicKey, .encrypt, algorithm) else { throw encryptionError } guard let cipherText = SecKeyCreateEncryptedData( publicKey, algorithm, text.data(using: .utf8)! as CFData, nil) else { throw encryptionError } return cipherText as Data } And when I try to print cipherText as a String using let encryptedString = String(decoding: encryptedData, as: UTF8.self) I just get this weird thing: "D�aj�\\m꒤h,�A�{��8�~�\nY\u0003F�Cˤ�@��\"�\u0018�\u0007\u001fX@VC�U_��E\u0005dž1���X��\/4Px��P\u0016�8}% ��<��@�I_�K\u000e�\bR*�� ���斋�7,�%���F^q�\u0000\\�'�ZTD\u0013Q�_\u0010\u001f>i]&��B���@1\u0006\b��E\u0004�F���yS\u0013�3����SB)��m\u0017%��5ʲ����s\u0003��r�&�?�8b��W@\u001e��؞ۡ��8�s~��ӹ�u\"�2��U�&\b�3XV���˔Y��xt[\fm&P:\\�\f� y��6jy" Android team is doing something like this using Kotlin: private fun extractPublicKey(certificateString: String): PublicKey { val encodedCertificateBytes = certificateString.toByteArray() val decodedCertificateBytes = Base64.decode(encodedCertificateBytes, Base64.DEFAULT) val inStream = decodedCertificateBytes.inputStream() val certificateFactory = CertificateFactory.getInstance("X.509") val certificate = certificateFactory.generateCertificate(inStream) inStream.close() return certificate.publicKey }
1
0
1.7k
Jan ’23
Encryption result with iPhone 14 devices
Hi I have code that uses SecKeyEncrypt to encrypt a string. SecKeyEncrypt(publickeysi!, SecPadding.PKCS1, aString, aString.count, &messageEncrypted, &messageEncryptedSize) This works across all devices, given identical source string, except the recently released iPhone 14 and Pro models. Simulator works across the board. Is there any reason why these devices would result in a B64 encoded string along the lines of AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA== where all other devices return an appropriate B64 string, such as DNfdGmJW8DOeuwB9DZxMjY/qcJHgKCewMd/Hi3m1vkHxdRaeQbYvFbmnJwtcudnqm9cRiT/cee1ls5Hm6bcmVtGPf23O4SnOha97MhrJIaUWOumUdRfKd5PYVd74NVuWPfQ+VHlKFQtiVjBNvNntiZmadBEV95BwRcxFWSVLDG7tfgzM2tNvYsDG+ZwN0r3F1AX4IH/Ggor9Dk//26c5WZ50HzwfkeY122qMDIj2LDCUGXXhXzkvSyEYFReJhscwtXdDk1nN49jrDB5bEUD9Xn1xZzlghpcSNC4DKqP/3TSuwqcHZ7g/BfYcRVtXeWGqUxeeQcaTNulUggCWWGdtJw== It appears that SecKeyEncrypt is deprecated in iOS 15 but I am struggling to find an appropriate alternative if that is even the issue. Thanks
3
0
1.5k
Dec ’22
How to implement AES encryption in swift
Parallel Android code is below: public static String getEncryptedText(String plainText, SecretKey secretKey) { if(plainText == null) { plainText = ""; } try { byte[] ivBytes = new byte[GCM_IV_LENGTH]; SecureRandom random = new SecureRandom(); random.nextBytes(ivBytes); String iv = Base64.getEncoder().encodeToString(ivBytes); byte[] cipherText = encrypt(plainText.getBytes(), secretKey, ivBytes); String text = Base64.getEncoder().encodeToString(cipherText); text = iv+text; return text; } catch (Exception e) { e.printStackTrace(); return ""; } } private static byte[] encrypt(byte[] plaintext, SecretKey key, byte[] nonce) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES"); GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, nonce);
1
0
1.5k
Dec ’22
HMAC<SHA256> in swift
I have 2 apps, I use HMAC for signature between apps. First App's minimum deployment target is 11.2 and it uses CryptoSwift for sending data to the second app while signing documents. But the Second app uses Apple's CryptoKit, and I get a signing error. Can I use different packages for HMAC Sha256 process?
1
0
3k
Oct ’22
CryptoKit X448 support
Hi, is there any chance for X448 and Ed448 elliptic curve support in CryptoKit (or other security framework) anytime soon? I need to support this curve in my project and really like to avoid messing with OpenSSL or other third party libs. Thanks much Matt
2
0
1.2k
Sep ’22
Diffie Hellman exchange for ECDH-ES not working properly, getting wrong secret key
HI all, I am trying to implement diffie-hellman key exchnage, by generating a secret key with an EC public key receives from API and the private key already generated in the project. Also I need to perform the KDF operation by passing some parameters. Here what my project code look like generating the secret key func generateSharedSecret(issuerPublicKey: SecKey, devicePrivateKey: SecKey, parameters:[SecKeyKeyExchangeParameter: Any] = [:]) throws -> Data? {     var error: Unmanaged<CFError>?     guard let shared = SecKeyCopyKeyExchangeResult(devicePrivateKey, .ecdhKeyExchangeStandard, issuerPublicKey, parameters as CFDictionary, &error) else {         let errStr = error?.takeRetainedValue().localizedDescription ?? "Derive Key Fail"         print(errStr)         throw error!.takeRetainedValue() as Error     }     return shared as Data } Setup parameters for performing secret key operation and KDF var algId: Data, keyDataLen: Int             algId = "".data(using: .utf8)!             keyDataLen = 256             let algorithmID = prefixedBigEndenLen(from: algId)             let partyUInfo = prefixedBigEndenLen(from: apu)             let partyVInfo = prefixedBigEndenLen(from: apv)             let suppPubInfo = intToData(value: UInt32(keyDataLen).bigEndian)             let suppPrivInfo = Data()             let concatedData = algorithmID + partyUInfo + partyVInfo + suppPubInfo + suppPrivInfo             let params = [SecKeyKeyExchangeParameter.requestedSize: 32, SecKeyKeyExchangeParameter.sharedInfo: concatedData] as [SecKeyKeyExchangeParameter : Any]             // Function call:             let sharedSecret = try generateSharedSecret(issuerPublicKey: pubKey, devicePrivateKey: eprivKey, parameters: params as [SecKeyKeyExchangeParameter : Any]) By using the resulting generated secret key I have performed the JWE encryption and got some encrypted string as output. The problem what I am facing it is not decrypting on the server side and server returns "Unable to parse error". Can anyone let me know, is it the correct way to generate a secret key? What am I doing wrong here? Thanks
5
0
2.3k
Sep ’22
CryptoKit sign payload and header with private key
I am trying to create a jwt token signed with Elliptic Curve Digital Signature Algorithm (ECDSA) with the P-256 curve and the SHA-256 hash algorithm. The payload and the header are created properly, but I am having problems signing it. The P256.Signing.PrivateKey(rawRepresentation: keyData) always returns nil. Can anyone please help? let privateKey = """ -----BEGIN ENCRYPTED PRIVATE KEY----- code -----END ENCRYPTED PRIVATE KEY----- """ let keyData = Data(base64Encoded: privateKey.toBase64())!     let header = jwtHeader()     let payload = jwtPayload()     let signingInput = "\(header).\(payload)"     let privateKey = try! P256.Signing.PrivateKey(rawRepresentation: keyData)     let sig = try! privateKey.signature(for: Data(signingInput.utf8)).rawRepresentation     return "\(signingInput).\(sig.base64URLEncodedString)" extension String {     func toBase64() -> String {         return Data(self.utf8).base64EncodedString()     } }
3
0
1.9k
Sep ’22
How can I verify publicKey fingerprint generated by other languages(Ruby)
Hello, I am trying to verify a EC publicKey(prime256v1) fingerprint generated by Ruby by using Swift's CryptoKit but I did't find any source or an example to verify the publicKey fingerprint. Someone please help me to provide a way to do verify in Swift? Example code to generate fingerprint in Ruby. OpenSSL::PKey::EC.new(public_key) fingerprint = key.fingerprint("sha256") Example PublicKey and its fingerprint PublicKey -----BEGIN PUBLIC KEY----- MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEJAZCn9MKy4TRr7GPcEdkgrVK0EAE fsASHQW4hOOj0UtIWAd7e1xT60zVeFPKKJrB7v5OE9Ha/Xs01IcSsVgE1w== -----END PUBLIC KEY----- Fingerprint SHA256:5r1Tcd4ZGfnY+NQIhXHx6mSGB4rz59JK0lrVUZoXNPI
1
0
1.4k
Aug ’22
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
10
1
4.7k
Jul ’22
SecureEnclave - Communcation between Node Server and Device
Hi, I want to use the iOs Secure Enclave to create a "Primary Device" Mechanism. It would work like this. Device Creates Enclave Key Pair and Sends the Public Key to the Server (Preferably Node JS) The Server encrypts a random message with the Public Key and sends it to the Device. I can be sure the Device is the only one able to decipher that string, because the private key is safe in the Secure Enclave Now the client would decrypt the message and send the result to the server which can compare it to the original message. When de- and encrypting Data in the ios ecosystem the process is straightforward. I Encrypt Data using SecKeyCreateEncryptedData and Decrypt using SecKeyCreateDecryptedData passing Public Key and CipherText Objects. Now my question is: how can I export the public Key to have my Node JS Backend encrypt Messages which will be decryptable again with the SecureEnclave.
2
0
1.2k
May ’22
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!
12
0
9.6k
Mar ’22
Why failed to add or get key in secure enclave on iPhone with iOS 12.x when running in loop
I have a project that use secure enclave to encrypt my data, this project minimum supports from iOS 11. To make sure the stability of my project, I run test, it has a loop to add, get, delete key in secure enclave for 100 iterations. I found that the secure enclave always failed to add/get key from secure enclave when using iOS device that is iOS 12.x. It returns error message - The operation couldn’t be completed. (OSStatus error -26276 - Key generation failed, error -26276) error code -26276 is errSecInternal - An internal error occured in the Security framework. I tested 23 devices, there are 5 out of 6 failed on iOS 12.x devices, the remaining devices with iOS 11.x, 13.x, 14.x, 15.x do not face this issue. Why it only happens on iOS 12.x device?
4
0
3.3k
Mar ’22
Use Cryptotokenkit for mail deciphering
Hello, I recently implemented the Cryptotokenkit for IOS in order to sign mails (via Apple Mail app). This part went relatively smooth. I found in the Mail settings the parameter under S/MIME that enable Signing mails. Now that this step is complete I also wanted to implement mail deciphering. I tried to run some tests but I met the following message when opening encrypted mail: This message is encrypted. Install a profile containing your encryption identity to decrypt this message I'm sure I've encrypted the mail for me. and I'm also sure the identity is saved and usable inside the Cryptotokenkit I implemented. My questions are: is it possible to use the Cryptotokenkit for mail deciphering? (I assume that since I can sign mail via Cryptotokenkit I can also do mail deciphering, right ?). If the first question's answer is yes. then how do you enable the Cryptotokenkit to do mail deciphering? (I thought the option was close to the one for enabling signing mails but I only found mail encryption)
1
1
1.1k
Feb ’22
Can I use private key to encrypt data using SecKeyCreateEncryptedData()
I want to perform RSA encryption&amp;Decryption using SecKeyCreateEncryptedData() Method allows public key as SecKey, My back end Java code has been set as encryption using private key &amp; decryption using public key. Here is a java code... @SuppressLint("NewApi") public static String encryptSecretKeyByPrivateKey(String data, String privatekeyPath) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { byte[] plaintext = data.getBytes(); PrivateKey privateKey = getPrivatekey(privatekeyPath); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, privateKey); byte[] encryptedByte = cipher.doFinal(plaintext); return Base64.getEncoder().encodeToString(encryptedByte); } public static PrivateKey getPrivatekey(String key) throws NoSuchAlgorithmException, InvalidKeySpecException { PrivateKey privateKey = null; KeyFactory keyFactory = null; byte[] encoded = DatatypeConverter.parseBase64Binary(key); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded); keyFactory = KeyFactory.getInstance("RSA"); privateKey = keyFactory.generatePrivate(keySpec); return privateKey; } Can I achieve the same in swift with the help of SecKeyEncrypt() or SecKeyCreateEncryptedData() ?
2
0
1.9k
Feb ’22
Swift smart contracts
Hello, I came on this forum to ask if there were any other developers or teams currently working on the Swift Based Blockchain protocol for Apple to make "Dapples"? I was hoping that someone would guide me in the right direction as far as exporting my solidity based smart contract application into swift / into Xcode. I cannot find out how to connect solidity and Xcode to make Dapps, and I was wondering if anyone was working on making the official smart contract for Swift IOS? thank you, Dylan Kawalec DYLANKAWALEC@GMAIL.COM 9284990093
Replies
1
Boosts
0
Views
2.4k
Activity
Jan ’23
How to create PublicKey from PEM?
I'm pretty new to RSA Keys and Certificates and all of that. So I'm getting a PEM File from a network request, I understand the PEM file is basically the certificate without header and footer, so essentially I have a string. I need to create a PublicKey from that in order to Encrypt some text, but I think I'm doing something wrong. This is my code so far, I have talked to other teams (Android) and when they print out the Encrypted Data, they are getting a regular String and I'm getting lots of weird characters. Thanks in advance guys! (: func encryptBase64(text: String, certificateStr: String) throws -&gt; Data { let encryptionError = EncrpytionError(message: "There has been an issue with encryption") guard let certData = Data(base64Encoded: certificateStr), let certificate = SecCertificateCreateWithData(nil, certData as CFData), let publicKey = SecCertificateCopyKey(certificate) else { throw encryptionError } let algorithm: SecKeyAlgorithm = .rsaEncryptionOAEPSHA256AESGCM guard SecKeyIsAlgorithmSupported(publicKey, .encrypt, algorithm) else { throw encryptionError } guard let cipherText = SecKeyCreateEncryptedData( publicKey, algorithm, text.data(using: .utf8)! as CFData, nil) else { throw encryptionError } return cipherText as Data } And when I try to print cipherText as a String using let encryptedString = String(decoding: encryptedData, as: UTF8.self) I just get this weird thing: "D�aj�\\m꒤h,�A�{��8�~�\nY\u0003F�Cˤ�@��\"�\u0018�\u0007\u001fX@VC�U_��E\u0005dž1���X��\/4Px��P\u0016�8}% ��&lt;��@�I_�K\u000e�\bR*�� ���斋�7,�%���F^q�\u0000\\�'�ZTD\u0013Q�_\u0010\u001f&gt;i]&amp;��B���@1\u0006\b��E\u0004�F���yS\u0013�3����SB)��m\u0017%��5ʲ����s\u0003��r�&amp;�?�8b��W@\u001e��؞ۡ��8�s~��ӹ�u\"�2��U�&amp;\b�3XV���˔Y��xt[\fm&amp;P:\\�\f� y��6jy" Android team is doing something like this using Kotlin: private fun extractPublicKey(certificateString: String): PublicKey { val encodedCertificateBytes = certificateString.toByteArray() val decodedCertificateBytes = Base64.decode(encodedCertificateBytes, Base64.DEFAULT) val inStream = decodedCertificateBytes.inputStream() val certificateFactory = CertificateFactory.getInstance("X.509") val certificate = certificateFactory.generateCertificate(inStream) inStream.close() return certificate.publicKey }
Replies
1
Boosts
0
Views
1.7k
Activity
Jan ’23
Can CryptoKit encrypt or decrypt streams?
I have a continuous data stream encrypted by aesgcm, I did not find a way to decrypt it using CryptoKit unless I have the full data. My question is Can CryptoKit decrypt or encrypt a stream without a complete read? Like EVP_xxx_Update in OpenSSL. Thank you.
Replies
8
Boosts
1
Views
3.1k
Activity
Jan ’23
Encryption result with iPhone 14 devices
Hi I have code that uses SecKeyEncrypt to encrypt a string. SecKeyEncrypt(publickeysi!, SecPadding.PKCS1, aString, aString.count, &messageEncrypted, &messageEncryptedSize) This works across all devices, given identical source string, except the recently released iPhone 14 and Pro models. Simulator works across the board. Is there any reason why these devices would result in a B64 encoded string along the lines of AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA== where all other devices return an appropriate B64 string, such as DNfdGmJW8DOeuwB9DZxMjY/qcJHgKCewMd/Hi3m1vkHxdRaeQbYvFbmnJwtcudnqm9cRiT/cee1ls5Hm6bcmVtGPf23O4SnOha97MhrJIaUWOumUdRfKd5PYVd74NVuWPfQ+VHlKFQtiVjBNvNntiZmadBEV95BwRcxFWSVLDG7tfgzM2tNvYsDG+ZwN0r3F1AX4IH/Ggor9Dk//26c5WZ50HzwfkeY122qMDIj2LDCUGXXhXzkvSyEYFReJhscwtXdDk1nN49jrDB5bEUD9Xn1xZzlghpcSNC4DKqP/3TSuwqcHZ7g/BfYcRVtXeWGqUxeeQcaTNulUggCWWGdtJw== It appears that SecKeyEncrypt is deprecated in iOS 15 but I am struggling to find an appropriate alternative if that is even the issue. Thanks
Replies
3
Boosts
0
Views
1.5k
Activity
Dec ’22
How to implement AES encryption in swift
Parallel Android code is below: public static String getEncryptedText(String plainText, SecretKey secretKey) { if(plainText == null) { plainText = ""; } try { byte[] ivBytes = new byte[GCM_IV_LENGTH]; SecureRandom random = new SecureRandom(); random.nextBytes(ivBytes); String iv = Base64.getEncoder().encodeToString(ivBytes); byte[] cipherText = encrypt(plainText.getBytes(), secretKey, ivBytes); String text = Base64.getEncoder().encodeToString(cipherText); text = iv+text; return text; } catch (Exception e) { e.printStackTrace(); return ""; } } private static byte[] encrypt(byte[] plaintext, SecretKey key, byte[] nonce) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES"); GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, nonce);
Replies
1
Boosts
0
Views
1.5k
Activity
Dec ’22
HMAC<SHA256> in swift
I have 2 apps, I use HMAC for signature between apps. First App's minimum deployment target is 11.2 and it uses CryptoSwift for sending data to the second app while signing documents. But the Second app uses Apple's CryptoKit, and I get a signing error. Can I use different packages for HMAC Sha256 process?
Replies
1
Boosts
0
Views
3k
Activity
Oct ’22
CryptoKit X448 support
Hi, is there any chance for X448 and Ed448 elliptic curve support in CryptoKit (or other security framework) anytime soon? I need to support this curve in my project and really like to avoid messing with OpenSSL or other third party libs. Thanks much Matt
Replies
2
Boosts
0
Views
1.2k
Activity
Sep ’22
Diffie Hellman exchange for ECDH-ES not working properly, getting wrong secret key
HI all, I am trying to implement diffie-hellman key exchnage, by generating a secret key with an EC public key receives from API and the private key already generated in the project. Also I need to perform the KDF operation by passing some parameters. Here what my project code look like generating the secret key func generateSharedSecret(issuerPublicKey: SecKey, devicePrivateKey: SecKey, parameters:[SecKeyKeyExchangeParameter: Any] = [:]) throws -> Data? {     var error: Unmanaged<CFError>?     guard let shared = SecKeyCopyKeyExchangeResult(devicePrivateKey, .ecdhKeyExchangeStandard, issuerPublicKey, parameters as CFDictionary, &error) else {         let errStr = error?.takeRetainedValue().localizedDescription ?? "Derive Key Fail"         print(errStr)         throw error!.takeRetainedValue() as Error     }     return shared as Data } Setup parameters for performing secret key operation and KDF var algId: Data, keyDataLen: Int             algId = "".data(using: .utf8)!             keyDataLen = 256             let algorithmID = prefixedBigEndenLen(from: algId)             let partyUInfo = prefixedBigEndenLen(from: apu)             let partyVInfo = prefixedBigEndenLen(from: apv)             let suppPubInfo = intToData(value: UInt32(keyDataLen).bigEndian)             let suppPrivInfo = Data()             let concatedData = algorithmID + partyUInfo + partyVInfo + suppPubInfo + suppPrivInfo             let params = [SecKeyKeyExchangeParameter.requestedSize: 32, SecKeyKeyExchangeParameter.sharedInfo: concatedData] as [SecKeyKeyExchangeParameter : Any]             // Function call:             let sharedSecret = try generateSharedSecret(issuerPublicKey: pubKey, devicePrivateKey: eprivKey, parameters: params as [SecKeyKeyExchangeParameter : Any]) By using the resulting generated secret key I have performed the JWE encryption and got some encrypted string as output. The problem what I am facing it is not decrypting on the server side and server returns "Unable to parse error". Can anyone let me know, is it the correct way to generate a secret key? What am I doing wrong here? Thanks
Replies
5
Boosts
0
Views
2.3k
Activity
Sep ’22
CryptoKit sign payload and header with private key
I am trying to create a jwt token signed with Elliptic Curve Digital Signature Algorithm (ECDSA) with the P-256 curve and the SHA-256 hash algorithm. The payload and the header are created properly, but I am having problems signing it. The P256.Signing.PrivateKey(rawRepresentation: keyData) always returns nil. Can anyone please help? let privateKey = """ -----BEGIN ENCRYPTED PRIVATE KEY----- code -----END ENCRYPTED PRIVATE KEY----- """ let keyData = Data(base64Encoded: privateKey.toBase64())!     let header = jwtHeader()     let payload = jwtPayload()     let signingInput = "\(header).\(payload)"     let privateKey = try! P256.Signing.PrivateKey(rawRepresentation: keyData)     let sig = try! privateKey.signature(for: Data(signingInput.utf8)).rawRepresentation     return "\(signingInput).\(sig.base64URLEncodedString)" extension String {     func toBase64() -> String {         return Data(self.utf8).base64EncodedString()     } }
Replies
3
Boosts
0
Views
1.9k
Activity
Sep ’22
How can I verify publicKey fingerprint generated by other languages(Ruby)
Hello, I am trying to verify a EC publicKey(prime256v1) fingerprint generated by Ruby by using Swift's CryptoKit but I did't find any source or an example to verify the publicKey fingerprint. Someone please help me to provide a way to do verify in Swift? Example code to generate fingerprint in Ruby. OpenSSL::PKey::EC.new(public_key) fingerprint = key.fingerprint("sha256") Example PublicKey and its fingerprint PublicKey -----BEGIN PUBLIC KEY----- MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEJAZCn9MKy4TRr7GPcEdkgrVK0EAE fsASHQW4hOOj0UtIWAd7e1xT60zVeFPKKJrB7v5OE9Ha/Xs01IcSsVgE1w== -----END PUBLIC KEY----- Fingerprint SHA256:5r1Tcd4ZGfnY+NQIhXHx6mSGB4rz59JK0lrVUZoXNPI
Replies
1
Boosts
0
Views
1.4k
Activity
Aug ’22
CryptoKit.CryptoKitError error 1 when using Symmetric key of size 512
Hi, Not working and error above. let key512 = SymmetricKey(size: .init(bitCount: 512)) let encryptedData512 = try ChaChaPoly.seal(clear_data2!, using: key512).combined If I change the bitcount to 256, no error. Same error even if I use AES.GCM Thanks
Replies
1
Boosts
0
Views
1.3k
Activity
Aug ’22
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
Replies
10
Boosts
1
Views
4.7k
Activity
Jul ’22
SecureEnclave - Communcation between Node Server and Device
Hi, I want to use the iOs Secure Enclave to create a "Primary Device" Mechanism. It would work like this. Device Creates Enclave Key Pair and Sends the Public Key to the Server (Preferably Node JS) The Server encrypts a random message with the Public Key and sends it to the Device. I can be sure the Device is the only one able to decipher that string, because the private key is safe in the Secure Enclave Now the client would decrypt the message and send the result to the server which can compare it to the original message. When de- and encrypting Data in the ios ecosystem the process is straightforward. I Encrypt Data using SecKeyCreateEncryptedData and Decrypt using SecKeyCreateDecryptedData passing Public Key and CipherText Objects. Now my question is: how can I export the public Key to have my Node JS Backend encrypt Messages which will be decryptable again with the SecureEnclave.
Replies
2
Boosts
0
Views
1.2k
Activity
May ’22
Difference between keys for EC KeyAgreement and Signing
Why does Cryptokit distinguish between private EC keys used for signing and key agreement? I noticed you can transform those keys into each other but for what purpose are they different? After all its an BigInt in both cases.
Replies
1
Boosts
0
Views
970
Activity
Apr ’22
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!
Replies
12
Boosts
0
Views
9.6k
Activity
Mar ’22
Why failed to add or get key in secure enclave on iPhone with iOS 12.x when running in loop
I have a project that use secure enclave to encrypt my data, this project minimum supports from iOS 11. To make sure the stability of my project, I run test, it has a loop to add, get, delete key in secure enclave for 100 iterations. I found that the secure enclave always failed to add/get key from secure enclave when using iOS device that is iOS 12.x. It returns error message - The operation couldn’t be completed. (OSStatus error -26276 - Key generation failed, error -26276) error code -26276 is errSecInternal - An internal error occured in the Security framework. I tested 23 devices, there are 5 out of 6 failed on iOS 12.x devices, the remaining devices with iOS 11.x, 13.x, 14.x, 15.x do not face this issue. Why it only happens on iOS 12.x device?
Replies
4
Boosts
0
Views
3.3k
Activity
Mar ’22
Use Cryptotokenkit for mail deciphering
Hello, I recently implemented the Cryptotokenkit for IOS in order to sign mails (via Apple Mail app). This part went relatively smooth. I found in the Mail settings the parameter under S/MIME that enable Signing mails. Now that this step is complete I also wanted to implement mail deciphering. I tried to run some tests but I met the following message when opening encrypted mail: This message is encrypted. Install a profile containing your encryption identity to decrypt this message I'm sure I've encrypted the mail for me. and I'm also sure the identity is saved and usable inside the Cryptotokenkit I implemented. My questions are: is it possible to use the Cryptotokenkit for mail deciphering? (I assume that since I can sign mail via Cryptotokenkit I can also do mail deciphering, right ?). If the first question's answer is yes. then how do you enable the Cryptotokenkit to do mail deciphering? (I thought the option was close to the one for enabling signing mails but I only found mail encryption)
Replies
1
Boosts
1
Views
1.1k
Activity
Feb ’22
Can I use private key to encrypt data using SecKeyCreateEncryptedData()
I want to perform RSA encryption&amp;Decryption using SecKeyCreateEncryptedData() Method allows public key as SecKey, My back end Java code has been set as encryption using private key &amp; decryption using public key. Here is a java code... @SuppressLint("NewApi") public static String encryptSecretKeyByPrivateKey(String data, String privatekeyPath) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { byte[] plaintext = data.getBytes(); PrivateKey privateKey = getPrivatekey(privatekeyPath); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, privateKey); byte[] encryptedByte = cipher.doFinal(plaintext); return Base64.getEncoder().encodeToString(encryptedByte); } public static PrivateKey getPrivatekey(String key) throws NoSuchAlgorithmException, InvalidKeySpecException { PrivateKey privateKey = null; KeyFactory keyFactory = null; byte[] encoded = DatatypeConverter.parseBase64Binary(key); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded); keyFactory = KeyFactory.getInstance("RSA"); privateKey = keyFactory.generatePrivate(keySpec); return privateKey; } Can I achieve the same in swift with the help of SecKeyEncrypt() or SecKeyCreateEncryptedData() ?
Replies
2
Boosts
0
Views
1.9k
Activity
Feb ’22
Support for SHA3 algorithm
Does swift have default support for SHA3-256 hashing algorithm for all devices iOS 12 and above?
Replies
2
Boosts
1
Views
3.4k
Activity
Feb ’22
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
Replies
1
Boosts
0
Views
655
Activity
Jan ’22