Skip to content

Commit

Permalink
Fix read/write DER length
Browse files Browse the repository at this point in the history
  • Loading branch information
kellerkindt committed Jan 20, 2024
1 parent df953d4 commit 485ccab
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 7 deletions.
13 changes: 7 additions & 6 deletions src/protocol/basic/distinguished/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,9 @@ const CLASS_BITS_APPLICATION: u8 = 0b_01_000000;
const CLASS_BITS_CONTEXT_SPECIFIC: u8 = 0b_10_000000;
const CLASS_BITS_PRIVATE: u8 = 0b_11_000000;

const LENGTH_MASK: u8 = 0b_11_000000;
const LENGTH_SHORT_FORM: u8 = 0b_01_000000;
const LENGTH_SHORT_MAX_VALUE: usize = 127;
const LENGTH_BIT_MASK: u8 = 0b1_0000000;
const LENGTH_BIT_SHORT_FORM: u8 = 0b0_0000000;

impl<T: Read> BasicRead for T {
type Flavor = DistinguishedEncodingRules;
Expand All @@ -53,8 +54,8 @@ impl<T: Read> BasicRead for T {
fn read_length(&mut self) -> Result<usize, Error> {
let mut bytes = [0u8; 1];
self.read_exact(&mut bytes[..])?;
if bytes[0] & LENGTH_MASK == LENGTH_SHORT_FORM {
Ok(usize::from(bytes[0] & !LENGTH_MASK))
if bytes[0] & LENGTH_BIT_MASK == LENGTH_BIT_SHORT_FORM {
Ok(usize::from(bytes[0] & !LENGTH_BIT_MASK))
} else {
todo!()
}
Expand Down Expand Up @@ -86,9 +87,9 @@ impl<T: Write> BasicWrite for T {

#[inline]
fn write_length(&mut self, length: usize) -> Result<(), Error> {
let byte = if length < 64 {
let byte = if length <= LENGTH_SHORT_MAX_VALUE {
// short form 8.1.3.4
LENGTH_SHORT_FORM | (length as u8)
LENGTH_BIT_SHORT_FORM | (length as u8)
} else {
// long form 8.1.3.5
todo!()
Expand Down
29 changes: 28 additions & 1 deletion tests/der_basic_boolean.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ pub fn test_der_basic_boolean() {
Boolean::<NoConstraint>::write_value(&mut writer, &bool_value).unwrap();

assert_eq!(
&[0x01, 0x41, if bool_value { 0x01 } else { 0x00 }],
&[0x01, 0x01, if bool_value { 0x01 } else { 0x00 }],
&buffer[..]
);

Expand All @@ -21,3 +21,30 @@ pub fn test_der_basic_boolean() {
assert_eq!(bool_value, result)
}
}

#[test]
pub fn test_der_basic_boolean_false_from_0x00() {
let mut reader = DER::reader(&[0x01, 0x01, 0xFF][..]);
let result = Boolean::<NoConstraint>::read_value(&mut reader).unwrap();

assert_eq!(true, result)
}

#[test]
pub fn test_der_basic_boolean_true_from_0xff() {
let mut reader = DER::reader(&[0x01, 0x01, 0xFF][..]);
let result = Boolean::<NoConstraint>::read_value(&mut reader).unwrap();

assert_eq!(true, result)
}

#[test]
pub fn test_der_basic_boolean_true_from_any_greater_zero() {
for value in 1..=u8::MAX {
let values = [0x01, 0x01, value];
let mut reader = DER::reader(&values[..]);
let result = Boolean::<NoConstraint>::read_value(&mut reader).unwrap();

assert_eq!(true, result)
}
}

0 comments on commit 485ccab

Please sign in to comment.