Xcode 11 Swift 5 CryptoKit share SymmetricKey
Asked Answered
S

1

10

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)?

Sutlej answered 3/3, 2020 at 9:34 Comment(0)
A
20

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 :)

Amphibolous answered 9/3, 2020 at 12:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.