I want to hash string using sha256 and then store it inside of my ink smart contract.

I tested this code in Rust and it works out for me:

use crypto::sha2::Sha256;
use crypto::digest::Digest;

let phrase = "purchase hobby popular celery evil fantasy someone party position gossip host gather";
let mut seed = Sha256::new();
let mut bytes = vec![0; seed.output_bytes()];

However, this code doesn't compile in ink, because ink can't seem to use crypto crate...

How can I use keccak256 inside of an ink smart contract to return me Vec ?

I found package Sha2x256, but I'm unsure how I should use this?

  • 1
    In this questions, he suggested to Hash String in client code and store that Hash in the contract.
    – Ganesh11
    Nov 5, 2022 at 11:04

1 Answer 1


You can use ink_env::hash module.

Then your hash function would look something like this

    use ink_env::hash;

    pub fn hash_keccak_256(input: &[u8]) -> [u8; 32] {
        let mut output = <hash::Keccak256 as hash::HashOutput>::Type::default();
        ink_env::hash_bytes::<hash::Keccak256>(input, &mut output);

input ofc is the bytes representation of the hashed value.

For ink! 4 replace ink_env with ink::env

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.