2020-11-06 09:32:09 +01:00
|
|
|
import CryptoSwift
|
2020-11-09 00:58:47 +01:00
|
|
|
import SessionUtilitiesKit
|
2020-12-10 06:12:22 +01:00
|
|
|
import Sodium
|
2020-11-06 09:32:09 +01:00
|
|
|
|
2021-01-04 05:30:13 +01:00
|
|
|
extension MessageReceiver {
|
2020-11-06 09:32:09 +01:00
|
|
|
|
2021-01-04 05:30:13 +01:00
|
|
|
internal static func decryptWithSessionProtocol(ciphertext: Data, using x25519KeyPair: ECKeyPair) throws -> (plaintext: Data, senderX25519PublicKey: String) {
|
|
|
|
let recipientX25519PrivateKey = x25519KeyPair.privateKey
|
|
|
|
let recipientX25519PublicKey = Data(hex: x25519KeyPair.hexEncodedPublicKey.removing05PrefixIfNeeded())
|
2020-12-10 06:12:22 +01:00
|
|
|
let sodium = Sodium()
|
|
|
|
let signatureSize = sodium.sign.Bytes
|
|
|
|
let ed25519PublicKeySize = sodium.sign.PublicKeyBytes
|
|
|
|
|
|
|
|
// 1. ) Decrypt the message
|
|
|
|
guard let plaintextWithMetadata = sodium.box.open(anonymousCipherText: Bytes(ciphertext), recipientPublicKey: Box.PublicKey(Bytes(recipientX25519PublicKey)),
|
|
|
|
recipientSecretKey: Bytes(recipientX25519PrivateKey)), plaintextWithMetadata.count > (signatureSize + ed25519PublicKeySize) else { throw Error.decryptionFailed }
|
|
|
|
// 2. ) Get the message parts
|
|
|
|
let signature = Bytes(plaintextWithMetadata[plaintextWithMetadata.count - signatureSize ..< plaintextWithMetadata.count])
|
|
|
|
let senderED25519PublicKey = Bytes(plaintextWithMetadata[plaintextWithMetadata.count - (signatureSize + ed25519PublicKeySize) ..< plaintextWithMetadata.count - signatureSize])
|
|
|
|
let plaintext = Bytes(plaintextWithMetadata[0..<plaintextWithMetadata.count - (signatureSize + ed25519PublicKeySize)])
|
|
|
|
// 3. ) Verify the signature
|
2020-12-16 01:45:01 +01:00
|
|
|
let verificationData = plaintext + senderED25519PublicKey + recipientX25519PublicKey
|
|
|
|
let isValid = sodium.sign.verify(message: verificationData, publicKey: senderED25519PublicKey, signature: signature)
|
2020-12-10 06:12:22 +01:00
|
|
|
guard isValid else { throw Error.invalidSignature }
|
|
|
|
// 4. ) Get the sender's X25519 public key
|
|
|
|
guard let senderX25519PublicKey = sodium.sign.toX25519(ed25519PublicKey: senderED25519PublicKey) else { throw Error.decryptionFailed }
|
|
|
|
|
|
|
|
return (Data(plaintext), "05" + senderX25519PublicKey.toHexString())
|
|
|
|
}
|
2020-11-06 09:32:09 +01:00
|
|
|
}
|