Given the decryption below which is using the older API of SecKeyCreateDecryptedData. (This has been proved end-to-end with backend that it works with their implementation of encryption.) I was checking this article during implementing the decryption back then.

let appEphPrivSecKey: SecKey = ...
let serverEphPubKeyData: Data = ...
let encryptedDataFromServer: Data = ...

var fullEncryptedData = serverEphPubKeyData
fullEncryptedData.append(contentsOf: encryptedDataFromServer) // so that we have the required format of ephemeral public key + ciphertext + tag
 
var unmanagedError: Unmanaged<CFError>?
let decryptedData = SecKeyCreateDecryptedData(
     appEphPrivSecKey,
     .eciesEncryptionCofactorVariableIVX963SHA256AESGCM,
     fullEncryptedData as CFData,
     &unmanagedError)

How can I implement the encryption part, but using the newer CryptoKit library provided by Apple?


I tried almost each and every combination, but never managed to make it work (neither with backend nor with my old decryption). This is one example of my tests:

let appEphPrivSecKey: SecKey = ...
let serverEphPubKeyData: Data = ...

let appEphemeralPrivKeyData = SecKeyCopyExternalRepresentation(appEphPrivSecKey, nil)! as Data
let appEphemeralPrivKey = try P256.KeyAgreement.PrivateKey(x963Representation: appEphemeralPrivKeyData)
        
let serverEphemeralPublicKey = try P256.KeyAgreement.PublicKey(x963Representation: serverEphPubKeyData)
        
let sharedSecret = try appEphemeralPrivKey.sharedSecretFromKeyAgreement(with: serverEphemeralPublicKey)
        
let derivedSymmetricKey = sharedSecret.x963DerivedSymmetricKey(
     using: SHA256.self,
     sharedInfo: appEphemeralPrivKey.publicKey.x963Representation,
     outputByteCount: 16)
        
let sealedBox = try AES.GCM.seal(sensitiveData, using: derivedSymmetricKey)
        
let encryptedData = sealedBox.ciphertext + sealedBox.tag

But this does not work, I always receive the error below: The operation couldn’t be completed. (OSStatus error -50 - ECIES: Failed to aes-gcm decrypt data (err -69))

0

There are 0 best solutions below