Skip to content

Commit

Permalink
Add example of generating a cert chain
Browse files Browse the repository at this point in the history
Generate two certficates and sign the second with the first. Addresses
  • Loading branch information
tbro committed Oct 9, 2023
1 parent 948c3b5 commit c5e20fe
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ required-features = ["pem"]
name = "rsa-irc-openssl"
required-features = ["pem"]

[[example]]
name = "sign-leaf-with-ca"
required-features = ["x509-parser"]

[dependencies]
yasna = { version = "0.5.2", features = ["time", "std"] }
ring = "0.17"
Expand Down
33 changes: 33 additions & 0 deletions examples/sign-leaf-with-ca.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
use rcgen::{BasicConstraints, Certificate, CertificateParams, IsCa};
use std::fs;

fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut ca_params: CertificateParams = Default::default();
let mut leaf_params: CertificateParams = Default::default();
ca_params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
leaf_params.is_ca = IsCa::NoCa;
let ca_cert = Certificate::from_params(ca_params)?;
let leaf_cert = Certificate::from_params(leaf_params)?;

// in order to sign leaf certificate we pass the ca cert in when
// serializing
let leaf_serialized = leaf_cert.serialize_pem_with_signer(&ca_cert)?;
let ca_serialized = ca_cert.serialize_pem()?;

println!("{ca_serialized}");
println!("{leaf_serialized}");
println!("{}", leaf_cert.serialize_private_key_pem());
std::fs::create_dir_all("certs/")?;
fs::write("certs/root-ca.pem", &ca_serialized.as_bytes())?;
fs::write(
"certs/root-ca.key.pem",
&ca_cert.serialize_private_key_pem(),
)?;
fs::write("certs/cert.pem", &leaf_serialized.as_bytes())?;
fs::write(
"certs/key.pem",
&leaf_cert.serialize_private_key_pem().as_bytes(),
)?;
fs::write("certs/key.der", &leaf_cert.serialize_private_key_der())?;
Ok(())
}

0 comments on commit c5e20fe

Please sign in to comment.