How do I use a self-signed certificate from rcgen with native-tls Identity?

Viewed 56

I need to generate a (very) short-lived native_tls::TlsStream for one-shot TLS communication over localhost.

Ideally the application can use a temporary native_tls::Identity built from a self-signed certificate generated using rcgen which can be used to configure a native_tls::Acceptor as follows:

// main.rs
fn main() {
    let test_certificate = rcgen::generate_simple_self_signed(["localhost".to_string()]).unwrap();

    // Serialises the certificate to ASCII PEM, does that conflict with PKCS#8?
    // rcgen does not expose a PKCS#8 equivalent that I could find:
    let pem = test_certificate.serialize_pem().unwrap();

    // Serialises to PKCS#8 format in PEM
    let pkey = test_certificate.get_key_pair().serialize_pem();

    // Use to generate native_tls::Identity
    let identity = native_tls::Identity::from_pkcs8(pem.as_bytes(), pkey.as_bytes()).unwrap();

    /* 
    Panics:
    Os { code: -2146881269, kind: Uncategorized, message: "ASN1 bad tag value met." }
    */
}
# cargo.toml
# ...
[dependencies]
rcgen = "0.9"
native-tls = "0.2.10"

As indicated, an ASN1 bad tag value met is raised by the OS when trying to use the certificate and private key. (Operating system is Windows 11)

What is the root of the problem here? Is it:

  • An incorrect use of rcgen and native_tls::Identity:?
  • rcgen cannot generate a self-signed certificate and private key that native-tls can use?
  • rcgen serialises the certificate and private key into a format that native-tls cannot use?
  • native_tls::Identity: cannot use self-signed certificates as generated by rcgen (It can use a pkcs12 self signed cert generated with the openssl cli)?

Is there an alternative crate that can be used to generate a native-tls compatible self-signed certificate? Is there a more idiomatic way to set up a short-lived TlsStream?

0 Answers
Related