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

Add support for HS384, HS512, RS384, RS512, and ES384 #11

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
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: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
/target
Cargo.lock
Cargo.lock
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this removal of the newline before EOF intentional?

2 changes: 1 addition & 1 deletion .rustfmt.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ fn_single_line = false
where_single_line = false
imports_indent = "Block"
imports_layout = "Mixed"
merge_imports = true
imports_granularity="Crate"
reorder_imports = true
reorder_modules = true
reorder_impl_items = false
Expand Down
16 changes: 8 additions & 8 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,23 +13,23 @@ edition = "2018"
base64 = "0.13"
bitflags = "1.2"
generic-array = "0.14"
jsonwebtoken = { version = "8.0", optional = true }
num-bigint = { version = "0.4", optional = true }
p256 = { version = "0.9", optional = true, features = ["arithmetic"] }
rand = { version = "0.8", optional = true }
serde = { version = "1.0", features = ["derive"] }
jsonwebtoken = { version = "8.1", optional = true }
num-bigint = { version = "0.4", optional = true }
p256 = { version = "0.10", optional = true, features = ["arithmetic"] }
rand = { version = "0.8", optional = true }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
thiserror = "1.0"
yasna = { version = "0.4", optional = true, features = ["num-bigint"] }
zeroize = { version = "1.4", features = ["zeroize_derive"] }
yasna = { version = "0.5", optional = true, features = ["num-bigint"] }
zeroize = { version = "1.4", features = ["zeroize_derive"] }

[features]
pkcs-convert = ["num-bigint", "yasna"]
jwt-convert = ["pkcs-convert", "jsonwebtoken"]
generate = ["p256", "rand"]

[dev-dependencies]
jsonwebtoken = "8.0"
jsonwebtoken = "8.1"

[package.metadata.docs.rs]
all-features = true
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

tl;dr: get keys into a format that can be used by other crates; be as safe as possible while doing so.

- Serialization and deserialization of _Required_ and _Recommended_ key types (HS256, RS256, ES256)
- Serialization and deserialization of _Required_ and _Recommended_ key types (HS256, HS384, HS512 RS256, RS384, RS512, ES256, ES384)
- Conversion to PEM for interop with existing JWT libraries (e.g., [jsonwebtoken](https://crates.io/crates/jsonwebtoken))
- Key generation (particularly useful for testing)

Expand Down
90 changes: 84 additions & 6 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ mod utils;

use std::{borrow::Cow, fmt};

use generic_array::typenum::U32;
use generic_array::typenum::{U32, U48};
use serde::{Deserialize, Serialize};

pub use byte_array::ByteArray;
Expand Down Expand Up @@ -164,8 +164,18 @@ impl JsonWebKey {
curve: Curve::P256 { .. },
},
)
| (
ES384,
EC {
curve: Curve::P384 { .. },
},
)
| (RS256, RSA { .. })
| (RS384, RSA { .. })
| (RS512, RSA { .. })
| (HS256, Symmetric { .. }) => Ok(()),
(HS384, Symmetric { .. }) => Ok(()),
(HS512, Symmetric { .. }) => Ok(()),
_ => Err(Error::MismatchedAlgorithm),
}
}
Expand Down Expand Up @@ -230,6 +240,10 @@ impl Key {
curve: Curve::P256 { d: Some(_), .. },
..
}
| Self::EC {
curve: Curve::P384 { d: Some(_), .. },
..
}
| Self::RSA {
private: Some(_),
..
Expand All @@ -253,6 +267,15 @@ impl Key {
d: None,
},
},
Self::EC {
curve: Curve::P384 { x, y, .. },
} => Self::EC {
curve: Curve::P384 {
x: x.clone(),
y: y.clone(),
d: None,
},
},
Self::RSA { public, .. } => Self::RSA {
public: public.clone(),
private: None,
Expand Down Expand Up @@ -307,6 +330,34 @@ impl Key {
None => pkcs8::write_public(oids, write_public),
}
}
Self::EC {
curve: Curve::P384 { d, x, y },
} => {
let ec_public_oid = ObjectIdentifier::from_slice(&[1, 2, 840, 10045, 2, 1]);
let prime384v1_oid = ObjectIdentifier::from_slice(&[1, 3, 132, 0, 34]);
let oids = &[Some(&ec_public_oid), Some(&prime384v1_oid)];

let write_public = |writer: DERWriter<'_>| {
let public_bytes: Vec<u8> = [0x04 /* uncompressed */]
.iter()
.chain(x.iter())
.chain(y.iter())
.copied()
.collect();
writer.write_bitvec_bytes(&public_bytes, 8 * (48 * 2 + 1));
};

match d {
Some(private_point) => {
pkcs8::write_private(oids, |writer: &mut DERWriterSeq<'_>| {
writer.next().write_i8(1); // version
writer.next().write_bytes(&**private_point);
writer.next().write_tagged(Tag::context(1), write_public);
})
}
None => pkcs8::write_public(oids, write_public),
}
}
Self::RSA { public, private } => {
let rsa_encryption_oid = ObjectIdentifier::from_slice(&[
1, 2, 840, 113549, 1, 1, 1, // rsaEncryption
Expand Down Expand Up @@ -417,7 +468,7 @@ impl Key {
let sk = elliptic_curve::SecretKey::random(&mut rand::thread_rng());
let sk_scalar = p256::Scalar::from(&sk);

let pk = p256::ProjectivePoint::generator() * sk_scalar;
let pk = p256::ProjectivePoint::GENERATOR * sk_scalar;
let pk_bytes = &pk
.to_affine()
.to_encoded_point(false /* compress */)
Expand Down Expand Up @@ -448,13 +499,29 @@ pub enum Curve {
/// The curve point y coordinate.
y: ByteArray<U32>,
},
/// Parameters of the prime384v1 (P384) curve.
#[serde(rename = "P-384")]
P384 {
/// The private scalar.
#[serde(skip_serializing_if = "Option::is_none")]
d: Option<ByteArray<U48>>,
/// The curve point x coordinate.
x: ByteArray<U48>,
/// The curve point y coordinate.
y: ByteArray<U48>,
},
}

impl fmt::Debug for Curve {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::P256 { x, y, .. } => f
.debug_struct("Curve:P256")
.debug_struct("Curve::P256")
.field("x", x)
.field("y", y)
.finish(),
Self::P384 { x, y, .. } => f
.debug_struct("Curve::P384")
.field("x", x)
.field("y", y)
.finish(),
Expand Down Expand Up @@ -525,20 +592,25 @@ impl fmt::Debug for RsaPrivate {
}
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Hash)]
pub enum KeyUse {
#[serde(rename = "sig")]
Signing,
#[serde(rename = "enc")]
Encryption,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Hash)]
#[allow(clippy::upper_case_acronyms)]
pub enum Algorithm {
HS256,
HS384,
HS512,
RS256,
RS384,
RS512,
ES256,
ES384,
}

#[cfg(feature = "jwt-convert")]
Expand All @@ -549,8 +621,13 @@ const _IMPL_JWT_CONVERSIONS: () = {
fn from(alg: Algorithm) -> Self {
match alg {
Algorithm::HS256 => Self::HS256,
Algorithm::HS384 => Self::HS384,
Algorithm::HS512 => Self::HS512,
Algorithm::ES256 => Self::ES256,
Algorithm::ES384 => Self::ES384,
Algorithm::RS256 => Self::RS256,
Algorithm::RS384 => Self::RS384,
Algorithm::RS512 => Self::RS512,
}
}
}
Expand Down Expand Up @@ -590,7 +667,8 @@ const _IMPL_JWT_CONVERSIONS: () = {
.unwrap()
}
Self::RSA { .. } => {
jwt::DecodingKey::from_rsa_pem(self.to_pem().as_bytes()).unwrap()
jwt::DecodingKey::from_rsa_pem(self.to_public().unwrap().to_pem().as_bytes())
.unwrap()
}
}
}
Expand Down
Loading