Add auto conversion for SEC1 EC keys to PKCS#8.

Fixes #386.
This commit is contained in:
Orne Brocaar 2024-03-27 09:50:18 +00:00
parent 286d8b33b2
commit 2c06edd6ff
3 changed files with 22 additions and 5 deletions

2
Cargo.lock generated
View File

@ -819,6 +819,7 @@ dependencies = [
"diesel-async",
"diesel_migrations",
"dotenv",
"elliptic-curve",
"email_address",
"futures",
"futures-util",
@ -839,6 +840,7 @@ dependencies = [
"mime_guess",
"oauth2",
"openidconnect",
"p256",
"pbjson-types",
"pbkdf2",
"petgraph",

View File

@ -105,6 +105,8 @@ rustls = "0.22"
rustls-native-certs = "0.7"
rustls-pemfile = "2.1"
rsa = "0.9"
elliptic-curve = { version = "0.13", features = ["pem"] }
p256 = "0.13"
rcgen = { version = "0.12", features = [ "x509-parser" ] }
openidconnect = { version = "3.5", features = ["accept-rfc3339-timestamps"] }
oauth2 = "4.4"

View File

@ -4,11 +4,6 @@ use anyhow::{Context, Result};
use rcgen::{
Certificate, CertificateParams, DnType, ExtendedKeyUsagePurpose, KeyPair, KeyUsagePurpose,
};
use rsa::{
pkcs1::DecodeRsaPrivateKey,
pkcs8::{EncodePrivateKey, LineEnding},
RsaPrivateKey,
};
use tokio::fs;
use uuid::Uuid;
@ -100,9 +95,27 @@ pub async fn client_cert_for_application_id(
fn private_key_to_pkcs8(pem: &str) -> Result<String> {
if pem.contains("RSA PRIVATE KEY") {
use rsa::{
pkcs1::DecodeRsaPrivateKey,
pkcs8::{EncodePrivateKey, LineEnding},
RsaPrivateKey,
};
let pkey = RsaPrivateKey::from_pkcs1_pem(pem).context("Read RSA PKCS#1")?;
let pkcs8_pem = pkey.to_pkcs8_pem(LineEnding::default())?;
Ok(pkcs8_pem.as_str().to_owned())
} else if pem.contains("EC PRIVATE KEY") {
use elliptic_curve::{
pkcs8::{EncodePrivateKey, LineEnding},
SecretKey,
};
// We assume it is a P256 based secret-key, which is the most popular curve.
// Attempting to decode it as P256 is still better than just failing to read it.
let pkey: SecretKey<p256::NistP256> =
SecretKey::from_sec1_pem(pem).context("Read EC SEC1")?;
let pkcs8_pem = pkey.to_pkcs8_pem(LineEnding::default())?;
Ok(pkcs8_pem.as_str().to_owned())
} else {
Ok(pem.to_string())
}