CryptoKit/Can not initialize SymmetricKey using SymmetricKey(data:)?

799 views Asked by At

I'm trying to create a symmetricKey from a custom string. My code worked well when I used SymmetricKey(size:), but I want to create symmetricKey from a custom string, so I used SymmetricKey(data:). I don't know what's wrong with my code.

func encryptAccessToken(with accessToken: String) {
    guard #available(iOS 13.0, *) else  { return }
    guard  let keyData = "myStringKey".data(using: .utf8), let data = accessToken.data(using: .utf8) else { return }
    let symmetricKey = SymmetricKey(data: keyData)
    do {
        let encryptedData = try AES.GCM.seal(data, using: symmetricKey).combined
        UserDefaults.standard.set(encryptedData, forKey: secretKey)
    } catch {
        print("\(error.localizedDescription)")
    }
}
1

There are 1 answers

2
James H On BEST ANSWER

I answered it myself, here's the answer for someone may need this.

func encryptAccessToken(with accessToken: String) {
        guard #available(iOS 13.0, *) else  { return }
        guard let data = accessToken.data(using: .utf8) else { return }
        let myString = "myString"
        let keyData = SHA256.hash(data: myString.data(using: .utf8)!)
        let symmetricKey = SymmetricKey(data: keyData)
        do {
            let encryptedData = try AES.GCM.seal(data, using: symmetricKey).combined
            UserDefaults.standard.set(encryptedData, forKey: secretKey)
        } catch {
            print("\(error.localizedDescription)")
        }
    }