cfun/
c_crypto.rs

1#[cfg(feature = "crypto")]
2use md5::{Digest, Md5};
3#[cfg(feature = "crypto")]
4use sha2::Sha256;
5
6/// get md5 of data
7#[cfg(feature = "crypto")]
8pub fn md5(data: &Vec<u8>, upper: bool) -> String {
9    let mut hasher = Md5::new();
10    hasher.update(data);
11    let result = hasher.finalize();
12    if upper {
13        format!("{:X}", result)
14    } else {
15        format!("{:x}", result)
16    }
17}
18
19/// get sha256 of data
20#[cfg(feature = "crypto")]
21pub fn sha256(data: &Vec<u8>, upper: bool) -> String {
22    let mut hasher = Sha256::new();
23    hasher.update(data);
24    let result = hasher.finalize();
25    if upper {
26        format!("{:X}", result)
27    } else {
28        format!("{:x}", result)
29    }
30}
31
32/// encode data with base64
33#[cfg(feature = "crypto")]
34pub fn base64_encode(data: &Vec<u8>) -> String {
35    use base64::{prelude::BASE64_STANDARD, Engine};
36    BASE64_STANDARD.encode(data)
37}
38
39/// decode data with base64
40#[cfg(feature = "crypto")]
41pub fn base64_decode(data: String) -> Result<Vec<u8>, base64::DecodeError> {
42    use base64::{prelude::BASE64_STANDARD, Engine};
43    BASE64_STANDARD.decode(data)
44}
45
46#[test]
47#[cfg(feature = "crypto")]
48fn test_md5() {
49    let data = b"hello world";
50    assert_eq!(
51        md5(&data.to_vec(), false),
52        "5eb63bbbe01eeed093cb22bb8f5acdc3"
53    );
54}
55
56#[test]
57#[cfg(feature = "crypto")]
58fn c_crypto_test_sha256() {
59    let data = b"hello world";
60    assert_eq!(
61        sha256(&data.to_vec(), false),
62        "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"
63    );
64}
65
66#[test]
67#[cfg(feature = "crypto")]
68fn test_base64_encode() {
69    let data = b"hello world";
70    assert_eq!(base64_encode(&data.to_vec()), "aGVsbG8gd29ybGQ=");
71}
72
73#[test]
74#[cfg(feature = "crypto")]
75fn test_base64_decode() {
76    let data = "aGVsbG8gd29ybGQ=";
77    assert_eq!(base64_decode(data.to_string()).unwrap(), b"hello world");
78}