Skip to content

Instantly share code, notes, and snippets.

@aludvik
Created October 11, 2018 16:17
Show Gist options
  • Save aludvik/26750afe309cc5e3b879c881e668fa3a to your computer and use it in GitHub Desktop.
Save aludvik/26750afe309cc5e3b879c881e668fa3a to your computer and use it in GitHub Desktop.
Verify openssl and rust-crypto give them same output
extern crate hex;
extern crate openssl;
extern crate crypto;
use crypto::digest::Digest;
fn main() {
eprintln!("testing simple hash");
test_simple_hash();
eprintln!("testing cumulative hash");
test_cumulative_hash();
}
fn test_simple_hash() {
let test_data = "alpha";
assert_eq!(
crypto_simple_sha256(&test_data),
openssl_simple_sha256(&test_data),
);
assert_eq!(
crypto_simple_sha512(&test_data),
openssl_simple_sha512(&test_data),
);
}
fn crypto_simple_sha256(item: &str) -> String {
crypto_simple(crypto::sha2::Sha256::new(), item)
}
fn crypto_simple_sha512(item: &str) -> String {
crypto_simple(crypto::sha2::Sha512::new(), item)
}
fn crypto_simple<D: Digest>(mut hasher: D, item: &str) -> String {
hasher.input(item.as_bytes());
hasher.result_str().to_string()
}
fn openssl_simple_sha256(item: &str) -> String {
let mut bytes: Vec<u8> = Vec::new();
bytes.extend(openssl::sha::sha256(item.as_bytes()).iter());
hex::encode(bytes)
}
fn openssl_simple_sha512(item: &str) -> String {
let mut bytes: Vec<u8> = Vec::new();
bytes.extend(openssl::sha::sha512(item.as_bytes()).iter());
hex::encode(bytes)
}
fn test_cumulative_hash() {
let test_data = vec!["alpha", "beta", "gamma"];
assert_eq!(
crypto_cumulative_sha256(&test_data),
openssl_cumulative_sha256(&test_data),
);
assert_eq!(
crypto_cumulative_sha512(&test_data),
openssl_cumulative_sha512(&test_data),
);
}
fn crypto_cumulative_sha256(items: &[&str]) -> Vec<u8> {
crypto_cumulative(crypto::sha2::Sha256::new(), items)
}
fn crypto_cumulative_sha512(items: &[&str]) -> Vec<u8> {
crypto_cumulative(crypto::sha2::Sha512::new(), items)
}
fn crypto_cumulative<D: Digest>(mut hasher: D, items: &[&str]) -> Vec<u8> {
for item in items {
hasher.input_str(item);
}
let mut bytes = vec![0; hasher.output_bytes()];
hasher.result(&mut bytes);
bytes
}
fn openssl_cumulative_sha256(items: &[&str]) -> Vec<u8> {
let mut hasher = openssl::sha::Sha256::new();
for item in items {
hasher.update(item.as_bytes());
}
let mut bytes = Vec::new();
bytes.extend(hasher.finish().iter());
bytes
}
fn openssl_cumulative_sha512(items: &[&str]) -> Vec<u8> {
let mut hasher = openssl::sha::Sha512::new();
for item in items {
hasher.update(item.as_bytes());
}
let mut bytes = Vec::new();
bytes.extend(hasher.finish().iter());
bytes
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment