-
Notifications
You must be signed in to change notification settings - Fork 0
Message Encryption
Messages are end-to-end encrypted with AESGCM and a shared key derived using Diffie-Hellman.
The Diffie-Hellman key exchange protocol is used to exchange public keys of the sender and the recipient of a message. Diffie-Hellman was chosen because it is simple and asymmetric. Asymmetric cryptography is useful in this case, as it allows a user to send a message to another without having had prior contact
When a user attempts to send a message to another user, private and public key pairs are generated for both users. The keys are generated using the same static parameters, where p is a 512-byte prime number, and g is a primitive root modulo p.
New key pairs are generated for each message being sent to ensure perfect forward secrecy, meaning that even if the most recent key is exposed, one can be assured that previous messages cannot be decrypted using the same key.
Once the sender generates their key pair, their public key is serialized into a PEM key, decoded into a UTF-8 string, and sent to the recipient. The recipient then does the same, and their serialized public key is sent to the original sender. Both the sender and the recipient have now exchanged public keys.
Once the sender has received the public key from the recipient, they can generate a shared key using their own private key along with the recipient's public key. The shared key is derived using HKDF (HMAC-based Extract-and-Expand Key Derivation Function), with the hash function SHA-256.
The message is then encrypted using the shared key with AESGCM, which provides message encryption alongside message confidentiality and integrity. A single use 16-byte nonce is used for each message and is appended to the encrypted message.
Messeges are encrypted using a shared key known to both the sender and the recipient, so either user can plausibly deny having sent any particular message between them. Only the sender and recipient know the shared key, providing end-to-end encryption.
Once the recipient has received the encrypted message, the recipient can generate a shared key using their own private key along with the sender's public key. The shared key is derived using HKDF, with the hash function being SHA-256.
The encrypted message is then decrypted using the shared key with AESGCM. The nonce is extracted from the key, and the cipher can then be decrypted to the original message.
If the message was somehow tampered with, an error will be returned saying that the message was not authenticated, providing message integrity assurance.