SHA-2
The OpenVM SHA-2 guest library provides access to a set of accelerated SHA-2 family hash functions. Currently, it supports the following:
- SHA-256
- SHA-512
- SHA-384
Refer to the FIPS publication for more details on the SHA-2 family of hash functions.
The SHA-2 guest library provides the Sha256, Sha512, and Sha384 structs for use in your guest code.
These structs mimic the identically-named structs found in the sha2 crate, in that they implement the sha2::Digest trait.
Importantly, the sha2::Digest trait has the following methods, which can be used to incrementally hash a stream of bytes.
fn update(&mut self, data: impl AsRef<[u8]>);
fn finalize(self) -> GenericArray<u8, Self::OutputSize>;
Example
The following example can be run as guest code or host code (i.e. run in the zkvm or natively).
To run with guest code, use cargo openvm run, and for host code use cargo run.
The implementations for Sha256, Sha512, and Sha384 fall back to using sha2 when running as host code.
#![cfg_attr(all(target_os = "zkvm", not(feature = "std")), no_main)]
#![cfg_attr(all(target_os = "zkvm", not(feature = "std")), no_std)]
extern crate alloc;
use alloc::{format, string::String};
use openvm_sha2::{Digest, Sha256, Sha384, Sha512};
openvm::entry!(main);
fn println(s: String) {
#[cfg(target_os = "zkvm")]
openvm::io::println(s);
#[cfg(not(target_os = "zkvm"))]
println!("{}", s);
}
pub fn main() {
let mut sha256 = Sha256::new();
sha256.update(b"Hello, world!");
sha256.update(b"some other input");
let output = sha256.finalize();
println(format!("SHA-256: {:?}", output));
let mut sha512 = Sha512::new();
sha512.update(b"Hello, world!");
sha512.update(b"some other input");
let output = sha512.finalize();
println(format!("SHA-512: {:?}", output));
let mut sha384 = Sha384::new();
sha384.update(b"Hello, world!");
sha384.update(b"some other input");
let output = sha384.finalize();
println(format!("SHA-384: {:?}", output));
}To be able to import the shaXXX functions and run the example, add the following to your Cargo.toml file:
openvm = { git = "https://github.com/openvm-org/openvm.git", tag = "v2.0.0-beta.2" }
openvm-sha2 = { git = "https://github.com/openvm-org/openvm.git", tag = "v2.0.0-beta.2" }Config parameters
For the guest program to build successfully add the following to your .toml file:
[app_vm_config.sha2]