computeNonce function
Calculates the QUIC AEAD nonce. Nonce is computed as IV XOR (big-endian 64-bit Packet Number). The IV is 12 bytes. The 64-bit Packet Number is left-padded with zeros and XORed with the rightmost 8 bytes of the IV.
Implementation
Uint8List computeNonce(Uint8List iv, int packetNumber) {
if (iv.length != 12) {
throw ArgumentError("IV must be 12 bytes for QUIC AEAD.");
}
// Create a mutable copy of the IV
final nonce = Uint8List.fromList(iv);
// Create an 8-byte buffer for the packet number (64-bit, big-endian)
final pnBuffer = Uint8List(8);
// Use ByteData to safely write the 64-bit integer in Big Endian format.
final byteData = ByteData(8);
byteData.setUint64(0, packetNumber, Endian.big);
// Copy to pnBuffer
pnBuffer.setAll(0, byteData.buffer.asUint8List());
// XOR the rightmost 8 bytes of the IV (indices 4-11) with the 8 bytes of pnBuffer.
// The first 4 bytes of the 12-byte IV remain untouched.
for (var i = 0; i < 8; i++) {
// pnBuffer[i] is byte 0 to 7 of the 64-bit packet number
// nonce[i + 4] is byte 4 to 11 of the 12-byte IV/Nonce
nonce[i + 4] ^= pnBuffer[i];
}
return nonce;
}