-
-
Save RandyMcMillan/f2f24959f1e44d6023fda1621d3853f6 to your computer and use it in GitHub Desktop.
hamming_distance.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use sha2::{Digest, Sha256}; | |
/// Calculates the Hamming distance between two SHA-256 hashes. | |
/// | |
/// This function takes two byte slices representing SHA-256 hashes and returns | |
/// the number of bits that differ between them. | |
fn hamming_distance_sha256(hash1: &[u8], hash2: &[u8]) -> u32 { | |
assert_eq!(hash1.len(), 32, "Invalid hash1 length"); | |
assert_eq!(hash2.len(), 32, "Invalid hash2 length"); | |
let mut distance = 0; | |
for (b1, b2) in hash1.iter().zip(hash2.iter()) { | |
let xor = b1 ^ b2; | |
distance += xor.count_ones(); | |
} | |
distance | |
} | |
/// Calculates the SHA-256 hash of a given byte slice. | |
fn sha256_hash(data: &[u8]) -> Vec<u8> { | |
let mut hasher = Sha256::new(); | |
hasher.update(data); | |
hasher.finalize().to_vec() | |
} | |
/// Calculates the distance between two strings based on their SHA-256 hashes. | |
/// | |
/// This function calculates the SHA-256 hashes of the input strings and | |
/// then computes the Hamming distance between the hashes. | |
fn string_distance_sha256(str1: &str, str2: &str) -> u32 { | |
let hash1 = sha256_hash(str1.as_bytes()); | |
let hash2 = sha256_hash(str2.as_bytes()); | |
hamming_distance_sha256(&hash1, &hash2) | |
} | |
fn main(){ | |
let distance = string_distance_sha256(&"",&" "); | |
println!("{}", distance); | |
} | |
#[cfg(test)] | |
mod tests { | |
use super::*; | |
#[test] | |
fn test_hamming_distance_sha256() { | |
let hash1: [u8; 32] = [ | |
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, | |
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, | |
]; | |
let hash2: [u8; 32] = [ | |
0xff, 0xfe, 0xfd, 0xfc, 0xfb, 0xfa, 0xf9, 0xf8, 0xf7, 0xf6, 0xf5, 0xf4, 0xf3, 0xf2, 0xf1, 0xf0, | |
0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, | |
]; | |
assert_eq!(hamming_distance_sha256(&hash1, &hash2), 256); | |
let hash3: [u8; 32] = [ | |
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, | |
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, | |
]; | |
assert_eq!(hamming_distance_sha256(&hash1, &hash3), 0); | |
} | |
#[test] | |
fn test_string_distance_sha256() { | |
//assert_eq!(string_distance_sha256("hello", "hello"), 0); | |
//assert_eq!(string_distance_sha256("hello", "world"), 256); // Example, actual distance may vary | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment