Apple CryptoKit

RSS for tag

Perform cryptographic operations securely and efficiently using Apple CryptoKit.

Apple CryptoKit Documentation

Pinned Posts

Posts under Apple CryptoKit tag

28 Posts
Sort by:
Post not yet marked as solved
8 Replies
3.9k Views
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 >= 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 >= 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)
Posted Last updated
.
Post not yet marked as solved
1 Replies
148 Views
Hi All. I have a need to store encrypted data on device. The data is arriving from multiple services in our app in the form of one line of text at a time. This data has to be decrypted on a server, probably using Java. In Java, there is concept of a CipherStream. I'll init that stream with a private key and IV (nonce), and feed it data as I get it. Once done, I can close the stream, and I have an encrypted file. In IOS, I'm trying to emulate that process. However, the concept of SealedBox seems to be getting in the way. I can seal each piece of text, but decrypting those doesn't work. I believe this has to do with the way the data is produced by the box. I can decrypt each piece individually, but I can't find a way to feed this into a stream and ultimately seal the whole thing. I understand I can write the file plain text, and encrypt it at the end, but this leaves the data vulnerable for long periods of time. Anyone has any Ideas on how to solve this on IOS?
Posted
by SK-Arctop.
Last updated
.
Post not yet marked as solved
6 Replies
561 Views
My need is to efficiently detects if OS supports secure enclave. There seems to be one way to decide if the Secure Enclave is present: Create an elliptic curve encryption key in the Secure Enclave, If this fails, and the error has a code of -4 = errSecUnimplemented, then there is no Secure Enclave. My question, is there any way other approach to detect if system supports secure enclave?
Posted
by antonl1.
Last updated
.
Post marked as solved
2 Replies
224 Views
My end goal is to use eciesEncryptionCofactorX963SHA256AESGCM with a key generated on the Secure Enclave using CryptoKit, that requires Biometric Authentication. CryptoKit does not implement the ECIES encryption algorithms, so my goal was to fall back to the Security framework. The public key can be easily converted to a SecKey because it implements x963Representation which can then be imported as follows: let enclaveSecKey: SecKey = SecKeyCreateWithData(enclaveKey.x963Representation as CFData, [ kSecAttrKeyType: kSecAttrKeyTypeECSECPrimeRandom, kSecAttrKeyClass: kSecAttrKeyClassPublic, kSecAttrKeySizeInBits: 256 ] as [String: Any] as CFDictionary, nil), I have everything working except the code to decrypt with the private key. Naturally, the Secure Enclave does not expose the private key - as is its design - rather some kind of token? I did read the Keychain documentation which notes that it is not possible to simply obtain an x963Representation of the private key (as it's a custom representation returned by the Secure Enclave). However, my ultimate question is this: can one convert the Secure Enclave representation into something that can be used as a SecKey for encryption/decryption (without necessarily being stored in the Keychain - i.e., 'correct') as it seems both CryptoKit and Security have a means of representing the private key token returned by the Secure Enclave? (Or is one's only recourse to use the Security framework for generating and storing the keys too?) I have also tried this code to create a SecKey representation, having retrieved the GenericPasswordConvertible out of the keychain (note the use of kSecAttrTokenID: kSecAttrTokenIDSecureEnclave) with the aforementioned goal of loading the Secure Enclave's private token as a SecKey: let enclaveSecKey: SecKey = SecKeyCreateWithData(enclaveKey.rawRepresentation as CFData, [ kSecAttrKeyType: kSecAttrKeyTypeECSECPrimeRandom, kSecAttrKeyClass: kSecAttrKeyClassPrivate, kSecAttrTokenID: kSecAttrTokenIDSecureEnclave, kSecAttrAccessible: kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly, kSecUseAuthenticationContext: try await createAuthContext( reason: "Decrypt data", fallbackTitle: "Enter your device password to decrypt data", mustEvaluate: true ), kSecAttrIsPermanent: true, kSecAttrIsExtractable: false, kSecAttrSynchronizable: false, kSecAttrKeySizeInBits: 256, kSecAttrAccessControl: SecAccessControlCreateWithFlags( nil, kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly, [.biometryAny, .privateKeyUsage], &cfSecKeyCreateError )! ] as [String: Any] as CFDictionary, nil) This works, in and of itself, (i.e., it loads without error and cfSecKeyCreateError is nil, however when I try SecSecKeyCopyPublicKey I get a different, incorrect public key and - naturally, I suppose - if I attempt to decrypt data with the private key that fails with: Optional(Swift.Unmanaged<__C.CFErrorRef>(_value: Error Domain=NSOSStatusErrorDomain Code=-50 "ECIES: Failed to aes-gcm decrypt data (err -69)" UserInfo={numberOfErrorsDeep=0, NSDescription=ECIES: Failed to aes-gcm decrypt data (err -69)}))
Posted
by samjakob.
Last updated
.
Post not yet marked as solved
0 Replies
175 Views
When implementing SiwA on the client, you have the option of passing a nonce to a ASAuthorizationOpenIDRequest (docs). Here's a snippet of the relevant code that could be part of a SiwA implementation: let appleIDProvider = ASAuthorizationAppleIDProvider() let request = appleIDProvider.createRequest() request.requestedScopes = [.fullName, .email] request.nonce = /* What should this look like? */ let authorizationController = ASAuthorizationController(authorizationRequests: [request]) My core question is: are there any restrictions on its length and allowed characters? A similar conversation has been had on this SO post, but I'd like to know if there are any nonce generation implications from a SiwA perspective, as opposed to another auth service provider. The SecRandomCopyBytes docs include the following snippet: var bytes = [Int8](repeating: 0, count: 10) let status = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes) if status == errSecSuccess { // Always test the status. print(bytes) // Prints something different every time you run. } Could the result here be used as a SiwA nonce? Should I instead use the random bytes to index into an alphanumeric array of characters so my nonce contains alphanumerics rather than just numbers? CryptoKit also includes the following API that looks relevant: let nonce = ChaChaPoly.Nonce() The docs say this is a 12-byte nonce– can I throw that in a string and use it? I'd appreciate any clarification on generating nonces for the ASAuthorizationOpenIDRequest API? Thanks!
Posted
by nickcooke.
Last updated
.
Post not yet marked as solved
2 Replies
196 Views
I want to use ECC (curve25519) with Diffie-Hellman Key exchange. Backend is using ECC with X9.62 and PKCS#8 encoding. I want to achieve same on iOS so that I can fetch data from backed, decrypt it and show it to user. I tried this code but didn't work func getPEM() -> String { let keyPair = Curve25519.Signing.PrivateKey() let pubKey = keyPair.publicKey let pem = "-----BEGIN PUBLIC KEY-----\(pubKey.rawRepresentation.base64EncodedString())-----END PUBLIC KEY-----" return pem } After searching on Google I found that In order to get PEM we need DER and ASN1 from my public key but they are not supported by CryptoKit. Android is able to get right PEM using bouncycastle. Just for reference I am posting snippet from android code base. import org.bouncycastle.asn1.x9.X9ECParameters import org.bouncycastle.crypto.ec.CustomNamedCurves import org.bouncycastle.jcajce.provider.asymmetric.util.EC5Util import org.bouncycastle.jce.provider.BouncyCastleProvider import java.security.* import java.security.spec.ECParameterSpec import java.security.spec.InvalidKeySpecException import java.security.spec.PKCS8EncodedKeySpec import java.security.spec.X509EncodedKeySpec object CryptoKeyGenerator { init { Security.removeProvider(BOUNCY_CASTLE_IDENTIFIER) Security.addProvider(BouncyCastleProvider()) } fun getClientKeyMaterial(): String { val keyPair = generateEphemeralKeyPair() val pemEncodedPublicKey = getPEMEncodedStream(keyPair.public, false) return pemEncodedPublicKey } private fun getPEMEncodedStream(key: Key, privateKey: Boolean): String { val pkcS8EncodedKeySpec = PKCS8EncodedKeySpec(key.encoded) val stringBuilder = StringBuilder() val keyType = if(privateKey) PRIVATE_KEY else PUBLIC_KEY stringBuilder.append(KEY_HEADER_START + keyType + KEY_HEADER_END) stringBuilder.append(CryptoUtils.getBase64Encoded(pkcS8EncodedKeySpec.encoded)) stringBuilder.append(KEY_FOOTER_START + keyType + KEY_HEADER_END) return stringBuilder.toString() } /** * This method generates an ECC KeyPair with Curve25519 specs */ private fun generateEphemeralKeyPair(): KeyPair { val keyPairGenerator = KeyPairGenerator.getInstance(EC_ALGO_IDENTIFIER, BOUNCY_CASTLE_IDENTIFIER) val eccParameters: X9ECParameters = CustomNamedCurves.getByName(ECC_CURVE_SPEC) val eccSpec: ECParameterSpec = EC5Util.convertToSpec(eccParameters) keyPairGenerator.initialize(eccSpec) return keyPairGenerator.generateKeyPair() } } Android generated PEM of public key look like this -----BEGIN PUBLIC KEY-----MIIBMTCB6gYHKoZIzj0CATCB3gIBATArBgcqhkjOPQEBAiB/////////////////////////////////////////7TBEBCAqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqYSRShRAQge0Je0Je0Je0Je0Je0Je0Je0Je0Je0Je0JgtenHcQyGQEQQQqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq0kWiCuGaG4oIa04B7dLHdI0UySPU1+bXxhsinpxaJ+ztPZAiAQAAAAAAAAAAAAAAAAAAAAFN753qL3nNZYEmMaXPXT7QIBCANCAAQwsdIRTVn2+6rlgqAhVvx7ERj/Oku0wHmZZU1OST617h95ygSP5zJOa9lNiKqZMArjtJh7yQ4rg7kUq08Nv8+Q-----END PUBLIC KEY----- Other references: This repo has code for C, Java and nodejs https://github.com/Sahamati/rahasya
Posted
by kmithi1.
Last updated
.
Post marked as solved
7 Replies
1.6k Views
Hi, How do I generate the pem representation of a curve25519 public key? I can generate the key using :      let privateKey = Curve25519.KeyAgreement.PrivateKey() let publicKey = privateKey.publicKey print(publicKey.rawRepresentation.base64EncodedString()) This prints a string like this : GyQfzi3bLfpDpzi8e9j6lovX15EZY1t1fQQcnJlURxI= But the expected strings are more like : ----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEApxUNh3jHlNSAWE7fadipsh9AjXv6439VY3EWEC5kbgY=\n-----END PUBLIC KEY Even if I add the " -----BEGIN PUBLIC KEY-----" and "-----END PUBLIC KEY-----" tags, it still doesn't process the key. So what format is exactly the base64 encoded string of the raw format of curve25519 public key? And how do I generate the public key pem format? The requirement is for Swift iOS.
Posted Last updated
.
Post not yet marked as solved
1 Replies
291 Views
Hi, I am using CryptoKit in my app. I am getting an error sometimes with some users. I log the description to Firebase but I am not sure what is it exactly about.  CryptoKit.CryptoKitError error 2  CryptoKit.CryptoKitError error 3 I receive both of these errors. I also save debug prints to a log file and let users share them with me. Logs are line-by-line encrypted but after getting these errors in the app also decryption of log files doesn't work and it throws these errors too. I couldn't reproduce the same error by myself, and I can't reach the user's logs so I am a little blind about what triggers this. It would be helpful to understand what these errors mean. Thanks
Posted Last updated
.
Post not yet marked as solved
4 Replies
576 Views
Hi, I'm using CryptoKit to implement a spec that uses ECDH using P256. The spec says that one should check that the computed shared secret is not all 0x00 bytes. I understand that this can only happen if one of both keys used is the identity point on the curve. Does CryptoKit guarantee that P256.KeyAgreement.PublicKeys can never be the identity point by construction? (as e.g. the Rust elliptic_curve public keys do, according to their documentation)
Posted
by tramo.
Last updated
.
Post marked as solved
3 Replies
433 Views
I am working on an application on IOS and I need to be able to decrypt an element that has been encrypted with a public key, but I only know the modulus and the private exponent of the private key. How can I obtain the private key from these elements in IOS? In java, with the following code I can get the private key from these elements and I can decrypt the element. final RSAPrivateKeySpec privateSpec = new RSAPrivateKeySpec(MODULUS, PRIVATE_EXPONENT); final KeyFactory factory = KeyFactory.getInstance("RSA"); final PrivateKey priv = factory.generatePrivate(privateSpec); On ios, I got the following code, but it doesn't return the private key:      let smodulus = "00c35d6ac32d287dab681c78272931b60ca442bd4505e1b306432af92ef6e07bc3e4e24c2bc2dac69c94753390c3793b80734ef906520a96cafb146ce587ab383e78efc58c5ccf56b5084f3f9bc719e646a0361155ab56b7d71b49f1f90673383ea0fdb4a67900c0973930aa3bc7071c479b4a5d229fcab7ce22b84c1637d7e70b"     let sPrivateExponent = "1f2535700832fc55e73322b49b8ca14942a6a125efda1b805414f5c4d6f6d2c45828fb9bbe64c2651405db42a8e71ae54f7cb7969a5db5cc865aab41ac6f4f77deccb51496fe588f9dcd724a1d49cab96712621afc9c656c56dea011f8ab8e12a321fd62430902b15586a36093a6679e31b67017397da83b0992f5f816017701"     let sPublicExponent = "010001"    public static func getPrivateKey(smodulus: String, sPrivateExponent: String) -> SecKey? {              let pubExponent: [UInt8] = [1, 0, 1]     let exponent: [UInt8] = sPrivateExponent.hexaBytes     var modulus: [UInt8] = smodulus.hexaBytes           //modulus.insert(0x00, at: 0)           var modulusEncoded: [UInt8] = []     modulusEncoded.append(0x02)     modulusEncoded.append(contentsOf: lengthField(of: modulus))     modulusEncoded.append(contentsOf: modulus)     var exponentEncoded: [UInt8] = []     exponentEncoded.append(0x02)     exponentEncoded.append(contentsOf: lengthField(of: exponent))     exponentEncoded.append(contentsOf: exponent)           var sequenceEncoded: [UInt8] = []     sequenceEncoded.append(0x30)     sequenceEncoded.append(contentsOf: lengthField(of: (modulusEncoded + exponentEncoded)))     sequenceEncoded.append(contentsOf: (modulusEncoded + exponentEncoded))           let keyData = Data(bytes: sequenceEncoded)           // RSA key size is the number of bits of the modulus.     let keySize = (modulus.count * 8)     let attributes: [String: Any] = [       kSecAttrKeyType as String: kSecAttrKeyTypeRSA,       kSecAttrKeyClass as String: kSecAttrKeyClassPrivate,       kSecAttrKeySizeInBits as String: keySize     ]                 let privateKey = SecKeyCreateWithData(keyData as CFData, attributes as CFDictionary, nil)                       return privateKey   }  private static func lengthField(of valueField: [UInt8]) -> [UInt8] {     var count = valueField.count     if count < 128 {       return [ UInt8(count) ]     }     // The number of bytes needed to encode count.     let lengthBytesCount = Int((log2(Double(count)) / 8) + 1)     // The first byte in the length field encoding the number of remaining bytes.     let firstLengthFieldByte = UInt8(128 + lengthBytesCount)     var lengthField: [UInt8] = []     for _ in 0..<lengthBytesCount {       // Take the last 8 bits of count.       let lengthByte = UInt8(count & 0xff)       // Add them to the length field.       lengthField.insert(lengthByte, at: 0)       // Delete the last 8 bits of count.       count = count >> 8     }     // Include the first byte.     lengthField.insert(firstLengthFieldByte, at: 0)     return lengthField   } extension StringProtocol {   var hexaData: Data { .init(hexa) }   var hexaBytes: [UInt8] { .init(hexa) }   private var hexa: UnfoldSequence<UInt8, Index> {     sequence(state: startIndex) { startIndex in       guard startIndex < self.endIndex else { return nil }       let endIndex = self.index(startIndex, offsetBy: 2, limitedBy: self.endIndex) ?? self.endIndex       defer { startIndex = endIndex }       return UInt8(self[startIndex..<endIndex], radix: 16)     }   } }
Posted Last updated
.
Post not yet marked as solved
0 Replies
1.2k 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 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 not yet marked as solved
4 Replies
481 Views
Hi! With CryptoKit functions i can instantiate certificate keys, but with usage of Security module the code fails. I cannot figure out what is the issue. Anyone have any idea what needs to be changed? Thanks!!!, Garfield This is the code that causes issue: import Security import CryptoKit // base64 encoded let privateKeyString = "deXnwQoRHddejAMvHsucXdPkE0B5hAIap1VE69ASplo=" let publicKeyString = "p4Rqbh+nmv/FslbJFGOe7JzSP6/ySaTkgW6h5t/+fqC/E8M9SVmamBKdTusddEecWY5KBGZo4x2oeNYyM7EtPA==" let attributesPrivate: [NSObject : NSObject] = [         kSecAttrKeyType: kSecAttrKeyTypeECSECPrimeRandom,         kSecAttrKeyClass: kSecAttrKeyClassPrivate  ]           let attributesPublic: [NSObject : NSObject] = [         kSecAttrKeyType: kSecAttrKeyTypeECSECPrimeRandom,         kSecAttrKeyClass: kSecAttrKeyClassPublic  ]        var errorPrivate: Unmanaged&lt;CFError&gt;?  var errorPublic: Unmanaged&lt;CFError&gt;?  var error: Unmanaged&lt;CFError&gt;?   if #available(iOS 13.0, *) {       let publicKeyX = try! P256.Signing.PublicKey(rawRepresentation: Data(base64Encoded: publicKeyString)!.suffix(65))       //https://developer.apple.com/forums/thread/680554       print(publicKeyX, "P256 PUBLIC")       let privateKeyX = try! P256.Signing.PrivateKey(rawRepresentation: Data(base64Encoded: privateKeyString)!.suffix(65))       print(privateKeyX, "P256 PRIVATE")             } else {       // Fallback on earlier versions     }                 let publicKey = SecKeyCreateWithData(Data(base64Encoded: publicKeyString)! as NSData, attributesPublic as NSDictionary, &amp;errorPublic)!           let privateKey = SecKeyCreateWithData(Data(base64Encoded: privateKeyString)! as NSData, attributesPrivate as NSDictionary, &amp;errorPrivate)!
Posted Last updated
.
Post not yet marked as solved
0 Replies
1.6k Views
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
Posted Last updated
.
Post not yet marked as solved
1 Replies
533 Views
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 }
Posted
by FerIves.
Last updated
.
Post marked as solved
5 Replies
1.4k Views
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_***_Update in OpenSSL. Thank you.
Posted
by HenryL.
Last updated
.
Post not yet marked as solved
3 Replies
760 Views
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
Posted
by OJDee.
Last updated
.
Post not yet marked as solved
5 Replies
965 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 not yet marked as solved
1 Replies
630 Views
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);
Posted
by TusharBOB.
Last updated
.