Skip to content

Commit

Permalink
feat(from_hex): Implemented Integrity::from_hex(), inverse of Integri…
Browse files Browse the repository at this point in the history
…ty::to_hex() (#11)

Fixes: #10
  • Loading branch information
nouritsu authored Jul 18, 2023
1 parent 95473be commit 991628e
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,8 @@ pub enum Error {
#[error("Integrity check failed.\n\tWanted: {0}\n\tActual: {1}")]
#[diagnostic(code(ssri::integrity_check_error), url(docsrs))]
IntegrityCheckError(Integrity, Integrity),
/// Error Decoding Hex Data
#[error("Failed decode hexadecimal data, reason: {0}")]
#[diagnostic(code(ssri::hex_decode_error), url(docsrs))]
HexDecodeError(String),
}
28 changes: 28 additions & 0 deletions src/integrity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,24 @@ impl Integrity {
.result()
}

/// Converts a hex string obtained from `to_hex()` to an `Integrity` with a `Hash` containing algorithm and decoded hex string.
///
/// # Example
///```
/// use ssri::{Integrity, Algorithm};
///
/// let expected = Integrity::from(b"hello");
/// let hex = String::from("2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824");
/// assert_eq!(Integrity::from_hex(hex, Algorithm::Sha256).unwrap(), expected);
///```
pub fn from_hex<B: AsRef<[u8]>>(hex: B, algorithm: Algorithm) -> Result<Integrity, Error> {
let b16 = hex::decode(hex).map_err(|e| Error::HexDecodeError(e.to_string()))?;
let digest = base64::prelude::BASE64_STANDARD.encode(b16);
Ok(Integrity {
hashes: vec![Hash { algorithm, digest }],
})
}

/// Join together two `Integrity` instances. Hashes will be grouped and
/// sorted by algorithm but otherwise kept in the same order.
///
Expand Down Expand Up @@ -241,6 +259,16 @@ mod tests {
)
}

#[test]
fn from_hex() {
let expected_integrity = Integrity::from(b"hello world");
let hex = String::from("b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9");
assert_eq!(
Integrity::from_hex(hex, Algorithm::Sha256).unwrap(),
expected_integrity
);
}

#[test]
fn to_hex() {
let sri = Integrity::from(b"hello world");
Expand Down

0 comments on commit 991628e

Please sign in to comment.