Skip to main content

Crate rsa

Crate rsa 

Source
Expand description

§RustCrypto: RSA

crates.io Documentation Build Status codecov Apache2/MIT licensed MSRV Project Chat

A portable RSA implementation in pure Rust, with encryption and signature schemes specified in PKCS#1 v2.2 (RFC8017).

SchemePurposeSpecification
RSAES-OAEPEncryptionRFC8017 §7.1
RSAES-PKCS1-v1_5EncryptionRFC8017 §7.2
RSASSA-PSSSignaturesRFC8017 §8.1
RSASSA-PKCS1-v1_5SignaturesRFC8017 §8.2

PKCS#1 v1.5 is provided as opt-in through feature pkcs1v15 for compatibility with legacy applications only. Prefer OAEP and PSS for new applications.

See the security warning below for known implementation vulnerabilities.

§Example

use rsa::{Generate, PrivateKey, sha2::Sha256};

let private_key = PrivateKey::generate();
let public_key = private_key.to_public_key();

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

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

Note: If you encounter unusually slow key generation time while using RsaPrivateKey::new you can try to compile in release mode or add the following to your Cargo.toml. Key generation is much faster when building with higher optimization levels, but this will increase the compile time a bit.

[profile.debug]
opt-level = 3

§⚠️Security Warning

Though this crate has been previously audited the implementation has diverged significantly since then, and several security issues have been discovered which have been resolved in the 0.10 release.

See the open security issues on our issue tracker for other known problems. This crate was previously vulnerable to the Marvin Attack which could enable private key recovery by a network attacker (see RUSTSEC-2023-0071).

You can follow our work on constant-time hardening in #711.

Users are advised to migrate to 0.10 in order to avoid the discovered side channels.

§⚠️ PCKS#1 1.5 Warning

Additionally legacy PKCS#1 1.5 implementations, including the implementation of it within this crate, has seen a long running source of Bleichenbacher and Marvin Attacks related vulnerabilities.

For this reason, users who require the use of this legacy padding scheme i.e. in legacy protocols must explicitly enable the pkcs1v15 feature to use it.

§Minimum Supported Rust Version (MSRV) Policy

MSRV increases are not considered breaking changes and can happen in patch releases.

The crate MSRV accounts for all supported targets and crate feature combinations.

§License

Licensed under either of

at your option.

§Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

§Supported algorithms

This crate supports several schemes described in RFC8017:

These schemes are described below.

§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, PrivateKey};

let private_key = PrivateKey::generate();

With the getrandom feature (enabled by default), Generate::generate and 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::{Generate, PrivateKey, sha2::Sha256};

let private_key = PrivateKey::generate();
let public_key = private_key.to_public_key();

// Encrypt
let data = b"hello world";
let enc_data = public_key.oaep_encrypt::<Sha256>(data)?;
assert_ne!(&data[..], &enc_data[..]);

// Decrypt
let dec_data = private_key.oaep_decrypt::<Sha256>(&enc_data)?;
assert_eq!(&data[..], &dec_data[..]);

§PKCS#1 v1.5 encryption

Warning: PKCS#1 v1.5 encryption is deprecated due to security concerns. See security notes in the pkcs1v15 module.
use rsa::{Generate, PrivateKey};

let private_key = PrivateKey::generate();
let public_key = private_key.to_public_key();

// Encrypt
let data = b"hello world";
let enc_data = public_key.pkcs1v15_encrypt(data)?;
assert_ne!(&data[..], &enc_data[..]);

// Decrypt
let dec_data = private_key.pkcs1v15_decrypt(&enc_data)?;
assert_eq!(&data[..], &dec_data[..]);

§PKCS#1 v1.5 signatures

Warning: See security notes in the pkcs1v15 module.
use rsa::{Generate, PrivateKey, sha2::Sha256};

let private_key = PrivateKey::generate();
let public_key = private_key.to_public_key();

// Sign
let data = b"hello world";
let signature = private_key.pkcs1v15_sign::<Sha256>(data)?;

// Verify
public_key.pkcs1v15_verify::<Sha256>(data, &signature)?;

§PSS signatures

use rsa::{Generate, PrivateKey, sha2::Sha256};

let private_key = PrivateKey::generate();
let public_key = private_key.to_public_key();

// Sign
let data = b"hello world";
let signature = private_key.pss_sign::<Sha256>(data)?;

// Verify
public_key.pss_verify::<Sha256>(data, &signature)?;

§PKCS#1 RSA Key Encoding

PKCS#1 supports a legacy format for encoding RSA keys as binary (DER) or text (PEM) data.

You can recognize PEM encoded PKCS#1 keys because they have “RSA * KEY” in the type label, e.g.:

-----BEGIN RSA PRIVATE KEY-----

Most modern applications use the newer PKCS#8 format instead (see below).

The following traits can be used to decode/encode PrivateKey and PublicKey as PKCS#1. Note that pkcs1 is re-exported from the toplevel of the rsa crate:

§Example

use rsa::{PublicKey, pkcs1::DecodeRsaPublicKey};

let pem = "-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEAtsQsUV8QpqrygsY+2+JCQ6Fw8/omM71IM2N/R8pPbzbgOl0p78MZ
GsgPOQ2HSznjD0FPzsH8oO2B5Uftws04LHb2HJAYlz25+lN5cqfHAfa3fgmC38Ff
wBkn7l582UtPWZ/wcBOnyCgb3yLcvJrXyrt8QxHJgvWO23ITrUVYszImbXQ67YGS
0YhMrbixRzmo2tpm3JcIBtnHrEUMsT0NfFdfsZhTT8YbxBvA8FdODgEwx7u/vf3J
9qbi4+Kv8cvqyJuleIRSjVXPsIMnoejIn04APPKIjpMyQdnWlby7rNyQtE4+CV+j
cFjqJbE/Xilcvqxt6DirjFCvYeKYl1uHLwIDAQAB
-----END RSA PUBLIC KEY-----";

let public_key = PublicKey::from_pkcs1_pem(pem)?;

§PKCS#8 RSA Key Encoding

PKCS#8 is a private key format with support for multiple algorithms. Like PKCS#1, it can be encoded as binary (DER) or text (PEM).

You can recognize PEM encoded PKCS#8 keys because they don’t have an algorithm name in the type label, e.g.:

-----BEGIN PRIVATE KEY-----

The following traits can be used to decode/encode PrivateKey and PublicKey as PKCS#8. Note that pkcs8 is re-exported from the toplevel of the rsa crate:

§Example

use rsa::{PublicKey, pkcs8::DecodePublicKey};

let pem = "-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtsQsUV8QpqrygsY+2+JC
Q6Fw8/omM71IM2N/R8pPbzbgOl0p78MZGsgPOQ2HSznjD0FPzsH8oO2B5Uftws04
LHb2HJAYlz25+lN5cqfHAfa3fgmC38FfwBkn7l582UtPWZ/wcBOnyCgb3yLcvJrX
yrt8QxHJgvWO23ITrUVYszImbXQ67YGS0YhMrbixRzmo2tpm3JcIBtnHrEUMsT0N
fFdfsZhTT8YbxBvA8FdODgEwx7u/vf3J9qbi4+Kv8cvqyJuleIRSjVXPsIMnoejI
n04APPKIjpMyQdnWlby7rNyQtE4+CV+jcFjqJbE/Xilcvqxt6DirjFCvYeKYl1uH
LwIDAQAB
-----END PUBLIC KEY-----";

let public_key = PublicKey::from_public_key_pem(pem)?;

Re-exports§

pub use crate::errors::Error;
pub use crate::errors::Result;
pub use crate::oaep::Oaep;
pub use crate::pss::Pss;
pub use crate::pkcs1v15::Pkcs1v15Encrypt;
pub use crate::pkcs1v15::Pkcs1v15Sign;
pub use rand_core;
pub use signature;
pub use pkcs1;
pub use pkcs8;
pub use sha2;

Modules§

algorithms 🔒
Building blocks for the schemes in RFC8017:
encoding 🔒
PKCS#1 and PKCS#8 encoding support.
errors
Error types.
oaep
Encryption and Decryption using OAEP padding.
pkcs1v15
RSAES-PKCS1-v1_5 encryption (RFC8017 § 7.2) and RSASSA-PKCS1-v1_5 signatures (RFC8017 § 8.2).
private_key 🔒
RSA private key type.
pss
Support for the Probabilistic Signature Scheme (PSS) a.k.a. RSASSA-PSS.
public_key 🔒
RSA public key type.
traits
RSA-related trait definitions.

Structs§

BoxedUint
Fixed-precision heap-allocated big unsigned integer.
CrtValue
Contains the precomputed Chinese remainder theorem values.
PrivateKey
Represents a whole RSA key, public and private parts.
PublicKey
Represents the public part of an RSA key.

Traits§

Generate
Secure random generation.

Type Aliases§

RsaPrivateKeyDeprecated
Deprecated alias for PrivateKey.
RsaPublicKeyDeprecated
Deprecated alias for PublicKey.