signatory/
algorithm.rs

1//! Algorithms supported by this library.
2
3use crate::{Error, Result};
4
5#[cfg(feature = "ed25519")]
6use crate::ed25519;
7
8/// Signature algorithms.
9#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
10#[non_exhaustive]
11pub enum Algorithm {
12    /// ECDSA with NIST P-256.
13    #[cfg(feature = "nistp256")]
14    EcdsaNistP256,
15
16    /// ECDSA with NIST P-384.
17    #[cfg(feature = "nistp384")]
18    EcdsaNistP384,
19
20    /// ECDSA with secp256k1.
21    #[cfg(feature = "secp256k1")]
22    EcdsaSecp256k1,
23
24    /// Ed25519.
25    #[cfg(feature = "ed25519")]
26    Ed25519,
27}
28
29impl Algorithm {
30    /// Is the algorithm ECDSA?
31    #[cfg(feature = "ecdsa")]
32    pub fn is_ecdsa(self) -> bool {
33        #[cfg(feature = "nistp256")]
34        if self == Algorithm::EcdsaNistP256 {
35            return true;
36        }
37
38        #[cfg(feature = "nistp384")]
39        if self == Algorithm::EcdsaNistP384 {
40            return true;
41        }
42
43        #[cfg(feature = "secp256k1")]
44        if self == Algorithm::EcdsaSecp256k1 {
45            return true;
46        }
47
48        false
49    }
50}
51
52impl TryFrom<pkcs8::AlgorithmIdentifierRef<'_>> for Algorithm {
53    type Error = Error;
54
55    #[allow(unused_variables)]
56    fn try_from(pkcs8_alg_id: pkcs8::AlgorithmIdentifierRef<'_>) -> Result<Self> {
57        #[cfg(feature = "ecdsa")]
58        if pkcs8_alg_id.oid == ecdsa::elliptic_curve::ALGORITHM_OID {
59            #[cfg(any(feature = "nistp256", feature = "secp256k1"))]
60            use pkcs8::AssociatedOid;
61
62            #[cfg(feature = "nistp256")]
63            if pkcs8_alg_id.parameters_oid() == Ok(crate::ecdsa::NistP256::OID) {
64                return Ok(Self::EcdsaNistP256);
65            }
66
67            #[cfg(feature = "nistp384")]
68            if pkcs8_alg_id.parameters_oid() == Ok(crate::ecdsa::NistP384::OID) {
69                return Ok(Self::EcdsaNistP384);
70            }
71
72            #[cfg(feature = "secp256k1")]
73            if pkcs8_alg_id.parameters_oid() == Ok(crate::ecdsa::Secp256k1::OID) {
74                return Ok(Self::EcdsaSecp256k1);
75            }
76        }
77
78        #[cfg(feature = "ed25519")]
79        if pkcs8_alg_id == ed25519::ALGORITHM_ID {
80            return Ok(Self::Ed25519);
81        }
82
83        Err(Error::AlgorithmInvalid)
84    }
85}