Skip to main content

cert_helper/
lib.rs

1//! # Cert-Helper
2//!
3//! A lightweight helper library for managing X.509 certificates using OpenSSL.
4//! Provides convenient tools for generating Certificate Signing Requests (CSRs),
5//! Certificate Revocation Lists (CRLs), and handling private keys.
6//!
7//! ## Description
8//!
9//! A minimal wrapper combining `openssl`, `yasna`, and `x509-parser` crates
10//! to simplify common certificate operations such as creation, signing, parsing, and revocation.
11//!
12//! The package has not been reviewed for any security issues and is intended for testing purposes only.
13//!
14//! This library provides a set of utility functions to simplify common tasks such as:
15//! - Creating self-signed or CA-signed certificates
16//! - Generating RSA, ECDSA,or Ed25519 private keys, note that Ed25519 do not require any hash variant
17//! - Creating Certificate Signing Requests (CSRs)
18//! - Signing certificates from CSRs using a CA certificate and key
19//! - Reading and writing certificates, keys, and CSRs in PEM format
20//! - Validating certificate chains and properties
21//! - Create or update certificate revocation list(crl)
22//!   - Note that this is a simple crl parser that only handle the fields that are included then
23//!  generating a crl with this code
24//!
25//! ### Certificate Signing Requirements
26//! To sign another certificate, the signing certificate must:
27//! - Have the `CA` (Certificate Authority) flag set to `true`
28//! - Include the `KeyUsage` extension with the `keyCertSign` bit enabled
29//!
30//! These constraints ensure that the certificate is recognized as a valid CA and can be used to issue other certificates.
31//!
32//! ### Use Cases
33//! - Generating certificates for local development or internal services
34//! - Creating a simple certificate authority for testing
35//! - Validating certificate chains in custom TLS setups
36//! - Creating CSRs to be signed by external or internal CAs
37//! - Issuing signed certificates from CSRs for controlled certificate management
38//! - Create crl for testing how a client handle certificate revocations, optionally add crl reason for the revoked certificate
39//!
40//!
41//! ## Basic Example creating a certificate and private key
42//! ```rust
43//! use cert_helper::certificate::{CertBuilder, Certificate, HashAlg, KeyType, Usage, verify_cert, UseesBuilderFields};
44//!
45//! // create a self signed certificate with several optional values set
46//! let ca = CertBuilder::new()
47//!     .common_name("My Test Ca")
48//!     .country_name("SE")
49//!     .state_province("Stockholm")
50//!     .organization("my org")
51//!     .locality_time("Stockholm")
52//!     .is_ca(true)
53//!     .key_type(KeyType::P521)
54//!     .signature_alg(HashAlg::SHA512)
55//!     .key_usage([Usage::certsign, Usage::crlsign].into_iter().collect());
56//! let root_cert = ca.build_and_self_sign();
57//! assert!(root_cert.is_ok())
58//! // to write data to file you need to use X509Common to access the save
59//! // ca.save("./certs/", "mytestca")?;
60//!```
61//! ## Basic Example creating a certificate signing request and private key
62//! ```rust
63//! use cert_helper::certificate::{Usage, Csr, verify_cert, UseesBuilderFields,CsrBuilder};
64//!
65//! // create a certificate signing request and private key
66//! let csr_builder = CsrBuilder::new()
67//!    .common_name("example2.com")
68//!    .country_name("SE")
69//!    .state_province("Stockholm")
70//!    .organization("My org")
71//!    .locality_time("Stockholm")
72//!    .alternative_names(vec!["example2.com", "www.example2.com"])
73//!    .key_usage(
74//!        [
75//!            Usage::contentcommitment,
76//!            Usage::encipherment,
77//!            Usage::serverauth,
78//!        ]
79//!        .into_iter()
80//!        .collect(),
81//!    );
82//! let csr = csr_builder.certificate_signing_request();
83//! assert!(csr.is_ok());
84//!
85//! // to write data to file you need to use X509Common to access the save
86//! // csr.save("./certs/", "mytestca")?;
87//!
88//!```
89//! ## Basic Example creating a signed certificate from a signing request
90//! ```rust
91//! use cert_helper::certificate::{CertBuilder, Csr, verify_cert, UseesBuilderFields, CsrBuilder,CsrOptions};
92//!
93//! let ca = CertBuilder::new().common_name("My Test Ca").is_ca(true);
94//! let root_cert = ca.build_and_self_sign().expect("failed to create root certificate");
95//!
96//! let csr_builder = CsrBuilder::new().common_name("example2.com");
97//! let csr = csr_builder.certificate_signing_request().expect("Failed to generate csr");
98//! let options = CsrOptions::new();// used for enabling csr for CA certficates
99//! let cert = csr.build_signed_certificate(&root_cert, options);
100//! assert!(cert.is_ok());
101//! ```
102//!
103//! ## Basic Example creating a chain of signed certificates and verify the chain
104//! ```rust
105//! use cert_helper::certificate::{CertBuilder, verify_cert, UseesBuilderFields};
106//!
107//! let cert = CertBuilder::new().common_name("Cert-1").is_ca(true);
108//! let cert_1 = cert.build_and_self_sign().expect("Failed to create certificate");
109//! let cert = CertBuilder::new().common_name("Cert-2").is_ca(true);
110//! let cert_2 = cert.build_and_sign(&cert_1).expect("Failed to create certificate");
111//! let cert = CertBuilder::new().common_name("Cert-3");
112//! let cert_3 = cert.build_and_sign(&cert_2).expect("Failed to create certificate");
113//!
114//! match verify_cert(&cert_3.x509, &cert_1.x509, vec![&cert_2.x509]) {
115//!    Ok(true) => println!("verify ok"),
116//!    _ => println!("failed verify"),
117//! }
118//!
119//! ```
120//!
121//! ## Example on how to create a certifcate revocation list(clr)
122//!
123//! Create a crl, with one revoked certificate that have CRL Reason: Key Compromise
124//!
125//! ```rust
126//! use cert_helper::certificate::{CertBuilder, UseesBuilderFields};
127//! use cert_helper::crl::{X509CrlBuilder,CrlReason,X509CrlWrapper};
128//! use chrono::Utc;
129//! use num_bigint::BigUint;
130//!
131//! let ca = CertBuilder::new()
132//!    .common_name("My Test Ca")
133//!    .is_ca(true)
134//!    .build_and_self_sign()
135//!    .unwrap();
136//! let mut builder = X509CrlBuilder::new(ca.clone());
137//!     let revocked = CertBuilder::new()
138//!    .common_name("My Test")
139//!    .build_and_self_sign()
140//!    .unwrap();
141//!
142//! let bytes = revocked.x509.serial_number().to_bn().unwrap().to_vec();
143//! builder.add_revoked_cert_with_reason(BigUint::from_bytes_be(&bytes),
144//!                          Utc::now(),
145//!                          vec![CrlReason::KeyCompromise]);
146//!
147//! let wrapper = builder.build_and_sign().unwrap();
148//! // to save crl as pem use the helper function
149//! //  wrapper.save_as_pem("./certs", "crl.pem").expect("failed to save crl as pem file");
150//!
151//! // use the wrapper to check sign, revocations
152//! let result = wrapper.verify_signature(ca.x509.public_key().as_ref().unwrap());
153//! assert!(result.unwrap());
154//! let is_revoked = wrapper.revoked(revocked.x509.serial_number());
155//! assert!(is_revoked);
156//! ```
157//!
158//! ## Config
159//!
160//! Values that can be selected for building a certificate
161//! | keyword | description | options |
162//! | ----------------- | --------------------------------------------------------------------------- | ----------------------------------- |
163//! | common_name | the common name this certificate shoud have, mandatory field | string: www.foo.se |
164//! | key_type  | key type to be used, defaults to RSA2048 | enum: RSA2048, RSA4096, P224, P256, P384, P512, Ed25519 |
165//! | ca | is this certificate used to sign other certificates, default value is false | boolean: true or false |
166//! | country_name | the country code to use,must follow the standard defined by ISO 3166-1 alpha-2. | string: SE |
167//! | organization | organisation name | string: test |
168//! | state_province | some name | string: test |
169//! | locality_time | Stockholm | string: Stockholm |
170//! | alternative_names | list of alternative DNS names this certificate is valid for | string: valid dns names |
171//! | signature_alg | which algorithm to be used for signature, default is SHA256 | enum: SHA1, SHA256, SHA384, SHA512 |
172//! | valid_from | Start date then the certificate is valid, default is now | string: 2010-01-01 |
173//! | valid_to | End date then the certificate is not valid, default is 1 year | string: 2020-01-01 |
174//! | usage | Key usage to add to the certificates, see list below for options | list of enums, defined in Key Usage table |
175//!
176//! ### Key usage
177//!
178//! If CA is true the key usages to sign certificates and crl lists are added automatically.
179//!
180//! | keyword           | description                                                |
181//! | ----------------- | ---------------------------------------------------------- |
182//! | certsign          | allowed to sign certificates                               |
183//! | crlsign           | allowed to sign crl                                        |
184//! | encipherment      | allowed to enciphering private or secret keys              |
185//! | clientauth        | allowed to authenticate as client                          |
186//! | serverauth        | allowed ot be used for server authenthication              |
187//! | signature         | allowed to perfom digital signature (For auth)             |
188//! | contentcommitment | allowed to perfom document signature (prev non repudation) |
189
190pub mod certificate;
191pub mod crl;