diff --git a/biscuit-auth/Cargo.toml b/biscuit-auth/Cargo.toml index 362fe0dd..a78bde15 100644 --- a/biscuit-auth/Cargo.toml +++ b/biscuit-auth/Cargo.toml @@ -24,6 +24,8 @@ datalog-macro = ["biscuit-quote"] bwk = ["chrono", "serde"] docsrs = [] uuid = ["dep:uuid"] +# used to expose pem/der loaders for keypairs +pem = ["ed25519-dalek/pem"] [dependencies] rand_core = "^0.6" diff --git a/biscuit-auth/src/crypto/mod.rs b/biscuit-auth/src/crypto/mod.rs index 9cfa0fff..37873ff9 100644 --- a/biscuit-auth/src/crypto/mod.rs +++ b/biscuit-auth/src/crypto/mod.rs @@ -10,10 +10,13 @@ use crate::{error::Format, format::schema}; use super::error; +#[cfg(feature = "pem")] +use ed25519_dalek::pkcs8::DecodePrivateKey; use ed25519_dalek::*; + use nom::Finish; use rand_core::{CryptoRng, RngCore}; -use std::{convert::TryInto, fmt::Display, hash::Hash, ops::Drop, str::FromStr}; +use std::{convert::TryInto, fmt::Display, hash::Hash, ops::Drop, path::Path, str::FromStr}; use zeroize::Zeroize; /// pair of cryptographic keys used to sign a token's block @@ -39,6 +42,34 @@ impl KeyPair { } } + #[cfg(feature = "pem")] + pub fn from_private_key_der(bytes: &[u8]) -> Result { + let kp = SigningKey::from_pkcs8_der(bytes) + .map_err(|e| error::Format::InvalidKey(e.to_string()))?; + Ok(KeyPair { kp }) + } + + #[cfg(feature = "pem")] + pub fn from_private_key_pem(str: &str) -> Result { + let kp = SigningKey::from_pkcs8_pem(str) + .map_err(|e| error::Format::InvalidKey(e.to_string()))?; + Ok(KeyPair { kp }) + } + + #[cfg(feature = "pem")] + pub fn from_private_key_der_file(path: impl AsRef) -> Result { + let kp = SigningKey::read_pkcs8_der_file(path) + .map_err(|e| error::Format::InvalidKey(e.to_string()))?; + Ok(KeyPair { kp }) + } + + #[cfg(feature = "pem")] + pub fn from_private_key_pem_file(path: impl AsRef) -> Result { + let kp = SigningKey::read_pkcs8_pem_file(path) + .map_err(|e| error::Format::InvalidKey(e.to_string()))?; + Ok(KeyPair { kp }) + } + pub fn private(&self) -> PrivateKey { let secret = self.kp.to_bytes(); PrivateKey(secret)