Generate a symmetric key on iOS using Security.framework

1.7k views Asked by At

I'm struggling to generate a symmetric key in iOS using the security framework. There is a method SecKeyGenerateSymmetric() in SecKey.h but its for macOS only. The only thing I see available is SecKeyGeneratePair() which is for asymmetric encryption.

Also from reading this documentation it looks the only way to do symmetric encryption is by generating an asymmetric key pair and calling SecKeyCreateEncryptedData() with the public key and behind the scenes a symmetric key is generated but you don't have access to it. I need to have access to the symmetric key.

If anyone has experience doing symmetric encryption on iOS I would be grateful of some guidance.

1

There are 1 answers

0
BlackPearl12 On

With CryptoKit's introduction this can be done using the following code:

 import CryptoKit

 //generate Symmetric  key
 let key = SymmetricKey(size: .bits256)
    
  

Here is an example using AES-GCM method for encrypting and decrypting using the 32 byte symmetric key:

//generate Symmetric  key
 let key = SymmetricKey(size: .bits256)

  //encrypt plaintext
   let encryptedData = try!  AES.GCM.seal("plain-text".data(using: .utf8)!, using: key)
    print("Encrypted data using symmetric key:\(encryptedData)")
    
    //decrypt data
    let sealedBoxRestored = try! AES.GCM.SealedBox(nonce: encryptedData.nonce, ciphertext: encryptedData.ciphertext, tag: encryptedData.tag)
    let decryptedData = try! AES.GCM.open(sealedBoxRestored, using: key)
    print("Decrypted:\n\(String(data: decryptedData, encoding: .utf8)!)")