Hashing
Cryptographic hash functions map arbitrary-length input to a fixed-length output (the hash value). These functions are one-way, meaning you cannot recover the input from the hash, and collision-resistant, meaning you cannot find two different inputs that produce the same hash. You use hash functions on Sui for data integrity verification, commitment schemes, and content addressing.
Sui supports the following cryptographic hash functions:
| Hash function | Module | Output size | Use case |
|---|---|---|---|
| SHA2-256 | std::hash::sha2_256 | 32 bytes | General-purpose hashing, interoperability with Bitcoin and TLS |
| SHA3-256 | std::hash::sha3_256 | 32 bytes | General-purpose hashing, NIST-standardized alternative to SHA2 |
| Keccak256 | sui::hash::keccak256 | 32 bytes | Ethereum compatibility (Keccak256 is the hash function used in Ethereum for address derivation and signatures) |
| Blake2b-256 | sui::hash::blake2b256 | 32 bytes | High-performance hashing, used internally by Sui for object ID computation |
SHA2-256 and SHA3-256 are in the Move Standard Library (std::hash). Keccak256 and Blake2b-256 are in the Sui Framework (sui::hash). The difference affects how you import them in your module.
Usage
The SHA2-256 and SHA3-256 hash functions are available in the Move Standard Library in the std::hash module. The following example shows how to use the SHA2-256 hash function in a smart contract:
module test::hashing_std {
use std::hash;
use sui::object::{Self, UID};
use sui::tx_context::TxContext;
use sui::transfer;
use std::vector;
/// Object that holds the output hash value.
struct Output has key, store {
id: UID,
value: vector<u8>
}
public fun hash_data(data: vector<u8>, recipient: address, ctx: &mut TxContext) {
let hashed = Output {
id: object::new(ctx),
value: hash::sha2_256(data),
};
// Transfer an output data object holding the hashed data to the recipient.
transfer::public_transfer(hashed, recipient)
}
}
The Keccak256 and Blake2b-256 hash functions are available through the sui::hash module in the Sui Move Library. An example of how to use the Keccak256 hash function in a smart contract is shown below. Notice that here, the input to the hash function is given as a reference. This is the case for both Keccak256 and Blake2b-256.
module test::hashing_sui {
use sui::hash;
use sui::object::{Self, UID};
use sui::tx_context::TxContext;
use sui::transfer;
use std::vector;
/// Object that holds the output hash value.
struct Output has key, store {
id: UID,
value: vector<u8>
}
public fun hash_data(data: vector<u8>, recipient: address, ctx: &mut TxContext) {
let hashed = Output {
id: object::new(ctx),
value: hash::keccak256(&data),
};
// Transfer an output data object holding the hashed data to the recipient.
transfer::public_transfer(hashed, recipient)
}
}