swiftxcodesharesymmetric-key

Xcode 11 Swift 5 CryptoKit share SymmetricKey


I'm starting to learn de-/encrypting with the CryptoKit. Everything works fine, but I can not share my generated SymmetricKey.

Example:

let key = SymmetricKey(size: .bits256)

Well, I generate a symmetric key. Now I want to share the key, but how I can do that? Inside the debugger the variable key is empty? I check the encryption and decryption - works well - output shows the encrypted and decrypted data. How can I save my variable key for distribution?

I found a solution:

let savedKey = key.withUnsafeBytes {Data(Array($0)).base64EncodedString()}

This works great, but how can I save the variable savedKey (String) back into the variable key (SymmetricKey)?


Solution

  • You can do that by converting key string to Data and retrieve the key from it

    let key = SymmetricKey(size: .bits256)
    let savedKey = key.withUnsafeBytes {Data(Array($0)).base64EncodedString()}
    
    if let keyData = Data(base64Encoded: savedKey) {
        let retrievedKey = SymmetricKey(data: keyData)
    }
    

    Hope this helps :)