Skip to main content

hash

Function hash 

Source
pub fn hash(input: &str) -> Result<String>
Expand description

Computes the SHA-256 hash of the input text.

This function implements the complete SHA-256 algorithm including:

  • Message preprocessing and padding
  • Processing in 512-bit blocks
  • 64 rounds of compression per block
  • Final hash value computation

§Arguments

  • input - The text to hash (any UTF-8 string)

§Returns

Returns a 64-character lowercase hexadecimal string representing the 256-bit hash value.

§Examples

use ruscrypt::hash::sha256;

// Empty string
let hash = sha256::hash("").unwrap();
assert_eq!(hash, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");

// Simple text
let hash = sha256::hash("abc").unwrap();
assert_eq!(hash, "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");

// Unicode support
let hash = sha256::hash("Hello 世界").unwrap();
assert_eq!(hash.len(), 64);

// Consistency check
let hash1 = sha256::hash("test").unwrap();
let hash2 = sha256::hash("test").unwrap();
assert_eq!(hash1, hash2);

§Algorithm Details

The implementation follows RFC 6234 and includes:

  • Proper message padding with length encoding
  • 64 rounds of SHA-256 compression function
  • Correct handling of endianness
  • Support for messages of any length
Examples found in repository?
examples/quick_start.rs (line 154)
147fn quick_hash_example() -> Result<()> {
148    println!("{}", "   Creates unique fingerprints for any data.".white());
149    println!("{}", "   ✅ Secure: Perfect for data integrity and passwords".green());
150    
151    let messages = vec!["Hello", "Hello!", "hello"];
152    
153    for (i, message) in messages.iter().enumerate() {
154        let hash = sha256::hash(message)?;
155        println!("   📝 Input {}: {} → Hash: {}...", 
156                (i + 1).to_string().white(),
157                message.cyan(), 
158                hash[..16].green().bold()
159        );
160    }
161    
162    // Show consistency
163    let test = "consistency";
164    let hash1 = sha256::hash(test)?;
165    let hash2 = sha256::hash(test)?;
166    println!("   🔍 Consistency: {} → {}", 
167            if hash1 == hash2 { "✅ Always same result" } else { "❌ Error" },
168            if hash1 == hash2 { "Perfect!" } else { "Failed!" }
169    );
170    
171    println!("   ✨ Notice: Small input changes = Completely different hashes!");
172    println!("   💡 Try: {}", "cargo run -- hash --sha256".bright_green());
173    
174    Ok(())
175}
More examples
Hide additional examples
examples/demo.rs (line 250)
225fn demo_hash_functions() -> Result<()> {
226    let sample_texts = vec![
227        "Hello, World!",
228        "RusCrypt is awesome!",
229        "Secure hashing with Rust",
230        "Small change", 
231        "small change", // Demonstrate avalanche effect
232    ];
233    
234    println!("{}", "Hash Function Comparison:".yellow());
235    println!("{}", "═════════════════════════".yellow());
236    
237    for (i, text) in sample_texts.iter().enumerate() {
238        println!("\n{} {}:", "Sample".cyan(), (i + 1).to_string().cyan());
239        println!("   Input: {}", text.white());
240        
241        // MD5 Hash
242        let md5_hash = md5::hash(text)?;
243        println!("   MD5    (128-bit): {}", md5_hash.bright_red());
244        
245        // SHA-1 Hash
246        let sha1_hash = sha1::hash(text)?;
247        println!("   SHA-1  (160-bit): {}", sha1_hash.bright_yellow());
248        
249        // SHA-256 Hash
250        let sha256_hash = sha256::hash(text)?;
251        println!("   SHA-256(256-bit): {}", sha256_hash.bright_green());
252        
253        if i == 3 { // Show avalanche effect
254            println!("   💡 Notice how 'Small change' vs 'small change' produces completely different hashes!");
255        }
256    }
257    
258    // Security status
259    println!("\n{}", "Security Status:".yellow());
260    println!("   ❌ MD5:    BROKEN - Collision attacks possible");
261    println!("   ⚠️  SHA-1:  DEPRECATED - Use only for legacy compatibility");
262    println!("   ✅ SHA-256: SECURE - Recommended for modern applications");
263    
264    // Demonstrate hash consistency
265    println!("\n{}", "🔍 Hash Consistency Verification:".yellow());
266    let test_input = "consistency_test";
267    let hash1 = sha256::hash(test_input)?;
268    let hash2 = sha256::hash(test_input)?;
269    println!("   Input: {}", test_input.white());
270    println!("   Hash 1: {}", hash1.green());
271    println!("   Hash 2: {}", hash2.green());
272    println!("   Match: {}", if hash1 == hash2 { "✅ Perfect consistency".bright_green() } else { "❌ Error!".bright_red() });
273    
274    Ok(())
275}