Reproducable sha256 of hashmap

Hi everybody

I am just taking my first steps with Rust.
I coded some functions and with the help of the Cookbook and the Rust Book, all the functions are working as I expect! With the exception of one function.

I try to calc a sha256 of a hashmap. So I coded a small test case:


    fn calc_sha256_of_document_1( ){

        let x : u16 = 34566;

        let mut document: HashMap<String, String>  = HashMap::new();
        document.insert( String::from("random"), x.to_string() );
        document.insert( String::from("doc_type"), String::from("Test document type") );
        document.insert( String::from("name"), String::from("Mike") );
        println!("document: {:?}",document );

        let digest: Digest = calc_sha256_of_document(&document).unwrap(); // call my own function

        let hash = HEXUPPER.encode(digest.as_ref());
        let s = String::from("B755BA07226A25E48C9EC854D60BA4811446F58CD55D52DFC0C6BADF11228B74");

        println!("h: {:?}", hash);
        println!("s: {:?}", s);    

        assert!( s.eq(&hash) );


and the function is:

fn calc_sha256_of_document( doc: &HashMap<String, String> ) -> Result<Digest> {

    let mut context = Context::new(&SHA256);

    for (key, val) in doc.iter() {




To my surprise the function returns a different value almost every time.
I don't understand waht I'm doing wrong, so any help would be appreciated...

I'm using the following crate:

use ring::digest::{Context, Digest, SHA256};

Thanks in advance

When you iterate through a hash map, you get the values in random order, but changing the order changes the hash. Consider using a BTreeMap, which always has the keys in sorted order.


Hi alice

what for a shame, I'm so stupid.
I have the same behaviour in another language....
So it's not a Rust issue, it's my mind

Thank you very much for your very fast answer ...


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.