Home > Software engineering >  CryptoKit/Can not initialize SymmetricKey using SymmetricKey(data:)?
CryptoKit/Can not initialize SymmetricKey using SymmetricKey(data:)?

Time:05-23

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)")
    }
}

CodePudding user response:

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)")
        }
    }
  • Related