Last active
May 27, 2025 13:51
-
-
Save manicmachine/8197cfca162cf8147b3fb8aee6a1e044 to your computer and use it in GitHub Desktop.
ChaChaPoly encryption in Swift with CryptoKit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import CryptoKit | |
extension SymmetricKey { | |
init?(base64EncodedString: String) { | |
guard let data = Data(base64Encoded: base64EncodedString) else { | |
return nil | |
} | |
self.init(data: data) | |
} | |
func serialize() -> String { | |
return self.withUnsafeBytes { body in | |
Data(body).base64EncodedString() | |
} | |
} | |
} | |
var encKey: String? = nil // Change this if you have an existing key you want to use. | |
var valuesToBeEncrypted = [String: String]() // Leave this alone. | |
// Append values to be encrypted here. | |
valuesToBeEncrypted["value1"] = "secret1" | |
valuesToBeEncrypted["value2"] = "secret2" | |
valuesToBeEncrypted["value3"] = "secret3" | |
// Don't touch | |
let symKey = if encKey == nil { SymmetricKey(size: .bits256) } else { SymmetricKey(base64EncodedString: encKey!)! } | |
var encValues = [String: String]() | |
print("Key: \(symKey.serialize())") | |
for (key, value) in valuesToBeEncrypted { | |
let encryptedValue = try! ChaChaPoly.seal(value.data(using: .utf8)!, using: symKey).combined | |
encValues[key] = encryptedValue.base64EncodedString() | |
print("Encrypted \(key) (\(value)): \(encryptedValue.base64EncodedString())") | |
} | |
// Example of how to decode these values | |
print("-- VALIDATION --") | |
for (key, value) in encValues { | |
guard let data = Data(base64Encoded: value) else { | |
print("Failed to initialize data for \(key)") | |
continue | |
} | |
if let sealedBox = try? ChaChaPoly.SealedBox(combined: data) { | |
if let decryptedData = try? ChaChaPoly.open(sealedBox, using: symKey) { | |
print("Decrypted \(key) (\(value)): \(String(data: decryptedData, encoding: .utf8)!)") | |
} else { | |
print("Failed to decrypt value for \(key)") | |
continue | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment