Skip to content

Commit

Permalink
Correctly pad bytes with zero in hex conversion
Browse files Browse the repository at this point in the history
When reading a secret in ascii or base32 format from the user, we
perform a conversion of the potentially decoded string into hexadecimal
bytes, because that is what libnitrokey expects.
The format string we used in the conversion, however, did not account
for padding with a leading zero for single digit results. E.g., the
newline/line feed symbol '\n', which has a decimal value of 10 would
result in the string 'a' being produced, whereas '0a' would be the
correct result.
This change corrects the format string to fix this problem.
  • Loading branch information
d-e-s-o committed Oct 13, 2019
1 parent e09f5d8 commit c46803a
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
1 change: 1 addition & 0 deletions nitrocli/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ Unreleased
- Removed `storage status` subcommand
- Moved its output into `status` command
- Removed previously deprecated `--ascii` option from `otp set` command
- Fixed wrong hexadecimal conversion used in `otp set` command
- Bumped `libc` dependency to `0.2.62`
- Bumped `cc` dependency to `1.0.40`

Expand Down
9 changes: 8 additions & 1 deletion nitrocli/src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -616,7 +616,7 @@ pub fn otp_get(
fn format_bytes(bytes: &[u8]) -> String {
bytes
.iter()
.map(|c| format!("{:x}", c))
.map(|c| format!("{:02x}", c))
.collect::<Vec<_>>()
.join("")
}
Expand Down Expand Up @@ -956,4 +956,11 @@ mod tests {
let result = prepare_ascii_secret("Österreich");
assert!(result.is_err());
}

#[test]
fn hex_string() {
assert_eq!(format_bytes(&[b' ']), "20");
assert_eq!(format_bytes(&[b' ', b' ']), "2020");
assert_eq!(format_bytes(&[b'\n', b'\n']), "0a0a");
}
}

0 comments on commit c46803a

Please sign in to comment.