我试图从自定义字符串创建symmetricKey
。当我使用SymmetricKey(size:)
时,我的代码工作得很好,但是我想从自定义字符串创建symmetricKey
,所以我使用SymmetricKey(data:)
。我不知道我的代码出了什么问题。
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)")
}
}
我自己回答了这个问题,这里的答案可能有人需要。
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)")
}
}