3

When trying to encrypt a block of plain data using SecKeyCreateEncryptedData, it encrypts the plain data using the specified algorithm and it works fine.The code snippet which i used for encryption is

SecKeyCreateEncryptedData(publicKey.underlying,SecKeyAlgorithm.eciesEncryptionSt
    andardX963SHA1AESGCM,cdata!, &error)

But when i am trying to do the same encryption using SecKeyEncrypt, it fails with a return value of (-50).The code snippet used for my encryption is

SecKeyEncrypt(publicKey.underlying as SecKey, .PKCS1, digestBytes, 
    newdata.length, &signatureBytes, &signatureLength)

And I am also unable to get the error description for the error code -50.

mahler
  • 526
  • 5
  • 25
vineeth
  • 41
  • 1
  • 6

1 Answers1

1

Here's a general difference between these two functions, not only limited to Swift.

SecKeyCreateEncryptedData function is intended for replacing the usage of SecKeyEncrypt since it is only available for iOS 10+, and Apple official guide is using that. Although both function takes SecKey as a parameter, the way to get the instance is also different.

If you publicKey is working fine for SecKeyCreateEncryptedData, chances are that the same publicKey won't work for SecKeyEncrypt function.

To correctly generate the SecKey for SecKeyEncrypt function, you need to

  1. Get the SecCertificate by using SecCertificateCreateWithData. Note that the certificate should be in .der format.
  2. Create and evaluate a SecTrust based on the SecCertificate you just created.
  3. Get the SecKey from the SecTrust

You can find more details here How can I get SecKeyRef from DER/PEM file.

PowerQian
  • 336
  • 4
  • 10