I have an error CryptoKit.CryptoKitError.authenticationFailure when the second user trying decrypt message. For the 1-st - works perfect! Cloud you check, what I missed?
Here the code:
func encryptMessage(chatId: String, text: String, completion: @escaping (String?, Error?)->()) {
do {
guard let keysModel = DatabaseManager.instance.getKeys(uuid: chatId) else { return }
let privateKey = try DatabaseManager.instance.importPrivateKey(keysModel.myPrivateKey)
let publickKey = try DatabaseManager.instance.importPublicKey(keysModel.publicUserKey ?? "")
let symmetricKey = try prepareKeysPair(privateKey: privateKey, publicKey: publickKey)
guard let textData = text.data(using: .utf8) else {
completion(nil, nil)
return }
let encrypted = try ChaChaPoly.seal(textData, using: symmetricKey)
let message = encrypted.combined.base64EncodedString()
completion(message, nil)
} catch {
completion(nil, error)
}
}
func decryptMessage(chatId: String, text: String, completion: @escaping (String?, Error?)->()) {
do {
guard let keysModel = DatabaseManager.instance.getKeys(uuid: chatId) else { return }
let privateKey = try DatabaseManager.instance.importPrivateKey(keysModel.myPrivateKey)
let publickKey = try DatabaseManager.instance.importPublicKey(keysModel.publicUserKey ?? "")
let symmetricKey = try prepareKeysPair(privateKey: privateKey, publicKey: publickKey)
guard let data = Data(base64Encoded: text) else {
completion(nil, nil)
return
}
let sealedBox = try ChaChaPoly.SealedBox(combined: data)
let decryptedData = try ChaChaPoly.open(sealedBox, using: symmetricKey)
let rSensitiveMessage = String(data: decryptedData, encoding: .utf8)!
completion(rSensitiveMessage, nil)
} catch {
completion(nil, error)
}
}
func prepareKeysPair(privateKey: P256.KeyAgreement.PrivateKey, publicKey: P256.KeyAgreement.PublicKey) throws -> SymmetricKey {
let iv = "31348c0987c7".data(using: .utf8)
let sharedSecret = try privateKey.sharedSecretFromKeyAgreement(with: publicKey)
let symmetricKey = sharedSecret.hkdfDerivedSymmetricKey(
using: SHA256.self,
salt: iv ?? Data(),
sharedInfo: Data(),
outputByteCount: 32
)
return symmetricKey
}