add sample

This commit is contained in:
2020-05-12 01:10:22 +08:00
parent 99a0486e26
commit 9f43983660
3 changed files with 31 additions and 1 deletions

1
crypto/Cargo.lock generated
View File

@@ -51,6 +51,7 @@ dependencies = [
"p256",
"p384",
"p521",
"sha2",
]
[[package]]

View File

@@ -15,4 +15,5 @@ k256 = "0.2.0"
p256 = "0.2.0"
p384 = "0.1.0"
p521 = "0.0.0"
sha2 = "0.8.1"

View File

@@ -1,3 +1,31 @@
use sha2::{Sha256, Sha512, Digest};
fn main() {
println!("Hello, world!");
println!("{}", to_hex(&sha256(b"hello world")));
println!("{}", to_hex(&sha512(b"hello world")));
}
fn sha256(data: &[u8]) -> Vec<u8> {
let mut hasher = Sha256::new();
hasher.input(data);
let result = hasher.result();
result[..].to_vec()
}
fn sha512(data: &[u8]) -> Vec<u8> {
let mut hasher = Sha512::new();
hasher.input(data);
let result = hasher.result();
result[..].to_vec()
}
fn to_hex(bs: &[u8]) -> String {
bs.iter().map(|u| {
let x = format!("{:x}", u);
if x.len() == 1 {
"0".to_owned() + &x
} else {
x
}
}).collect()
}