如何存储加密数据

How can i store encrypted data

我正在尝试在 UserDefaults 中存储和检索我的加密文本数据,但检索它时出现问题。我使用 CryptoKit 来加密和解密数据。

错误信息是:"Could not cast value of type 'Foundation.__NSSwiftData' (0x7fff89d1ee50) to 'CryptoKit.ChaChaPoly.SealedBox' (0x7fff8085abc8)."

有没有更好的方法可以将 SymmetricKey 存储在钥匙串中,而无需通过 UnsafeBytes 将其转换为字符串?我使用 SwiftKeychainWrapper。

func encrypt(text: String) {
    let key = SymmetricKey(size: .bits256)
    let message = text.data(using: .utf8)!
    let sealedBox = try! ChaChaPoly.seal(message, using: key)

    let defaults = UserDefaults.standard
    defaults.set(sealedBox.combined, forKey: "sealedBox")

    let savedKey = key.withUnsafeBytes {Data(Array([=10=])).base64EncodedString()}
    Services.saveKey(key: savedKey)
}

func decrypt() {
    let savedKey = Services.getKey()

    if let keyData = Data(base64Encoded: savedKey) {
        let retrievedKey = SymmetricKey(data: keyData)

        let defaults = UserDefaults.standard
        let sealedBox = (defaults.object(forKey: "sealedBox") as? ChaChaPoly.SealedBox)!

        let decryptedMessage = try! ChaChaPoly.open(sealedBox, using: retrievedKey)
        textView.text = String(data: decryptedMessage, encoding: .utf8)!
    }
}

您正在将 Data 存储在 UserDefaults 中,因此您必须再次提取它。然后从中创建一个 SealedBox,像这样:

let defaults = UserDefaults.standard
let data = defaults.object(forKey: "sealedBox") as? Data

let sealedBox = try! ChaChaPoly.SealedBox(combined: data!)
let decryptedMessage = try! ChaChaPoly.open(sealedBox, using: retrievedKey)

(当然你会想避免在实际生产代码中强制解包)