Skip to content

Commit

Permalink
Merge pull request #139 from RustCrypto/pkcs1-v0.3+pkcs8-v0.8
Browse files Browse the repository at this point in the history
  • Loading branch information
dignifiedquire authored Jan 17, 2022
2 parents 2d68db2 + e4366a7 commit 6717592
Show file tree
Hide file tree
Showing 8 changed files with 85 additions and 38 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ jobs:
strategy:
matrix:
rust:
- 1.51.0
- 1.56.0
- stable
- nightly
target:
Expand All @@ -36,7 +36,7 @@ jobs:
target: x86_64-unknown-linux-gnu
args: --no-default-features --features=std
exclude:
- rust: 1.51.0
- rust: 1.56.0
target: thumbv7m-none-eabi

steps:
Expand Down
6 changes: 3 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ rand = { version = "0.8.0", features = ["std_rng"], default-features = false }
byteorder = { version = "1.3.1", default-features = false }
subtle = { version = "2.1.1", default-features = false }
digest = { version = "0.10.0", default-features = false }
pkcs1 = { version = "0.2.3", default-features = false }
pkcs8 = { version = "0.7.5", default-features = false }
pkcs1 = { version = "0.3.3", default-features = false, features = ["pkcs8"] }
pkcs8 = { version = "0.8", default-features = false }

[dependencies.zeroize]
version = ">=1, <1.5" # zeroize 1.4 is MSRV 1.51+
Expand Down Expand Up @@ -59,7 +59,7 @@ nightly = ["subtle/nightly", "num-bigint/nightly"]
serde = ["num-bigint/serde", "serde_crate"]
expose-internals = []
std = ["alloc", "digest/std", "pkcs1/std", "pkcs8/std", "rand/std"]
alloc = ["digest/alloc", "pkcs1/alloc", "pkcs8/alloc", "pkcs8/pkcs1"]
alloc = ["digest/alloc", "pkcs1/alloc", "pkcs8/alloc"]
pem = ["alloc", "pkcs1/pem", "pkcs8/pem"]
pkcs5 = ["pkcs8/encryption"]

Expand Down
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
[![crates.io][crate-image]][crate-link]
[![Documentation][doc-image]][doc-link]
[![Build Status][build-image]][build-link]
![minimum rustc 1.51][msrv-image]
![minimum rustc 1.56][msrv-image]
[![Project Chat][chat-image]][chat-link]
[![dependency status][deps-image]][deps-link]

Expand Down Expand Up @@ -71,7 +71,7 @@ There will be three phases before `1.0` 🚢 can be released.
## Minimum Supported Rust Version (MSRV)
All crates in this repository support Rust 1.51 or higher. In future
All crates in this repository support Rust 1.56 or higher. In future
minimally supported version of Rust can be changed, but it will be done with
a minor version bump.
Expand All @@ -98,7 +98,7 @@ dual licensed as above, without any additional terms or conditions.
[doc-link]: https://docs.rs/rsa
[build-image]: https://github.com/rustcrypto/RSA/workflows/CI/badge.svg
[build-link]: https://github.com/RustCrypto/RSA/actions?query=workflow%3ACI+branch%3Amaster
[msrv-image]: https://img.shields.io/badge/rustc-1.51+-blue.svg
[msrv-image]: https://img.shields.io/badge/rustc-1.56+-blue.svg
[chat-image]: https://img.shields.io/badge/zulip-join_chat-blue.svg
[chat-link]: https://rustcrypto.zulipchat.com/#narrow/stream/260047-RSA
[deps-image]: https://deps.rs/repo/github/RustCrypto/RSA/status.svg
Expand Down
82 changes: 63 additions & 19 deletions src/encoding.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,41 @@
//! PKCS#1 encoding support
//! PKCS#1 and PKCS#8 encoding support.
//!
//! Note: PKCS#1 support is achieved through a blanket impl of the
//! `pkcs1` crate's traits for types which impl the `pkcs8` crate's traits.

use crate::{key::PublicKeyParts, BigUint, RsaPrivateKey, RsaPublicKey};
use core::convert::{TryFrom, TryInto};
use num_bigint::ModInverse;
use pkcs1::{
FromRsaPrivateKey, FromRsaPublicKey, RsaPrivateKeyDocument, RsaPublicKeyDocument,
ToRsaPrivateKey, ToRsaPublicKey,
use pkcs8::{
DecodePrivateKey, DecodePublicKey, EncodePrivateKey, EncodePublicKey, PrivateKeyDocument,
PublicKeyDocument,
};
use zeroize::Zeroizing;

impl FromRsaPrivateKey for RsaPrivateKey {
fn from_pkcs1_private_key(pkcs1_key: pkcs1::RsaPrivateKey<'_>) -> pkcs1::Result<Self> {
/// Verify that the `AlgorithmIdentifier` for a key is correct.
fn verify_algorithm_id(algorithm: &pkcs8::AlgorithmIdentifier) -> pkcs8::spki::Result<()> {
algorithm.assert_algorithm_oid(pkcs1::ALGORITHM_OID)?;

if algorithm.parameters_any()? != pkcs8::der::asn1::Null.into() {
return Err(pkcs8::spki::Error::KeyMalformed);
}

Ok(())
}

impl TryFrom<pkcs8::PrivateKeyInfo<'_>> for RsaPrivateKey {
type Error = pkcs8::Error;

fn try_from(private_key_info: pkcs8::PrivateKeyInfo<'_>) -> pkcs8::Result<Self> {
verify_algorithm_id(&private_key_info.algorithm)?;

let pkcs1_key = pkcs1::RsaPrivateKey::try_from(private_key_info.private_key)?;

// Multi-prime RSA keys not currently supported
if pkcs1_key.version() != pkcs1::Version::TwoPrime {
return Err(pkcs1::Error::Version.into());
}

let n = BigUint::from_bytes_be(pkcs1_key.modulus.as_bytes());
let e = BigUint::from_bytes_be(pkcs1_key.public_exponent.as_bytes());
let d = BigUint::from_bytes_be(pkcs1_key.private_exponent.as_bytes());
Expand All @@ -20,19 +46,28 @@ impl FromRsaPrivateKey for RsaPrivateKey {
}
}

impl FromRsaPublicKey for RsaPublicKey {
fn from_pkcs1_public_key(pkcs1_key: pkcs1::RsaPublicKey<'_>) -> pkcs1::Result<Self> {
impl DecodePrivateKey for RsaPrivateKey {}

impl TryFrom<pkcs8::SubjectPublicKeyInfo<'_>> for RsaPublicKey {
type Error = pkcs8::spki::Error;

fn try_from(spki: pkcs8::SubjectPublicKeyInfo<'_>) -> pkcs8::spki::Result<Self> {
verify_algorithm_id(&spki.algorithm)?;

let pkcs1_key = pkcs1::RsaPublicKey::try_from(spki.subject_public_key)?;
let n = BigUint::from_bytes_be(pkcs1_key.modulus.as_bytes());
let e = BigUint::from_bytes_be(pkcs1_key.public_exponent.as_bytes());
RsaPublicKey::new(n, e).map_err(|_| pkcs1::Error::Crypto)
Ok(RsaPublicKey::new(n, e).map_err(|_| pkcs8::spki::Error::KeyMalformed)?)
}
}

impl ToRsaPrivateKey for RsaPrivateKey {
fn to_pkcs1_der(&self) -> pkcs1::Result<RsaPrivateKeyDocument> {
impl DecodePublicKey for RsaPublicKey {}

impl EncodePrivateKey for RsaPrivateKey {
fn to_pkcs8_der(&self) -> pkcs8::Result<PrivateKeyDocument> {
// Check if the key is multi prime
if self.primes.len() > 2 {
return Err(pkcs1::Error::Version);
return Err(pkcs1::Error::Version.into());
}

let modulus = self.n().to_bytes_be();
Expand All @@ -50,8 +85,7 @@ impl ToRsaPrivateKey for RsaPrivateKey {
.1,
);

Ok(pkcs1::RsaPrivateKey {
version: pkcs1::Version::TwoPrime,
let private_key = pkcs1::RsaPrivateKey {
modulus: pkcs1::UIntBytes::new(&modulus)?,
public_exponent: pkcs1::UIntBytes::new(&public_exponent)?,
private_exponent: pkcs1::UIntBytes::new(&private_exponent)?,
Expand All @@ -60,19 +94,29 @@ impl ToRsaPrivateKey for RsaPrivateKey {
exponent1: pkcs1::UIntBytes::new(&exponent1)?,
exponent2: pkcs1::UIntBytes::new(&exponent2)?,
coefficient: pkcs1::UIntBytes::new(&coefficient)?,
other_prime_infos: None,
}
.to_der())
.to_der()?;

pkcs8::PrivateKeyInfo::new(pkcs1::ALGORITHM_ID, private_key.as_ref()).to_der()
}
}

impl ToRsaPublicKey for RsaPublicKey {
fn to_pkcs1_der(&self) -> pkcs1::Result<RsaPublicKeyDocument> {
impl EncodePublicKey for RsaPublicKey {
fn to_public_key_der(&self) -> pkcs8::spki::Result<PublicKeyDocument> {
let modulus = self.n().to_bytes_be();
let public_exponent = self.e().to_bytes_be();
Ok(pkcs1::RsaPublicKey {

let subject_public_key = pkcs1::RsaPublicKey {
modulus: pkcs1::UIntBytes::new(&modulus)?,
public_exponent: pkcs1::UIntBytes::new(&public_exponent)?,
}
.to_der())
.to_der()?;

pkcs8::SubjectPublicKeyInfo {
algorithm: pkcs1::ALGORITHM_ID,
subject_public_key: subject_public_key.as_ref(),
}
.try_into()
}
}
5 changes: 4 additions & 1 deletion src/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -514,7 +514,10 @@ impl RsaPrivateKey {
/// Check that the public key is well formed and has an exponent within acceptable bounds.
#[inline]
pub fn check_public(public_key: &impl PublicKeyParts) -> Result<()> {
let public_key = public_key.e().to_u64().ok_or(Error::PublicExponentTooLarge)?;
let public_key = public_key
.e()
.to_u64()
.ok_or(Error::PublicExponentTooLarge)?;

if public_key < MIN_PUB_EXPONENT {
return Err(Error::PublicExponentTooSmall);
Expand Down
4 changes: 2 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! # #[cfg(feature = "pem")]
//! # {
//! use rsa::{RsaPublicKey, pkcs1::FromRsaPublicKey};
//! use rsa::{RsaPublicKey, pkcs1::DecodeRsaPublicKey};
//!
//! let pem = "-----BEGIN RSA PUBLIC KEY-----
//! MIIBCgKCAQEAtsQsUV8QpqrygsY+2+JCQ6Fw8/omM71IM2N/R8pPbzbgOl0p78MZ
Expand Down Expand Up @@ -127,7 +127,7 @@
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! # #[cfg(feature = "pem")]
//! # {
//! use rsa::{RsaPublicKey, pkcs8::FromPublicKey};
//! use rsa::{RsaPublicKey, pkcs8::DecodePublicKey};
//!
//! let pem = "-----BEGIN PUBLIC KEY-----
//! MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtsQsUV8QpqrygsY+2+JC
Expand Down
10 changes: 5 additions & 5 deletions tests/pkcs1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

use hex_literal::hex;
use rsa::{
pkcs1::{FromRsaPrivateKey, FromRsaPublicKey, ToRsaPrivateKey, ToRsaPublicKey},
pkcs1::{DecodeRsaPrivateKey, DecodeRsaPublicKey, EncodeRsaPrivateKey, EncodeRsaPublicKey},
PublicKeyParts, RsaPrivateKey, RsaPublicKey,
};

Expand Down Expand Up @@ -170,30 +170,30 @@ fn decode_rsa4096_pub_pem() {
#[cfg(feature = "pem")]
fn encode_rsa2048_priv_pem() {
let key = RsaPrivateKey::from_pkcs1_pem(RSA_2048_PRIV_PEM).unwrap();
let pem = key.to_pkcs1_pem().unwrap();
let pem = key.to_pkcs1_pem(Default::default()).unwrap();
assert_eq!(&*pem, RSA_2048_PRIV_PEM)
}

#[test]
#[cfg(feature = "pem")]
fn encode_rsa4096_priv_pem() {
let key = RsaPrivateKey::from_pkcs1_pem(RSA_4096_PRIV_PEM).unwrap();
let pem = key.to_pkcs1_pem().unwrap();
let pem = key.to_pkcs1_pem(Default::default()).unwrap();
assert_eq!(&*pem, RSA_4096_PRIV_PEM)
}

#[test]
#[cfg(feature = "pem")]
fn encode_rsa2048_pub_pem() {
let key = RsaPublicKey::from_pkcs1_pem(RSA_2048_PUB_PEM).unwrap();
let pem = key.to_pkcs1_pem().unwrap();
let pem = key.to_pkcs1_pem(Default::default()).unwrap();
assert_eq!(&*pem, RSA_2048_PUB_PEM)
}

#[test]
#[cfg(feature = "pem")]
fn encode_rsa4096_pub_pem() {
let key = RsaPublicKey::from_pkcs1_pem(RSA_4096_PUB_PEM).unwrap();
let pem = key.to_pkcs1_pem().unwrap();
let pem = key.to_pkcs1_pem(Default::default()).unwrap();
assert_eq!(&*pem, RSA_4096_PUB_PEM)
}
6 changes: 3 additions & 3 deletions tests/pkcs8.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const RSA_2048_PUB_PEM: &str = include_str!("examples/pkcs8/rsa2048-pub.pem");

use hex_literal::hex;
use rsa::{
pkcs8::{FromPrivateKey, FromPublicKey, ToPrivateKey, ToPublicKey},
pkcs8::{DecodePrivateKey, DecodePublicKey, EncodePrivateKey, EncodePublicKey},
PublicKeyParts, RsaPrivateKey, RsaPublicKey,
};

Expand Down Expand Up @@ -84,14 +84,14 @@ fn decode_rsa2048_pub_pem() {
#[cfg(feature = "pem")]
fn encode_rsa2048_priv_pem() {
let key = RsaPrivateKey::from_pkcs8_pem(RSA_2048_PRIV_PEM).unwrap();
let pem = key.to_pkcs8_pem().unwrap();
let pem = key.to_pkcs8_pem(Default::default()).unwrap();
assert_eq!(&*pem, RSA_2048_PRIV_PEM)
}

#[test]
#[cfg(feature = "pem")]
fn encode_rsa2048_pub_pem() {
let key = RsaPublicKey::from_public_key_pem(RSA_2048_PUB_PEM).unwrap();
let pem = key.to_public_key_pem().unwrap();
let pem = key.to_public_key_pem(Default::default()).unwrap();
assert_eq!(&*pem, RSA_2048_PUB_PEM)
}

0 comments on commit 6717592

Please sign in to comment.