Skip to main content

wire_e2e_identity/
utils.rs

1use certval::ExtensionProcessing as _;
2use rusty_jwt_tools::{
3    jsonwebtoken::DecodingKey,
4    prelude::{JwsAlgorithm, Pem},
5};
6use spki::AlgorithmIdentifierOwned;
7use x509_cert::ext::pkix::AuthorityKeyIdentifier;
8
9use crate::{error::E2eIdentityResult, validation};
10
11pub fn generate_key(sign_alg: JwsAlgorithm) -> E2eIdentityResult<Pem> {
12    Ok(sign_alg.generate_keypair()?)
13}
14
15pub fn pem_from_bytes(bytes: &[u8], sign_alg: JwsAlgorithm) -> E2eIdentityResult<Pem> {
16    Ok(sign_alg.keypair_from_bytes(bytes)?)
17}
18
19/// The public key of `keypair`, as an uncompressed SEC1 point for ECDSA and as the 32 byte key for EdDSA
20pub(crate) fn public_key_bytes(alg: JwsAlgorithm, keypair: &Pem) -> E2eIdentityResult<Vec<u8>> {
21    let jwk = alg.public_jwk(keypair)?;
22    Ok(DecodingKey::from_jwk(&jwk)?.try_get_as_bytes()?.to_vec())
23}
24
25pub(crate) fn jws_alg_to_x509_identifier(alg: JwsAlgorithm) -> AlgorithmIdentifierOwned {
26    match alg {
27        JwsAlgorithm::EdDSA => AlgorithmIdentifierOwned {
28            oid: const_oid::db::rfc8410::ID_ED_25519,
29            parameters: None,
30        },
31        JwsAlgorithm::ES256 => AlgorithmIdentifierOwned {
32            oid: const_oid::db::rfc5912::ID_EC_PUBLIC_KEY,
33            parameters: Some(const_oid::db::rfc5912::SECP_256_R_1.into()),
34        },
35        JwsAlgorithm::ES384 => AlgorithmIdentifierOwned {
36            oid: const_oid::db::rfc5912::ID_EC_PUBLIC_KEY,
37            parameters: Some(const_oid::db::rfc5912::SECP_384_R_1.into()),
38        },
39        JwsAlgorithm::ES512 => AlgorithmIdentifierOwned {
40            oid: const_oid::db::rfc5912::ID_EC_PUBLIC_KEY,
41            parameters: Some(const_oid::db::rfc5912::SECP_521_R_1.into()),
42        },
43    }
44}
45
46pub(crate) fn extract_ski_aki_from_cert(cert: &x509_cert::Certificate) -> validation::Result<(String, Option<String>)> {
47    let cert = certval::PDVCertificate::try_from(cert.clone())?;
48
49    let ski = cert
50        .get_extension(&const_oid::db::rfc5912::ID_CE_SUBJECT_KEY_IDENTIFIER)?
51        .ok_or(validation::Error::MissingSki)?;
52    let ski = match ski {
53        certval::PDVExtension::SubjectKeyIdentifier(ski) => hex::encode(ski.0.as_bytes()),
54        _ => return Err(validation::Error::ImplementationError),
55    };
56
57    let aki = cert
58        .get_extension(&const_oid::db::rfc5912::ID_CE_AUTHORITY_KEY_IDENTIFIER)?
59        .and_then(|ext| match ext {
60            certval::PDVExtension::AuthorityKeyIdentifier(AuthorityKeyIdentifier { key_identifier, .. }) => {
61                key_identifier.as_ref()
62            }
63            _ => None,
64        })
65        .map(|ki| hex::encode(ki.as_bytes()));
66
67    Ok((ski, aki))
68}