elabs_crypto/
lib.rs

1// Copyright (C) 2022 The Elabs Authors.
2// This file is part of the Elabs.
3//
4// Elabs 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, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Elabs is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Elabs.  If not, see <https://www.gnu.org/licenses/>.
16
17//! # Elabs Crypto.
18//! This crate provides a set of cryptographic helper functions.
19//! It provide `secp256k1` PublicKey, PrivateKey, signer, and `hash` functions.
20//! This crate is based on [`secp256k1`] and [`tiny-keccak`].
21//!
22//! ## Usage
23//! ```toml
24//! [dependencies]
25//! elabs-crypto = "0.1"
26//! ```
27//! ## Example
28//! ```rust
29//! use elabs_crypto::*;
30//!
31//! fn main() {
32//!        let msg = b"hello world";
33//!        let hash = keccak256(msg);
34//!        let sk = PrivateKey::random();
35//!        let pk = sk.to_public().unwrap();
36//!        let sig = sign(msg, sk).unwrap();
37//!        let (recid, bsig) = sig.serialize_compact();
38//!        let pk2 = ecrecover(&hash, &bsig, recid.to_i32() as u8).unwrap();
39//!        assert_eq!(pk, pk2);
40//! }
41//! ```
42
43pub mod keys;
44pub use keys::*;
45
46pub mod signer;
47pub use signer::*;
48
49use tiny_keccak::{Hasher, Keccak};
50
51/// calculate and return keccak256 hash of the input data.
52/// # Arguments
53/// * `data` - input data
54/// # Returns
55/// keccak256 hash of the input data.
56pub fn keccak256(data: &[u8]) -> [u8; 32] {
57    let mut buf = [0u8; 32];
58    let mut hasher = Keccak::v256();
59    hasher.update(data);
60    hasher.finalize(&mut buf);
61    buf
62}
63
64/// calculate and return keccak512 hash of the input data.
65/// # Arguments
66/// * `data` - input data
67/// # Returns
68/// keccak512 hash of the input data.
69pub fn keccak512(data: &[u8]) -> [u8; 64] {
70    let mut buf = [0u8; 64];
71    let mut hasher = Keccak::v512();
72    hasher.update(data);
73    hasher.finalize(&mut buf);
74    buf
75}