Table of contents
Open Table of contents
Project Details
Today I’m open sourcing an implementation of the XChaCha20-Poly1305 AEAD algorithm that is 100% compliant with the RFCs RFC 8439 and RFC draft-irtf-cfrg-xchacha-03.
You can find the code on GitHub at pmuens/xchacha20-poly1305.
During the implementation I focused on code readability so you should be able to read the respective RFC and compare it to the code equivalent without any issues (if not, please let me know).
The code is tested against all the RFC test vectors, the implementations of which you can find the the respective _test.go
files.
I also took great care in splitting up the different algorithms into separate self-contained units. This makes it possible to e.g. use ChaCha20 without Poly1305.
Note that I wrote the implementation for educational purposes only. You could in theory use it to encrypt and authenticate your data packets, but you probably should’t as the code isn’t optimized or audited.
Algorithms
ChaCha20-Poly1305 and its extension XChaCha20-Poly1305 uses the following algorithms under the hood.
ChaCha20
The ChaCha20 stream cipher that allows for encryption and decryption of arbitrary messages.
You can find the implementation here.
XChaCha20
The XChaCha20 stream cipher which extends ChaCha20 so 192-bit nonces can be used. Extending ChaCha20 this way makes it possible to randomly sample a nonce which removes the need to track nonce usage (i.e. it allows for a stateless system).
XChaCha20 relies on HChaCha20 which converts the key and part of the nonce into a subkey. Both implementations can be fond here.
Poly1305
The Poly1305 message authentication code (MAC). A MAC is used to ensure that a message originated from the correct sender and wasn’t tampered with in transit (i.e. it ensures the integrity and authenticity of a message).
The Poly1305 implementation can be found here.
ChaCha20-Poly1305
ChaCha20-Poly1305 combines ChaCha20 and Poly1305 to allow for authenticated encryptions with associated data (AEAD).
Using it one can encrypt and authenticate a message and any arbitrary, additional data in one go.
The full implementation can be found here.
XChaCha20-Poly1305
XChaCha20-Poly1305 is an extension of ChaCha20-Poly1305 which combines XChaCha20 and Poly1305 to allow for AEAD’s with 192-bit nonces.
You can find the full implementation here.
Usage
You can use the Go documentation to learn how the different components can be used in isolation or together.
Other than that I’d encourage you to take a look at the various _test.go
files which can be understood as a second form of documentation.
While it was challenging at times, I really had a blast implementing a fully RFC compliant version of ChaCha20-Poly1305 and XChaCha20-Poly1305.
In my opinion implementing algorithms is the best way to learn. I hope that by sharing the codebase you’ll learn something new too! Feel free to drop me a message if you have any questions or feedback.