ades/digest.rs
1use const_oid::ObjectIdentifier;
2use sha2::Digest;
3
4/// Supported digest algorithms for AdES signatures.
5#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6#[non_exhaustive]
7pub enum DigestAlgorithm {
8 /// SHA-256 (recommended minimum for new signatures).
9 Sha256,
10 /// SHA-384.
11 Sha384,
12 /// SHA-512.
13 Sha512,
14}
15
16impl DigestAlgorithm {
17 /// Returns the OID for this digest algorithm.
18 ///
19 /// # Example
20 ///
21 /// ```
22 /// use ades::DigestAlgorithm;
23 /// let oid = DigestAlgorithm::Sha256.oid();
24 /// assert_eq!(oid.to_string(), "2.16.840.1.101.3.4.2.1");
25 /// ```
26 #[must_use]
27 pub fn oid(self) -> ObjectIdentifier {
28 match self {
29 // id-sha256
30 Self::Sha256 => ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.2.1"),
31 // id-sha384
32 Self::Sha384 => ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.2.2"),
33 // id-sha512
34 Self::Sha512 => ObjectIdentifier::new_unwrap("2.16.840.1.101.3.4.2.3"),
35 }
36 }
37
38 /// Computes the digest of `data` using this algorithm.
39 ///
40 /// # Example
41 ///
42 /// ```
43 /// use ades::DigestAlgorithm;
44 /// let digest = DigestAlgorithm::Sha256.hash(b"hello world");
45 /// assert_eq!(digest.len(), 32);
46 /// ```
47 #[must_use]
48 pub fn hash(self, data: &[u8]) -> Vec<u8> {
49 match self {
50 Self::Sha256 => sha2::Sha256::digest(data).to_vec(),
51 Self::Sha384 => sha2::Sha384::digest(data).to_vec(),
52 Self::Sha512 => sha2::Sha512::digest(data).to_vec(),
53 }
54 }
55
56 /// Returns the output length in bytes for this algorithm.
57 #[must_use]
58 pub fn output_len(self) -> usize {
59 match self {
60 Self::Sha256 => 32,
61 Self::Sha384 => 48,
62 Self::Sha512 => 64,
63 }
64 }
65}