Skip to content

Instantly share code, notes, and snippets.

@miquels
Created August 9, 2018 16:00
Show Gist options
  • Save miquels/26143490a505c5f338687be63b1da95c to your computer and use it in GitHub Desktop.
Save miquels/26143490a505c5f338687be63b1da95c to your computer and use it in GitHub Desktop.
native_tls::TlsAcceptor from .key/.crt PEM files instead of .p12 file.
use std::io::{self,Error,ErrorKind};
use std::path::Path;
use openssl::pkey::PKey;
use openssl::x509::X509;
use openssl::pkcs12::Pkcs12;
use openssl::stack::Stack;
use native_tls::{self,Identity};
fn read_pems(key: impl AsRef<Path>, cert: impl AsRef<Path>, password: &str) -> io::Result<Vec<u8>> {
let b = std::fs::read_to_string(key)?;
let pkey = if password.len() > 0 {
PKey::private_key_from_pem_passphrase(b.as_bytes(), password.as_bytes())
} else {
PKey::private_key_from_pem(b.as_bytes())
}?;
let b = std::fs::read_to_string(cert)?;
let mut certs = X509::stack_from_pem(b.as_bytes())?;
let cert = certs.remove(0);
let mut stack = Stack::<X509>::new().unwrap();
certs.into_iter().for_each(|x| stack.push(x).unwrap());
let mut builder = Pkcs12::builder();
builder.ca(stack);
let nickname = "certfile";
let pkcs12 = builder.build("", nickname, &pkey, &cert)?;
Ok(pkcs12.to_der()?)
}
pub fn acceptor_from_pem_files(key: impl AsRef<Path>, cert: impl AsRef<Path>, password: &str) -> io::Result<native_tls::TlsAcceptor> {
let der = read_pems(key, cert, password)?;
let cert = Identity::from_pkcs12(&der, "").map_err(|e| Error::new(ErrorKind::Other, e))?;
native_tls::TlsAcceptor::builder(cert).build().map_err(|e| Error::new(ErrorKind::Other, e))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment