Skip to content

Commit

Permalink
Expose PEM/DER decoder functions in KeyPair (#204)
Browse files Browse the repository at this point in the history
* Expose PEM/DER decoder functions in KeyPair

* Add feature gate
  • Loading branch information
baranyildirim authored Feb 6, 2024
1 parent 29030e0 commit df039b3
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
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

0 comments on commit df039b3

Please sign in to comment.