chik_sha2/
lib.rs

1#[cfg(not(feature = "openssl"))]
2use sha2::Digest;
3
4#[derive(Default, Clone)]
5pub struct Sha256 {
6    #[cfg(feature = "openssl")]
7    ctx: openssl::sha::Sha256,
8
9    #[cfg(not(feature = "openssl"))]
10    ctx: sha2::Sha256,
11}
12
13impl Sha256 {
14    pub fn new() -> Self {
15        Self::default()
16    }
17    pub fn update(&mut self, buf: impl AsRef<[u8]>) {
18        self.ctx.update(buf.as_ref());
19    }
20    pub fn finalize(self) -> [u8; 32] {
21        #[cfg(feature = "openssl")]
22        {
23            self.ctx.finish()
24        }
25        #[cfg(not(feature = "openssl"))]
26        {
27            self.ctx.finalize().into()
28        }
29    }
30}
31
32#[test]
33fn test_sha256() {
34    // https://www.di-mgt.com.au/sha_testvectors.html
35
36    let output = &[
37        0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, 0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, 0x22,
38        0x23, 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c, 0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00,
39        0x15, 0xad,
40    ];
41
42    let mut ctx = Sha256::new();
43    ctx.update([0x61, 0x62, 0x63]);
44    assert_eq!(&ctx.finalize().as_slice(), output);
45
46    let mut ctx = Sha256::new();
47    ctx.update([0x61]);
48    ctx.update([0x62]);
49    ctx.update([0x63]);
50    assert_eq!(&ctx.finalize().as_slice(), output);
51
52    let mut ctx = Sha256::new();
53    ctx.update([0x61, 0x62]);
54    ctx.update([0x63]);
55    assert_eq!(&ctx.finalize().as_slice(), output);
56
57    let mut ctx = Sha256::new();
58    ctx.update([0x61]);
59    ctx.update([0x62, 0x63]);
60    assert_eq!(&ctx.finalize().as_slice(), output);
61}