Skip to content

Commit ad30da5

Browse files
ctzdjc
authored andcommitted
Fix regression in key usage purpose encoding
1 parent b2d5990 commit ad30da5

File tree

1 file changed

+13
-4
lines changed

1 file changed

+13
-4
lines changed

rcgen/src/certificate.rs

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -214,9 +214,6 @@ impl CertificateParams {
214214

215215
/// Write a certificate's KeyUsage as defined in RFC 5280.
216216
fn write_key_usage(&self, writer: DERWriter) {
217-
// RFC 5280 defines 9 key usages, which we detail in our key usage enum
218-
// We could use std::mem::variant_count here, but it's experimental
219-
const KEY_USAGE_BITS: usize = 9;
220217
if self.key_usages.is_empty() {
221218
return;
222219
}
@@ -227,7 +224,16 @@ impl CertificateParams {
227224
let bit_string = self.key_usages.iter().fold(0u16, |bit_string, key_usage| {
228225
bit_string | key_usage.to_u16()
229226
});
230-
writer.write_bitvec_bytes(&bit_string.to_be_bytes(), KEY_USAGE_BITS);
227+
228+
match u16::BITS - bit_string.trailing_zeros() {
229+
bits @ 0..=8 => {
230+
writer.write_bitvec_bytes(&bit_string.to_be_bytes()[..1], bits as usize)
231+
},
232+
bits @ 9..=16 => {
233+
writer.write_bitvec_bytes(&bit_string.to_be_bytes(), bits as usize)
234+
},
235+
_ => unreachable!(),
236+
}
231237
});
232238
}
233239

@@ -1146,6 +1152,9 @@ mod tests {
11461152

11471153
for ext in cert.extensions() {
11481154
if key_usage_oid_str == ext.oid.to_id_string() {
1155+
// should have the minimal number of octets, and no extra trailing zero bytes
1156+
// ref. https://github.com/rustls/rcgen/issues/368
1157+
assert_eq!(ext.value, vec![0x03, 0x02, 0x05, 0xe0]);
11491158
if let x509_parser::extensions::ParsedExtension::KeyUsage(usage) =
11501159
ext.parsed_extension()
11511160
{

0 commit comments

Comments
 (0)