Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move hex functions out of test mod #293

Merged
merged 1 commit into from
Dec 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions aws-lc-rs/src/agreement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ use crate::error::Unspecified;
use crate::fips::indicator_check;
use crate::ptr::LcPtr;
use crate::rand::SecureRandom;
use crate::{ec, test};
use crate::{ec, hex};
use aws_lc::{
EVP_PKEY_CTX_new, EVP_PKEY_CTX_new_id, EVP_PKEY_derive, EVP_PKEY_derive_init,
EVP_PKEY_derive_set_peer, EVP_PKEY_get_raw_public_key, EVP_PKEY_keygen, EVP_PKEY_keygen_init,
Expand Down Expand Up @@ -420,7 +420,7 @@ impl Debug for PublicKey {
f.write_str(&format!(
"PublicKey {{ algorithm: {:?}, bytes: \"{}\" }}",
self.alg,
test::to_hex(&self.public_key[0..self.len])
hex::encode(&self.public_key[0..self.len])
))
}
}
Expand Down Expand Up @@ -455,7 +455,7 @@ impl<B: Debug + AsRef<[u8]>> Debug for UnparsedPublicKey<B> {
f.write_str(&format!(
"UnparsedPublicKey {{ algorithm: {:?}, bytes: {:?} }}",
self.alg,
test::to_hex(self.bytes.as_ref())
hex::encode(self.bytes.as_ref())
))
}
}
Expand Down Expand Up @@ -851,6 +851,7 @@ mod tests {

#[test]
fn agreement_traits() {
use crate::test;
use regex;
use regex::Regex;

Expand Down
4 changes: 2 additions & 2 deletions aws-lc-rs/src/ec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ use crate::error::{KeyRejected, Unspecified};
use crate::fips::indicator_check;
use crate::ptr::{ConstPointer, DetachableLcPtr, LcPtr, Pointer};
use crate::signature::{Signature, VerificationAlgorithm};
use crate::{digest, sealed, test};
use crate::{digest, hex, sealed};

pub(crate) mod key_pair;

Expand Down Expand Up @@ -159,7 +159,7 @@ impl Debug for PublicKey {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
f.write_str(&format!(
"EcdsaPublicKey(\"{}\")",
test::to_hex(self.octets.as_ref())
hex::encode(self.octets.as_ref())
))
}
}
Expand Down
6 changes: 3 additions & 3 deletions aws-lc-rs/src/ed25519.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use crate::pkcs8::{Document, Version};
use crate::ptr::LcPtr;
use crate::rand::SecureRandom;
use crate::signature::{KeyPair, Signature, VerificationAlgorithm};
use crate::{constant_time, sealed, test};
use crate::{constant_time, hex, sealed};

/// The length of an Ed25519 public key.
pub const ED25519_PUBLIC_KEY_LEN: usize = aws_lc::ED25519_PUBLIC_KEY_LEN as usize;
Expand Down Expand Up @@ -90,7 +90,7 @@ impl Debug for Ed25519KeyPair {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
f.write_str(&format!(
"Ed25519KeyPair {{ public_key: PublicKey(\"{}\") }}",
test::to_hex(&self.public_key)
hex::encode(&self.public_key)
))
}
}
Expand Down Expand Up @@ -146,7 +146,7 @@ impl AsRef<[u8]> for PublicKey {

impl Debug for PublicKey {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.write_str(&format!("PublicKey(\"{}\")", test::to_hex(self.0)))
f.write_str(&format!("PublicKey(\"{}\")", hex::encode(self.0)))
}
}

Expand Down
67 changes: 67 additions & 0 deletions aws-lc-rs/src/hex.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0 OR ISC

/// Converts bytes to a lower-case hex string
#[allow(clippy::missing_panics_doc)]
pub fn encode<T: AsRef<[u8]>>(bytes: T) -> String {
let bytes = bytes.as_ref();
let mut encoding = String::with_capacity(2 * bytes.len());
for byte in bytes {
let upper_val = byte >> 4u8;
let lower_val = byte & 0x0f;
// DON'T PANIC: it shouldn't be possible to panic because only bottom 4 bits can be set.
encoding.push(char::from_digit(u32::from(upper_val), 16).unwrap());
encoding.push(char::from_digit(u32::from(lower_val), 16).unwrap());
}
encoding
}

/// Converts bytes to an upper-case hex string
pub fn encode_upper<T: AsRef<[u8]>>(bytes: T) -> String {
encode(bytes).to_ascii_uppercase()
}

/// Converts a hex string to a vector of bytes
/// # Errors
/// Returns an error if `hex_str` contains a non-hex digit.
#[allow(clippy::missing_panics_doc)]
pub fn decode(hex_str: &str) -> Result<Vec<u8>, String> {
let mut bytes = Vec::<u8>::with_capacity(hex_str.len() / 2 + 1);
let mut current_byte = b'\0';
let mut index: u32 = 0;
for ch in hex_str.chars() {
if !ch.is_ascii_hexdigit() {
return Err("Invalid hex string".to_string());
}
#[allow(clippy::cast_possible_truncation)]
// DON'T PANIC: it should not be possible to panic because we verify above that the character is a
// hex digit.
let value = ch.to_digit(16).unwrap() as u8;
if index % 2 == 0 {
current_byte = value << 4;
} else {
current_byte |= value;
bytes.push(current_byte);
}

if let Some(idx) = index.checked_add(1) {
index = idx;
} else {
break;
}
}
if index % 2 == 1 {
bytes.push(current_byte);
}
Ok(bytes)
}

/// Converts a hex string to a vector of bytes.
/// It ignores any characters that are not valid hex digits.
#[must_use]
#[allow(clippy::missing_panics_doc)]
pub fn decode_dirty(hex_str: &str) -> Vec<u8> {
let clean: String = hex_str.chars().filter(char::is_ascii_hexdigit).collect();
// DON'T PANIC: it should not be possible to panic because we filter out all non-hex digits.
decode(clean.as_str()).unwrap()
}
3 changes: 2 additions & 1 deletion aws-lc-rs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,6 @@ extern crate core;

pub mod aead;
pub mod agreement;
mod buffer;
pub mod constant_time;
pub mod digest;
pub mod error;
Expand All @@ -118,6 +117,7 @@ pub mod signature;
pub mod test;

mod bn;
mod buffer;
mod cbb;
mod cbs;
pub mod cipher;
Expand All @@ -127,6 +127,7 @@ mod ed25519;
mod endian;
mod evp_pkey;
mod fips;
mod hex;
pub mod iv;
mod ptr;
mod rsa;
Expand Down
4 changes: 2 additions & 2 deletions aws-lc-rs/src/rsa.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use crate::io;
use crate::ptr::{ConstPointer, DetachableLcPtr, LcPtr};
use crate::sealed::Sealed;
use crate::signature::{KeyPair, VerificationAlgorithm};
use crate::{cbs, digest, rand, test};
use crate::{cbs, digest, hex, rand};
#[cfg(feature = "fips")]
use aws_lc::RSA_check_fips;
use aws_lc::{
Expand Down Expand Up @@ -425,7 +425,7 @@ impl Debug for RsaSubjectPublicKey {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
f.write_str(&format!(
"RsaSubjectPublicKey(\"{}\")",
test::to_hex(self.key.as_ref())
hex::encode(self.key.as_ref())
))
}
}
Expand Down
4 changes: 2 additions & 2 deletions aws-lc-rs/src/signature.rs
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,7 @@ pub use crate::ed25519::{
Ed25519KeyPair, Ed25519SeedBin, EdDSAParameters, Seed as Ed25519Seed, ED25519_PUBLIC_KEY_LEN,
};
use crate::rsa;
use crate::{digest, ec, error, sealed, test};
use crate::{digest, ec, error, hex, sealed};

/// The longest signature is an ASN.1 P-384 signature where *r* and *s* are of
/// maximum length with the leading high bit set on each. Then each component
Expand Down Expand Up @@ -361,7 +361,7 @@ impl<B: AsRef<[u8]>> Debug for UnparsedPublicKey<B> {
f.write_str(&format!(
"UnparsedPublicKey {{ algorithm: {:?}, bytes: \"{}\" }}",
self.algorithm,
test::to_hex(self.bytes.as_ref())
hex::encode(self.bytes.as_ref())
))
}
}
Expand Down
56 changes: 5 additions & 51 deletions aws-lc-rs/src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,11 @@ use mirai_annotations::unrecoverable;

use crate::{digest, error};

pub use crate::hex::{
decode as from_hex, decode_dirty as from_dirty_hex, encode as to_hex,
encode_upper as to_hex_upper,
};

extern crate std;

/// `compile_time_assert_clone::<T>();` fails to compile if `T` doesn't
Expand Down Expand Up @@ -341,57 +346,6 @@ where
assert!(!failed, "Test failed.");
}

pub fn to_hex_upper<T: AsRef<[u8]>>(bytes: T) -> String {
to_hex(bytes).to_ascii_uppercase()
}

pub fn to_hex<T: AsRef<[u8]>>(bytes: T) -> String {
let bytes = bytes.as_ref();
let mut encoding = String::with_capacity(2 * bytes.len());
for byte in bytes {
let upper_val = byte >> 4u8;
let lower_val = byte & 0x0f;
encoding.push(char::from_digit(u32::from(upper_val), 16).unwrap());
encoding.push(char::from_digit(u32::from(lower_val), 16).unwrap());
}
encoding
}

pub fn from_hex(hex_str: &str) -> Result<Vec<u8>, String> {
let mut bytes = Vec::<u8>::with_capacity(hex_str.len() / 2 + 1);
let mut current_byte = b'\0';
let mut index: u32 = 0;
for ch in hex_str.chars() {
if !ch.is_ascii_hexdigit() {
return Err("Invalid hex string".to_string());
}
#[allow(clippy::cast_possible_truncation)]
let value = ch.to_digit(16).unwrap() as u8;
if index % 2 == 0 {
current_byte = value << 4;
} else {
current_byte |= value;
bytes.push(current_byte);
}

if let Some(idx) = index.checked_add(1) {
index = idx;
} else {
break;
}
}
if index % 2 == 1 {
bytes.push(current_byte);
}
Ok(bytes)
}

#[must_use]
pub fn from_dirty_hex(hex_str: &str) -> Vec<u8> {
let clean: String = hex_str.chars().filter(char::is_ascii_hexdigit).collect();
from_hex(clean.as_str()).unwrap()
}

fn parse_test_case(
current_section: &mut String,
lines: &mut dyn Iterator<Item = &str>,
Expand Down
Loading