CryptoKit/Can 不使用 SymmetricKey(data:) 初始化 SymmetricKey?
CryptoKit/Can not initialize SymmetricKey using SymmetricKey(data:)?
我正在尝试从自定义字符串创建 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)")
}
}
我正在尝试从自定义字符串创建 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)")
}
}