Skip to content
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
13 changes: 5 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,21 +26,18 @@ See the security warning below for known implementation vulnerabilities.
## Example

```rust
use rsa::{Oaep, RsaPrivateKey, RsaPublicKey};
use sha2::Sha256;
use rsa::{Generate, PrivateKey, sha2::Sha256};

let mut rng = rand::rng();
let bits = 2048;
let priv_key = RsaPrivateKey::new(&mut rng, bits).expect("failed to generate a key");
let pub_key = RsaPublicKey::from(&priv_key);
let private_key = PrivateKey::generate();
let public_key = private_key.to_public_key();

// Encrypt
let data = b"hello world";
let enc_data = pub_key.encrypt(&mut rng, Oaep::<Sha256>::new(), &data[..]).expect("failed to encrypt");
let enc_data = public_key.oaep_encrypt::<Sha256>(data).expect("failed to encrypt");
assert_ne!(&data[..], &enc_data[..]);

// Decrypt
let dec_data = priv_key.decrypt_blinded(&mut rng, Oaep::<Sha256>::new(), &enc_data).expect("failed to decrypt");
let dec_data = private_key.oaep_decrypt::<Sha256>(&enc_data).expect("failed to decrypt");
assert_eq!(&data[..], &dec_data[..]);
```

Expand Down
131 changes: 72 additions & 59 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#![cfg_attr(not(test), no_std)]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![doc = include_str!("../README.md")]
#![cfg_attr(feature = "getrandom", doc = include_str!("../README.md"))] // example needs `getrandom`
#![doc(html_logo_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo_small.png")]

//! # Supported algorithms
Expand All @@ -16,42 +16,58 @@
//!
//! # Usage
//!
//! [`PublicKey`] and [`PrivateKey`] provide algorithm-specific methods for
//! encryption, decryption, signing, and verification. Signing and verification
//! methods hash the message; their `_prehash` counterparts accept a digest instead.
//!
//! Methods ending in `_with_rng` accept a caller-provided [`rand_core::TryCryptoRng`].
//! With the default `getrandom` feature, encryption, decryption, and signing methods
//! without an RNG argument use the operating system RNG. Without that feature,
//! encryption and PSS signing require `_with_rng`; decryption and PKCS#1 v1.5
//! signing remain available without blinding.
//!
//! The algorithm-specific key types in [`oaep`], `pkcs1v15`, and [`pss`] also
//! implement encryption and signature traits. Use these types for configurable
//! OAEP labels and MGF1 digests, PSS salt lengths, or unprefixed PKCS#1 v1.5 signatures.
//! PKCS#1 v1.5 methods and key types require the `pkcs1v15` feature.
//!
//! ## Key generation
//!
//! [`Generate`] creates 3072-bit RSA keys with public exponent 65537. This targets an estimated
//! 128-bit security strength; see [`PrivateKey::DEFAULT_BITS`] for the rationale. Use
//! [`PrivateKey::new`] to select a different key size.
//!
//! ```
//! use rsa::{Generate, RsaPrivateKey};
#![cfg_attr(feature = "getrandom", doc = "```")]
#![cfg_attr(not(feature = "getrandom"), doc = "```ignore")]
//! use rsa::{Generate, PrivateKey};
//!
//! let private_key = RsaPrivateKey::generate_from_rng(&mut rand::rng());
//! let private_key = PrivateKey::generate();
//! ```
//!
//! With the `getrandom` feature (enabled by default), `Generate::generate` and
//! `Generate::try_generate` use the operating system RNG.
//! `Generate::try_generate` use the operating system RNG. Use `Generate::generate_from_rng`
//! or `Generate::try_generate_from_rng` to supply an RNG explicitly.
//!
//! ## OAEP encryption
//!
//! ```
//! use rsa::{RsaPrivateKey, RsaPublicKey, Oaep, sha2::Sha256};
#![cfg_attr(feature = "getrandom", doc = "```")]
#![cfg_attr(not(feature = "getrandom"), doc = "```ignore")]
//! # fn main() -> Result<(), rsa::Error> {
//! use rsa::{Generate, PrivateKey, sha2::Sha256};
//!
//! let mut rng = rand::rng();
//!
//! let bits = 2048;
//! let private_key = RsaPrivateKey::new(&mut rng, bits).expect("failed to generate a key");
//! let public_key = RsaPublicKey::from(&private_key);
//! let private_key = PrivateKey::generate();
//! let public_key = private_key.to_public_key();
//!
//! // Encrypt
//! let data = b"hello world";
//! let padding = Oaep::<Sha256>::new();
//! let enc_data = public_key.encrypt(&mut rng, padding, &data[..]).expect("failed to encrypt");
//! let enc_data = public_key.oaep_encrypt::<Sha256>(data)?;
//! assert_ne!(&data[..], &enc_data[..]);
//!
//! // Decrypt
//! let padding = Oaep::<Sha256>::new();
//! let dec_data = private_key.decrypt(padding, &enc_data).expect("failed to decrypt");
//! let dec_data = private_key.oaep_decrypt::<Sha256>(&enc_data)?;
//! assert_eq!(&data[..], &dec_data[..]);
//! # Ok(())
//! # }
//! ```
//!
//! ## PKCS#1 v1.5 encryption
Expand All @@ -62,24 +78,27 @@
//! <code><a href="./pkcs1v15/index.html">pkcs1v15</a></code> module.
//! </div>
//!
#![cfg_attr(feature = "pkcs1v15", doc = "```")]
#![cfg_attr(not(feature = "pkcs1v15"), doc = "```ignore")]
//! use rsa::{RsaPrivateKey, RsaPublicKey, Pkcs1v15Encrypt};
//!
//! let mut rng = rand::rng();
#![cfg_attr(all(feature = "getrandom", feature = "pkcs1v15"), doc = "```")]
#![cfg_attr(
not(all(feature = "getrandom", feature = "pkcs1v15")),
doc = "```ignore"
)]
//! # fn main() -> Result<(), rsa::Error> {
//! use rsa::{Generate, PrivateKey};
//!
//! let bits = 2048;
//! let private_key = RsaPrivateKey::new(&mut rng, bits).expect("failed to generate a key");
//! let public_key = RsaPublicKey::from(&private_key);
//! let private_key = PrivateKey::generate();
//! let public_key = private_key.to_public_key();
//!
//! // Encrypt
//! let data = b"hello world";
//! let enc_data = public_key.encrypt(&mut rng, Pkcs1v15Encrypt, &data[..]).expect("failed to encrypt");
//! let enc_data = public_key.pkcs1v15_encrypt(data)?;
//! assert_ne!(&data[..], &enc_data[..]);
//!
//! // Decrypt
//! let dec_data = private_key.decrypt(Pkcs1v15Encrypt, &enc_data).expect("failed to decrypt");
//! let dec_data = private_key.pkcs1v15_decrypt(&enc_data)?;
//! assert_eq!(&data[..], &dec_data[..]);
//! # Ok(())
//! # }
//! ```
//!
//! ## PKCS#1 v1.5 signatures
Expand All @@ -89,51 +108,45 @@
//! See security notes in the <code><a href="./pkcs1v15/index.html">pkcs1v15</a></code> module.
//! </div>
//!
#![cfg_attr(feature = "pkcs1v15", doc = "```")]
#![cfg_attr(not(feature = "pkcs1v15"), doc = "```ignore")]
//! use rsa::RsaPrivateKey;
//! use rsa::pkcs1v15::{SigningKey, VerifyingKey};
//! use rsa::signature::{Keypair, RandomizedSigner, SignatureEncoding, Verifier};
//! use rsa::sha2::{Digest, Sha256};
//!
//! let mut rng = rand::rng();
#![cfg_attr(all(feature = "getrandom", feature = "pkcs1v15"), doc = "```")]
#![cfg_attr(
not(all(feature = "getrandom", feature = "pkcs1v15")),
doc = "```ignore"
)]
//! # fn main() -> Result<(), rsa::Error> {
//! use rsa::{Generate, PrivateKey, sha2::Sha256};
//!
//! let bits = 2048;
//! let private_key = RsaPrivateKey::new(&mut rng, bits).expect("failed to generate a key");
//! let signing_key = SigningKey::<Sha256>::new(private_key);
//! let verifying_key = signing_key.verifying_key();
//! let private_key = PrivateKey::generate();
//! let public_key = private_key.to_public_key();
//!
//! // Sign
//! let data = b"hello world";
//! let signature = signing_key.sign_with_rng(&mut rng, data);
//! assert_ne!(signature.to_bytes().as_ref(), data.as_slice());
//! let signature = private_key.pkcs1v15_sign::<Sha256>(data)?;
//!
//! // Verify
//! verifying_key.verify(data, &signature).expect("failed to verify");
//! public_key.pkcs1v15_verify::<Sha256>(data, &signature)?;
//! # Ok(())
//! # }
//! ```
//!
//! ## PSS signatures
//!
//! ```
//! use rsa::RsaPrivateKey;
//! use rsa::pss::{BlindedSigningKey, VerifyingKey};
//! use rsa::signature::{Keypair,RandomizedSigner, SignatureEncoding, Verifier};
//! use rsa::sha2::{Digest, Sha256};
//!
//! let mut rng = rand::rng();
#![cfg_attr(feature = "getrandom", doc = "```")]
#![cfg_attr(not(feature = "getrandom"), doc = "```ignore")]
//! # fn main() -> Result<(), rsa::Error> {
//! use rsa::{Generate, PrivateKey, sha2::Sha256};
//!
//! let bits = 2048;
//! let private_key = RsaPrivateKey::new(&mut rng, bits).expect("failed to generate a key");
//! let signing_key = BlindedSigningKey::<Sha256>::new(private_key);
//! let verifying_key = signing_key.verifying_key();
//! let private_key = PrivateKey::generate();
//! let public_key = private_key.to_public_key();
//!
//! // Sign
//! let data = b"hello world";
//! let signature = signing_key.sign_with_rng(&mut rng, data);
//! assert_ne!(signature.to_bytes().as_ref(), data);
//! let signature = private_key.pss_sign::<Sha256>(data)?;
//!
//! // Verify
//! verifying_key.verify(data, &signature).expect("failed to verify");
//! public_key.pss_verify::<Sha256>(data, &signature)?;
//! # Ok(())
//! # }
//! ```
//!
//! ## PKCS#1 RSA Key Encoding
Expand Down Expand Up @@ -165,7 +178,7 @@
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! # #[cfg(all(feature = "encoding", feature = "std"))]
//! # {
//! use rsa::{RsaPublicKey, pkcs1::DecodeRsaPublicKey};
//! use rsa::{PublicKey, pkcs1::DecodeRsaPublicKey};
//!
//! let pem = "-----BEGIN RSA PUBLIC KEY-----
//! MIIBCgKCAQEAtsQsUV8QpqrygsY+2+JCQ6Fw8/omM71IM2N/R8pPbzbgOl0p78MZ
Expand All @@ -176,7 +189,7 @@
//! cFjqJbE/Xilcvqxt6DirjFCvYeKYl1uHLwIDAQAB
//! -----END RSA PUBLIC KEY-----";
//!
//! let public_key = RsaPublicKey::from_pkcs1_pem(pem)?;
//! let public_key = PublicKey::from_pkcs1_pem(pem)?;
//! # }
//! # Ok(())
//! # }
Expand Down Expand Up @@ -209,7 +222,7 @@
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! # #[cfg(all(feature = "encoding", feature = "std"))]
//! # {
//! use rsa::{RsaPublicKey, pkcs8::DecodePublicKey};
//! use rsa::{PublicKey, pkcs8::DecodePublicKey};
//!
//! let pem = "-----BEGIN PUBLIC KEY-----
//! MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtsQsUV8QpqrygsY+2+JC
Expand All @@ -221,7 +234,7 @@
//! LwIDAQAB
//! -----END PUBLIC KEY-----";
//!
//! let public_key = RsaPublicKey::from_public_key_pem(pem)?;
//! let public_key = PublicKey::from_public_key_pem(pem)?;
//! # }
//! # Ok(())
//! # }
Expand Down
79 changes: 79 additions & 0 deletions src/oaep.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,85 @@ use crate::errors::{Error, Result};
use crate::traits::{PaddingScheme, PublicKeyParts};
use crate::{PrivateKey, PublicKey, public_key};

#[cfg(feature = "getrandom")]
use crypto_common::getrandom::SysRng;

impl PublicKey {
/// Encrypt `plaintext` using OAEP and the operating system RNG.
///
/// Uses `D` for both OAEP and MGF1, with an empty label. For a different MGF1
/// digest or a nonempty label, use [`EncryptingKey`].
///
/// # Errors
/// Returns an error if the key is invalid, the plaintext is too long, or the RNG fails.
#[cfg(feature = "getrandom")]
pub fn oaep_encrypt<D>(&self, plaintext: &[u8]) -> Result<Vec<u8>>
where
D: Digest + FixedOutputReset,
{
self.oaep_encrypt_with_rng::<D, _>(&mut SysRng, plaintext)
}

/// Encrypt `plaintext` using OAEP and the provided RNG.
///
/// Uses `D` for both OAEP and MGF1, with an empty label. For a different MGF1
/// digest or a nonempty label, use [`EncryptingKey`].
///
/// # Errors
/// Returns an error if the key is invalid, the plaintext is too long, or the RNG fails.
pub fn oaep_encrypt_with_rng<D, R>(&self, rng: &mut R, plaintext: &[u8]) -> Result<Vec<u8>>
where
D: Digest + FixedOutputReset,
R: TryCryptoRng + ?Sized,
{
encrypt_digest::<_, D, D>(rng, self, plaintext, None)
}
}

impl PrivateKey {
/// Decrypt `ciphertext` using OAEP.
///
/// Uses `D` for both OAEP and MGF1, with an empty label. For a different MGF1
/// digest or a nonempty label, use [`DecryptingKey`].
///
/// Uses the operating system RNG for blinding when `getrandom` is enabled.
/// Otherwise, this operation is unblinded; use [`Self::oaep_decrypt_with_rng`]
/// to provide blinding randomness.
///
/// # Errors
/// Returns an error if the key or ciphertext is invalid or the private operation
/// fails, including RNG failures.
pub fn oaep_decrypt<D>(&self, ciphertext: &[u8]) -> Result<Vec<u8>>
where
D: Digest + FixedOutputReset,
{
#[cfg(feature = "getrandom")]
{
self.oaep_decrypt_with_rng::<D, _>(&mut SysRng, ciphertext)
}
#[cfg(not(feature = "getrandom"))]
{
decrypt_digest::<crate::dummy_rng::DummyRng, D, D>(None, self, ciphertext, None)
}
}

/// Decrypt `ciphertext` using OAEP, using the provided RNG for blinding.
///
/// Uses `D` for both OAEP and MGF1, with an empty label. For a different MGF1
/// digest or a nonempty label, use [`DecryptingKey`].
///
/// # Errors
/// Returns an error if the key or ciphertext is invalid or the private operation
/// fails, including RNG failures.
pub fn oaep_decrypt_with_rng<D, R>(&self, rng: &mut R, ciphertext: &[u8]) -> Result<Vec<u8>>
where
D: Digest + FixedOutputReset,
R: TryCryptoRng + ?Sized,
{
decrypt_digest::<_, D, D>(Some(rng), self, ciphertext, None)
}
}

/// Encryption and Decryption using [OAEP padding](https://datatracker.ietf.org/doc/html/rfc8017#section-7.1).
///
/// - `digest` is used to hash the label. The maximum possible plaintext length is `m = k - 2 * h_len - 2`,
Expand Down
Loading
Loading