Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 414
P. S. Avatar asked Dec 17 '22 14:12

P. S.


1 Answers

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

like image 53
Umair M Avatar answered Jan 06 '23 09:01

Umair M