From de54f85b0f1aa9ab5930912feac829c8392c941c Mon Sep 17 00:00:00 2001 From: Justus Winter Date: Sat, 16 Mar 2024 18:59:52 +0100 Subject: openpgp: Avoid heap allocation when hashing keys. - Notably, this is done during certificate canonicalization. This is expensive as-is, let's keep the allocator out of it. --- openpgp/src/crypto/hash.rs | 33 +++++++++++++++++---------------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/openpgp/src/crypto/hash.rs b/openpgp/src/crypto/hash.rs index 79a31f8a..c3742664 100644 --- a/openpgp/src/crypto/hash.rs +++ b/openpgp/src/crypto/hash.rs @@ -381,27 +381,28 @@ impl Hash for Key4 // include the tag (1 byte) or the length (2 bytes). let len = (9 - 3) + self.mpis().serialized_len() as u16; - let mut header: Vec = Vec::with_capacity(9); + let mut header = [ + // Tag. Note: we use this whether + 0x99u8, - // Tag. Note: we use this whether - header.push(0x99); + // Length (2 bytes, big endian). Fixup later. + 0, 0, - // Length (2 bytes, big endian). - header.extend_from_slice(&len.to_be_bytes()); + // Version. + 4, - // Version. - header.push(4); - - // Creation time. - let creation_time: u32 = - Timestamp::try_from(self.creation_time()) - .unwrap_or_else(|_| Timestamp::from(0)) - .into(); - header.extend_from_slice(&creation_time.to_be_bytes()); + // Creation time. Fixup later. + 0, 0, 0, 0, - // Algorithm. - header.push(self.pk_algo().into()); + // Algorithm. + self.pk_algo().into(), + ]; + // Fixup length and creation time and hash the header. + header[1..3].copy_from_slice(&len.to_be_bytes()); + header[4..8].copy_from_slice(&u32::from( + Timestamp::try_from(self.creation_time()) + .unwrap_or_else(|_| Timestamp::from(0))).to_be_bytes()); hash.update(&header[..]); // MPIs. -- cgit v1.2.3