Skip to content

Commit

Permalink
No-std support
Browse files Browse the repository at this point in the history
  • Loading branch information
roblabla committed Jun 11, 2020
1 parent 02689d1 commit 9d171a6
Show file tree
Hide file tree
Showing 13 changed files with 87 additions and 47 deletions.
2 changes: 2 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ matrix:
script:
- if [[ "$TRAVIS_NIGHTLY" == "true" ]]; then cargo test --verbose --all-features; fi
- if [[ "$TRAVIS_NIGHTLY" == "true" ]]; then cargo bench --verbose --all-features --no-run; fi
- if [[ "$TRAVIS_NIGHTLY" == "true" ]]; then rustup target add thumbv7m-none-eabi; fi
- if [[ "$TRAVIS_NIGHTLY" == "true" ]]; then cargo build --verbose --no-default-features --target thumbv7m-none-eabi; fi
- if [[ "$TRAVIS_NIGHTLY" != "true" ]]; then cargo test --verbose; fi

cache: cargo
32 changes: 16 additions & 16 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,17 @@ categories = ["cryptography"]
readme = "README.md"

[dependencies]
num-bigint = { version = "0.6", features = ["rand", "i128", "u64_digit", "prime", "zeroize"], package = "num-bigint-dig" }
num-traits = "0.2.6"
num-integer = "0.1.39"
num-iter = "0.1.37"
lazy_static = "1.3.0"
rand = "0.7.0"
byteorder = "1.3.1"
thiserror = "1.0.11"
subtle = "2.0.0"
simple_asn1 = "0.4"
num-bigint = { version = "0.6", features = ["i128", "u64_digit", "prime", "zeroize"], default-features = false, package = "num-bigint-dig" }
num-traits = { version= "0.2.9", default-features = false, features = ["libm"] }
num-integer = { version = "0.1.39", default-features = false }
num-iter = { version = "0.1.37", default-features = false }
lazy_static = { version = "1.3.0", features = ["spin_no_std"] }
rand = { version = "0.7.0", default-features = false }
byteorder = { version = "1.3.1", default-features = false }
subtle = { version = "2.0.0", default-features = false }
simple_asn1 = { version = "0.4", optional = true }
pem = { version = "0.8", optional = true }
digest = { version = "0.9.0", features = ["std"] }
sha2 = "0.9.0"
digest = { version = "0.9.0", default-features = false }

[dependencies.zeroize]
version = "1.1.0"
Expand All @@ -35,16 +33,16 @@ package = "serde"
optional = true
version = "1.0.89"
default-features = false
features = ["std", "derive"]
features = ["derive"]

[dev-dependencies]
base64 = "0.12.0"
hex = "0.4.0"
serde_test = "1.0.89"
rand_xorshift = "0.2.0"
pem = "0.8"
sha-1 = "0.9.0"
sha3 = "0.9.0"
#sha-1 = "0.9.0"
#sha3 = "0.9.0"

[[bench]]
name = "key"
Expand All @@ -56,8 +54,10 @@ name = "key"
# debug = true

[features]
default = ["pem"]
default = ["std", "pem"]
nightly = ["subtle/nightly", "num-bigint/nightly"]
serde = ["num-bigint/serde", "serde_crate"]
serde1 = ["serde"] # deprecated
expose-internals = []
std = ["alloc", "simple_asn1", "digest/std"]
alloc = ["digest/alloc"]
5 changes: 4 additions & 1 deletion src/algorithms.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ use digest::DynDigest;
use num_bigint::traits::ModInverse;
use num_bigint::{BigUint, RandPrime};
use num_traits::{FromPrimitive, One, Zero};
#[cfg(not(feature = "std"))]
use num_traits::{Float};
use rand::Rng;
use alloc::vec;

use crate::errors::{Error, Result};
use crate::key::RSAPrivateKey;
Expand Down Expand Up @@ -119,7 +122,7 @@ pub fn mgf1_xor(out: &mut [u8], digest: &mut dyn DynDigest, seed: &[u8]) {
let mut counter = [0u8; 4];
let mut i = 0;

const MAX_LEN: u64 = std::u32::MAX as u64 + 1;
const MAX_LEN: u64 = core::u32::MAX as u64 + 1;
assert!(out.len() as u64 <= MAX_LEN);

while i < out.len() {
Expand Down
47 changes: 28 additions & 19 deletions src/errors.rs
Original file line number Diff line number Diff line change
@@ -1,40 +1,49 @@
use thiserror::Error;
use alloc::string::String;

pub type Result<T> = ::std::result::Result<T, Error>;
pub type Result<T> = core::result::Result<T, Error>;

/// Error types
#[derive(Debug, Error)]
#[derive(Debug)]
pub enum Error {
#[error("invalid padding scheme")]
InvalidPaddingScheme,
#[error("decryption error")]
Decryption,
#[error("verification error")]
Verification,
#[error("message too long")]
MessageTooLong,
#[error("input must be hashed")]
InputNotHashed,
#[error("nprimes must be >= 2")]
NprimesTooSmall,
#[error("too few primes of given length to generate an RSA key")]
TooFewPrimes,
#[error("invalid prime value")]
InvalidPrime,
#[error("invalid modulus")]
InvalidModulus,
#[error("invalid exponent")]
InvalidExponent,
#[error("invalid coefficient")]
InvalidCoefficient,
#[error("public exponent too small")]
PublicExponentTooSmall,
#[error("public exponent too large")]
PublicExponentTooLarge,
#[error("parse error: {}", reason)]
ParseError { reason: String },
#[error("internal error")]
Internal,
#[error("label too long")]
LabelTooLong,
}

#[cfg(feature = "std")]
impl std::error::Error for Error {}
impl core::fmt::Display for Error {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
match self {
Error::InvalidPaddingScheme => write!(f, "invalid padding scheme"),
Error::Decryption => write!(f, "decryption error"),
Error::Verification => write!(f, "verification error"),
Error::MessageTooLong => write!(f, "message too long"),
Error::InputNotHashed => write!(f, "input must be hashed"),
Error::NprimesTooSmall => write!(f, "nprimes must be >= 2"),
Error::TooFewPrimes => write!(f, "too few primes of given length to generate an RSA key"),
Error::InvalidPrime => write!(f, "invalid prime value"),
Error::InvalidModulus => write!(f, "invalid modulus"),
Error::InvalidExponent => write!(f, "invalid exponent"),
Error::InvalidCoefficient => write!(f, "invalid coefficient"),
Error::PublicExponentTooSmall => write!(f, "public exponent too small"),
Error::PublicExponentTooLarge => write!(f, "public exponent too large"),
Error::ParseError { reason } => write!(f, "parse error: {}", reason),
Error::Internal => write!(f, "internal error"),
Error::LabelTooLong => write!(f, "label too long"),
}
}
}
4 changes: 3 additions & 1 deletion src/internals.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
use num_bigint::{BigInt, BigUint, IntoBigInt, IntoBigUint, ModInverse, RandBigInt, ToBigInt};
use num_traits::{One, Signed, Zero};
use rand::Rng;
use std::borrow::Cow;
use alloc::borrow::Cow;
use zeroize::Zeroize;
use alloc::vec::Vec;
use alloc::vec;

use crate::errors::{Error, Result};
use crate::key::{PublicKeyParts, RSAPrivateKey};
Expand Down
18 changes: 12 additions & 6 deletions src/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,12 @@ use num_bigint::traits::ModInverse;
use num_bigint::Sign::Plus;
use num_bigint::{BigInt, BigUint};
use num_traits::{FromPrimitive, One};
use rand::{rngs::ThreadRng, Rng};
use rand::{rngs::StdRng, Rng};
#[cfg(feature = "serde")]
use serde_crate::{Deserialize, Serialize};
use std::ops::Deref;
use core::ops::Deref;
use zeroize::Zeroize;
use alloc::vec::Vec;

use crate::algorithms::generate_multi_prime_key;
use crate::errors::{Error, Result};
Expand Down Expand Up @@ -247,6 +248,7 @@ impl RSAPublicKey {
/// let der_bytes = base64::decode(&der_encoded).expect("failed to decode base64 content");
/// let public_key = RSAPublicKey::from_pkcs1(&der_bytes).expect("failed to parse key");
/// ```
#[cfg(feature = "std")]
pub fn from_pkcs1(der: &[u8]) -> Result<RSAPublicKey> {
crate::parse::parse_public_key_pkcs1(der)
}
Expand Down Expand Up @@ -281,6 +283,7 @@ impl RSAPublicKey {
/// let der_bytes = base64::decode(&der_encoded).expect("failed to decode base64 content");
/// let public_key = RSAPublicKey::from_pkcs8(&der_bytes).expect("failed to parse key");
/// ```
#[cfg(feature = "std")]
pub fn from_pkcs8(der: &[u8]) -> Result<RSAPublicKey> {
crate::parse::parse_public_key_pkcs8(der)
}
Expand Down Expand Up @@ -393,6 +396,7 @@ impl RSAPrivateKey {
/// let der_bytes = base64::decode(&der_encoded).expect("failed to decode base64 content");
/// let private_key = RSAPrivateKey::from_pkcs1(&der_bytes).expect("failed to parse key");
/// ```
#[cfg(feature = "std")]
pub fn from_pkcs1(der: &[u8]) -> Result<RSAPrivateKey> {
crate::parse::parse_private_key_pkcs1(der)
}
Expand Down Expand Up @@ -433,6 +437,7 @@ impl RSAPrivateKey {
/// let der_bytes = base64::decode(&der_encoded).expect("failed to decode base64 content");
/// let private_key = RSAPrivateKey::from_pkcs8(&der_bytes).expect("failed to parse key");
/// ```
#[cfg(feature = "std")]
pub fn from_pkcs8(der: &[u8]) -> Result<RSAPrivateKey> {
crate::parse::parse_private_key_pkcs8(der)
}
Expand Down Expand Up @@ -542,10 +547,10 @@ impl RSAPrivateKey {
match padding {
// need to pass any Rng as the type arg, so the type checker is happy, it is not actually used for anything
PaddingScheme::PKCS1v15Encrypt => {
pkcs1v15::decrypt::<ThreadRng, _>(None, self, ciphertext)
pkcs1v15::decrypt::<StdRng, _>(None, self, ciphertext)
}
PaddingScheme::OAEP { mut digest, label } => {
oaep::decrypt::<ThreadRng, _>(None, self, ciphertext, &mut *digest, label)
oaep::decrypt::<StdRng, _>(None, self, ciphertext, &mut *digest, label)
}
_ => Err(Error::InvalidPaddingScheme),
}
Expand All @@ -572,14 +577,15 @@ impl RSAPrivateKey {
/// Sign the given digest.
pub fn sign(&self, padding: PaddingScheme, digest_in: &[u8]) -> Result<Vec<u8>> {
match padding {
// need to pass any Rng as the type arg, so the type checker is happy, it is not actually used for anything
PaddingScheme::PKCS1v15Sign { ref hash } => {
pkcs1v15::sign::<ThreadRng, _>(None, self, hash.as_ref(), digest_in)
pkcs1v15::sign::<StdRng, _>(None, self, hash.as_ref(), digest_in)
}
PaddingScheme::PSS {
mut salt_rng,
mut digest,
salt_len,
} => pss::sign::<_, ThreadRng, _>(
} => pss::sign::<_, StdRng, _>(
&mut *salt_rng,
None,
self,
Expand Down
7 changes: 7 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,12 @@
//! let dec_data = private_key.decrypt(padding, &enc_data).expect("failed to decrypt");
//! assert_eq!(&data[..], &dec_data[..]);
//! ```
#![no_std]

#[cfg(feature = "alloc")]
extern crate alloc;
#[cfg(feature = "std")]
extern crate std;

#[macro_use]
extern crate lazy_static;
Expand Down Expand Up @@ -80,6 +86,7 @@ pub use pem;

mod key;
mod oaep;
#[cfg(feature = "std")]
mod parse;
mod pkcs1v15;
mod pss;
Expand Down
3 changes: 3 additions & 0 deletions src/oaep.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
use rand::Rng;
use alloc::vec;
use alloc::vec::Vec;
use alloc::string::String;

use digest::DynDigest;
use subtle::{Choice, ConditionallySelectable, ConstantTimeEq, CtOption};
Expand Down
4 changes: 3 additions & 1 deletion src/padding.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use std::fmt;
use core::fmt;
use alloc::string::{String, ToString};
use alloc::boxed::Box;

use digest::{Digest, DynDigest};
use rand::RngCore;
Expand Down
6 changes: 4 additions & 2 deletions src/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ use crate::{
RSAPrivateKey, RSAPublicKey,
};
use simple_asn1::{ASN1Block, ASN1DecodeErr, BigUint, OID};

use std::convert::TryFrom;
use alloc::format;
use alloc::vec;
use alloc::vec::Vec;
use core::convert::TryFrom;

impl From<ASN1DecodeErr> for Error {
fn from(e: ASN1DecodeErr) -> Error {
Expand Down
2 changes: 2 additions & 0 deletions src/pkcs1v15.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use rand::Rng;
use subtle::{Choice, ConditionallySelectable, ConstantTimeEq};
use alloc::vec;
use alloc::vec::Vec;

use crate::errors::{Error, Result};
use crate::hash::Hash;
Expand Down
3 changes: 2 additions & 1 deletion src/pss.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::vec::Vec;
use alloc::vec;
use alloc::vec::Vec;

use digest::DynDigest;
use rand::{Rng, RngCore};
Expand Down
1 change: 1 addition & 0 deletions src/raw.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use num_bigint::BigUint;
use rand::Rng;
use zeroize::Zeroize;
use alloc::vec::Vec;

use crate::errors::{Error, Result};
use crate::internals;
Expand Down

0 comments on commit 9d171a6

Please sign in to comment.