Skip to main content

smgw_sec/
openssl.rs

1mod signing;
2pub use signing::BrainpoolP256SigningKey;
3
4use crate::BrainpoolP256Verifier;
5use ::openssl::{
6    bn::BigNum,
7    ecdsa::EcdsaSig,
8    error::ErrorStack,
9    hash::MessageDigest,
10    nid::Nid,
11    pkey::{PKey, Public},
12    sign::Verifier,
13};
14use core::fmt;
15
16/// Configuration failure while loading a provisioned verifier key.
17#[derive(Debug)]
18pub enum PublicKeyError {
19    /// The key is not a valid named brainpoolP256r1 public key.
20    InvalidKey,
21    /// OpenSSL could not decode the supplied SubjectPublicKeyInfo.
22    Decode(ErrorStack),
23}
24
25impl fmt::Display for PublicKeyError {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        match self {
28            Self::InvalidKey => f.write_str("expected a valid Brainpool P-256 public key"),
29            Self::Decode(error) => error.fmt(f),
30        }
31    }
32}
33
34impl core::error::Error for PublicKeyError {
35    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
36        match self {
37            Self::InvalidKey => None,
38            Self::Decode(error) => Some(error),
39        }
40    }
41}
42
43/// A provisioned OpenSSL public key checked for the Brainpool P-256 signature profile.
44#[derive(Clone)]
45pub struct BrainpoolP256PublicKey(PKey<Public>);
46
47impl BrainpoolP256PublicKey {
48    /// Load the SubjectPublicKeyInfo from an independently trusted PEM.
49    pub fn from_pem(pem: &[u8]) -> Result<Self, PublicKeyError> {
50        Self::new(PKey::public_key_from_pem(pem).map_err(PublicKeyError::Decode)?)
51    }
52
53    /// Bind a public key obtained from an authenticated source, for example a validated certificate.
54    pub fn new(key: PKey<Public>) -> Result<Self, PublicKeyError> {
55        let ec = key.ec_key().map_err(|_| PublicKeyError::InvalidKey)?;
56        if ec.group().curve_name() != Some(Nid::BRAINPOOL_P256R1) {
57            return Err(PublicKeyError::InvalidKey);
58        }
59        ec.check_key().map_err(|_| PublicKeyError::InvalidKey)?;
60        Ok(Self(key))
61    }
62}
63
64impl BrainpoolP256Verifier for BrainpoolP256PublicKey {
65    type Error = ErrorStack;
66
67    fn verify(&mut self, message: &[u8], r: &[u8; 32], s: &[u8; 32]) -> Result<bool, Self::Error> {
68        // EVP accepts a DER-encoded ECDSA signature.
69        let signature =
70            EcdsaSig::from_private_components(BigNum::from_slice(r)?, BigNum::from_slice(s)?)?;
71        Verifier::new(MessageDigest::sha256(), &self.0)?
72            .verify_oneshot(&signature.to_der()?, message)
73    }
74}
75
76#[cfg(test)]
77mod tests {
78    use super::*;
79    use ::openssl::ec::{EcGroup, EcKey};
80
81    #[test]
82    fn commissioning_requires_a_well_formed_brainpool_public_key() {
83        let group = EcGroup::from_curve_name(Nid::X9_62_PRIME256V1).unwrap();
84        let other = PKey::from_ec_key(EcKey::generate(&group).unwrap()).unwrap();
85        assert!(matches!(
86            BrainpoolP256PublicKey::from_pem(&other.public_key_to_pem().unwrap()),
87            Err(PublicKeyError::InvalidKey)
88        ));
89        assert!(matches!(
90            BrainpoolP256PublicKey::from_pem(b""),
91            Err(PublicKeyError::Decode(_))
92        ));
93    }
94}