0

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)")
    }
}
Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220
James H
  • 14
  • 3

1 Answers1

-1

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)")
        }
    }
James H
  • 14
  • 3
  • 1
    You need to separate ”code runs” from ”secure solution”, this is the first but not the latter. When encrypting data the encryption key needs to be cryptographically secure. If it originates from a password you should use PBKDF2 and run the password through it, at the very least use HKDF with relevant inputs. CommonCrypto and CryptoSwift has PBKDF2. Scrypt is also a secure KDF, but unsure if part of CryptoSwift (too lazy to check now). – Sajjon May 21 '22 at 15:23
  • This code is only for testing purposes to see if it could run properly. My goal is to create a `symetricKey` from random words to store the encrypted token locally, not send it anywhere. I've tried to use HKDF to derive `symmetricKey`. But for an unknown reason, I can not use `AES.GCM` or `ChaChaPoly` to encrypt data with that `symmetricKey`. Only `symmetricKey` initialized using SymmetricKey(data:) with data is the digest of SHA256 can use to encrypt data. Do you have any solution for me? – James H May 23 '22 at 06:09