Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Expose PEM/DER decoder functions in KeyPair #204

Merged
merged 2 commits into from
Feb 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions biscuit-auth/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
33 changes: 32 additions & 1 deletion biscuit-auth/src/crypto/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -39,6 +42,34 @@ impl KeyPair {
}
}

#[cfg(feature = "pem")]
pub fn from_private_key_der(bytes: &[u8]) -> Result<Self, error::Format> {
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<Self, error::Format> {
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<Path>) -> Result<Self, error::Format> {
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<Path>) -> Result<Self, error::Format> {
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)
Expand Down
Loading