elabs_k256/
lib.rs

1// Copyright (C) 2022 The Elabs Project Authors.
2// This file is part of the Elabs library.
3//
4// The Elabs library is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, version 3 of the License.
7//
8// The Elabs library is distributed in the hope that it will be useful,
9// but WITHOUT ANY WARRANTY; without even the implied warranty of
10// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11// GNU General Public License for more details.
12//
13// You should have received a copy of the GNU General Public License along with The Elabs library.
14// If not, see <https://www.gnu.org/licenses/>.
15
16//! Elabs-k256 is a wrapper around the tiny_keccak::Keccak::v256() Hasher.
17//! It give a simple interface to use the Hasher.
18//! # Usage
19//! To use elabs_k256, you need to import the `elabs_k256` crate and use the `k256` or `k256_hash` function.
20//! ```toml
21//! [dependencies]
22//! elabs_k256 = "0.1"
23//! ```
24//! # Example
25//! ```rust
26//! use elabs_k256::k256;
27//!
28//! fn main() {
29//!    let input = "Hello World";
30//!    let hash = k256(input);
31//!    println!("{:?}", hash);
32//! }
33//! ```
34//! ```rust
35//! use elabs_k256::k256_hash;
36//!
37//! fn main() {
38//!   let input = "Hello World";
39//!   let mut hash = [0u8; 32];
40//!   k256_hash(input, &mut hash);
41//!   println!("{:?}", hash);
42//! }
43//! ```
44
45use tiny_keccak::{Hasher, Keccak};
46
47/// Compute the keccak256 hash of the input data.
48/// The output is 32 bytes long.
49/// # Arguments
50/// * `data` - The data to hash.
51/// # Return
52/// * The hash of the data.
53/// # Example
54/// ```
55/// use elabs_k256::k256;
56///
57/// fn main() {
58///   let data = "Hello World";
59///   let hash = k256(data);
60///   println!("{:?}", hash);
61/// }
62/// ```
63pub fn k256(data: &str) -> [u8; 32] {
64    let mut hash = [0u8; 32];
65    k256_hash(data, &mut hash);
66    hash
67}
68
69/// Compute the Keccak-256 hash of the given slice.
70/// The result is written directly to the output slice.
71/// # Arguments
72/// * `data` - The data to hash.
73/// * `output` - The output buffer.
74/// # Example
75/// ```
76/// use elabs_k256::k256_hash;
77///
78/// fn main() {
79///  let data = "Hello World";
80///  let mut hash = [0u8; 32];
81///  k256_hash(data, &mut hash);
82///  println!("{:?}", hash);
83/// }
84/// ```
85pub fn k256_hash(data: &str, output: &mut [u8; 32]) {
86    let mut hasher = Keccak::v256();
87    hasher.update(data.as_bytes());
88    hasher.finalize(output);
89}
90
91#[cfg(test)]
92mod test {
93    use super::*;
94
95    // Test k256 and k256_hash.
96    #[test]
97    fn test_hash() {
98        let data = "Hello World";
99        let hash = k256(data);
100        let mut hash2 = [0u8; 32];
101        k256_hash(data, &mut hash2);
102        assert_eq!(hash, hash2);
103    }
104}