rsa/lib.rs
1#![no_std]
2#![cfg_attr(docsrs, feature(doc_cfg))]
3#![cfg_attr(feature = "getrandom", doc = include_str!("../README.md"))] // example needs `getrandom`
4#![doc(html_logo_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo_small.png")]
5
6//! # Supported algorithms
7//!
8//! This crate supports several schemes described in [RFC8017]:
9//!
10//! - [OAEP encryption scheme](#oaep-encryption)
11//! - [PKCS#1 v1.5 encryption scheme](#pkcs1-v15-encryption)
12//! - [PKCS#1 v1.5 signature scheme](#pkcs1-v15-signatures)
13//! - [PSS signature scheme](#pss-signatures)
14//!
15//! These schemes are described below.
16//!
17//! # Usage
18//!
19//! [`PublicKey`] and [`PrivateKey`] provide algorithm-specific methods for
20//! encryption, decryption, signing, and verification. Signing and verification
21//! methods hash the message; their `_prehash` counterparts accept a digest instead.
22//!
23//! Methods ending in `_with_rng` accept a caller-provided [`rand_core::TryCryptoRng`].
24//! With the default `getrandom` feature, encryption, decryption, and signing methods
25//! without an RNG argument use the operating system RNG. Without that feature,
26//! encryption and PSS signing require `_with_rng`; decryption and PKCS#1 v1.5
27//! signing remain available without blinding.
28//!
29//! The algorithm-specific key types in [`oaep`], `pkcs1v15`, and [`pss`] also
30//! implement encryption and signature traits. Use these types for configurable
31//! OAEP labels and MGF1 digests, PSS salt lengths, or unprefixed PKCS#1 v1.5 signatures.
32//! PKCS#1 v1.5 methods and key types require the `pkcs1v15` feature.
33//!
34//! ## Key generation
35//!
36//! [`Generate`] creates 3072-bit RSA keys with public exponent 65537. This targets an estimated
37//! 128-bit security strength; see [`PrivateKey::DEFAULT_BITS`] for the rationale. Use
38//! [`PrivateKey::new`] to select a different key size.
39//!
40#![cfg_attr(feature = "getrandom", doc = "```")]
41#![cfg_attr(not(feature = "getrandom"), doc = "```ignore")]
42//! use rsa::{Generate, PrivateKey};
43//!
44//! let private_key = PrivateKey::generate();
45//! ```
46//!
47//! With the `getrandom` feature (enabled by default), `Generate::generate` and
48//! `Generate::try_generate` use the operating system RNG. Use `Generate::generate_from_rng`
49//! or `Generate::try_generate_from_rng` to supply an RNG explicitly.
50//!
51//! ## OAEP encryption
52//!
53#![cfg_attr(feature = "getrandom", doc = "```")]
54#![cfg_attr(not(feature = "getrandom"), doc = "```ignore")]
55//! # fn main() -> Result<(), rsa::Error> {
56//! use rsa::{Generate, PrivateKey, sha2::Sha256};
57//!
58//! let private_key = PrivateKey::generate();
59//! let public_key = private_key.to_public_key();
60//!
61//! // Encrypt
62//! let data = b"hello world";
63//! let enc_data = public_key.oaep_encrypt::<Sha256>(data)?;
64//! assert_ne!(&data[..], &enc_data[..]);
65//!
66//! // Decrypt
67//! let dec_data = private_key.oaep_decrypt::<Sha256>(&enc_data)?;
68//! assert_eq!(&data[..], &dec_data[..]);
69//! # Ok(())
70//! # }
71//! ```
72//!
73//! ## PKCS#1 v1.5 encryption
74//!
75//! <div class="warning">
76//! <b>Warning:</b>
77//! PKCS#1 v1.5 encryption is deprecated due to security concerns. See security notes in the
78//! <code><a href="./pkcs1v15/index.html">pkcs1v15</a></code> module.
79//! </div>
80//!
81#![cfg_attr(all(feature = "getrandom", feature = "pkcs1v15"), doc = "```")]
82#![cfg_attr(
83 not(all(feature = "getrandom", feature = "pkcs1v15")),
84 doc = "```ignore"
85)]
86//! # fn main() -> Result<(), rsa::Error> {
87//! use rsa::{Generate, PrivateKey};
88//!
89//! let private_key = PrivateKey::generate();
90//! let public_key = private_key.to_public_key();
91//!
92//! // Encrypt
93//! let data = b"hello world";
94//! let enc_data = public_key.pkcs1v15_encrypt(data)?;
95//! assert_ne!(&data[..], &enc_data[..]);
96//!
97//! // Decrypt
98//! let dec_data = private_key.pkcs1v15_decrypt(&enc_data)?;
99//! assert_eq!(&data[..], &dec_data[..]);
100//! # Ok(())
101//! # }
102//! ```
103//!
104//! ## PKCS#1 v1.5 signatures
105//!
106//! <div class="warning">
107//! <b>Warning:</b>
108//! See security notes in the <code><a href="./pkcs1v15/index.html">pkcs1v15</a></code> module.
109//! </div>
110//!
111#![cfg_attr(all(feature = "getrandom", feature = "pkcs1v15"), doc = "```")]
112#![cfg_attr(
113 not(all(feature = "getrandom", feature = "pkcs1v15")),
114 doc = "```ignore"
115)]
116//! # fn main() -> Result<(), rsa::Error> {
117//! use rsa::{Generate, PrivateKey, sha2::Sha256};
118//!
119//! let private_key = PrivateKey::generate();
120//! let public_key = private_key.to_public_key();
121//!
122//! // Sign
123//! let data = b"hello world";
124//! let signature = private_key.pkcs1v15_sign::<Sha256>(data)?;
125//!
126//! // Verify
127//! public_key.pkcs1v15_verify::<Sha256>(data, &signature)?;
128//! # Ok(())
129//! # }
130//! ```
131//!
132//! ## PSS signatures
133//!
134#![cfg_attr(feature = "getrandom", doc = "```")]
135#![cfg_attr(not(feature = "getrandom"), doc = "```ignore")]
136//! # fn main() -> Result<(), rsa::Error> {
137//! use rsa::{Generate, PrivateKey, sha2::Sha256};
138//!
139//! let private_key = PrivateKey::generate();
140//! let public_key = private_key.to_public_key();
141//!
142//! // Sign
143//! let data = b"hello world";
144//! let signature = private_key.pss_sign::<Sha256>(data)?;
145//!
146//! // Verify
147//! public_key.pss_verify::<Sha256>(data, &signature)?;
148//! # Ok(())
149//! # }
150//! ```
151//!
152//! ## PKCS#1 RSA Key Encoding
153//!
154//! PKCS#1 supports a legacy format for encoding RSA keys as binary (DER) or
155//! text (PEM) data.
156//!
157//! You can recognize PEM encoded PKCS#1 keys because they have "RSA * KEY" in
158//! the type label, e.g.:
159//!
160//! ```text
161//! -----BEGIN RSA PRIVATE KEY-----
162//! ```
163//!
164//! Most modern applications use the newer PKCS#8 format instead (see below).
165//!
166//! The following traits can be used to decode/encode [`PrivateKey`] and
167//! [`PublicKey`] as PKCS#1. Note that [`pkcs1`] is re-exported from the
168//! toplevel of the `rsa` crate:
169//!
170//! - [`pkcs1::DecodeRsaPrivateKey`]: decode RSA private keys from PKCS#1
171//! - [`pkcs1::EncodeRsaPrivateKey`]: encode RSA private keys to PKCS#1
172//! - [`pkcs1::DecodeRsaPublicKey`]: decode RSA public keys from PKCS#1
173//! - [`pkcs1::EncodeRsaPublicKey`]: encode RSA public keys to PKCS#1
174//!
175//! ### Example
176//!
177#![cfg_attr(feature = "encoding", doc = "```")]
178#![cfg_attr(not(feature = "encoding"), doc = "```ignore")]
179//! # fn main() -> Result<(), rsa::Error> {
180//! use rsa::{PublicKey, pkcs1::DecodeRsaPublicKey};
181//!
182//! let pem = "-----BEGIN RSA PUBLIC KEY-----
183//! MIIBCgKCAQEAtsQsUV8QpqrygsY+2+JCQ6Fw8/omM71IM2N/R8pPbzbgOl0p78MZ
184//! GsgPOQ2HSznjD0FPzsH8oO2B5Uftws04LHb2HJAYlz25+lN5cqfHAfa3fgmC38Ff
185//! wBkn7l582UtPWZ/wcBOnyCgb3yLcvJrXyrt8QxHJgvWO23ITrUVYszImbXQ67YGS
186//! 0YhMrbixRzmo2tpm3JcIBtnHrEUMsT0NfFdfsZhTT8YbxBvA8FdODgEwx7u/vf3J
187//! 9qbi4+Kv8cvqyJuleIRSjVXPsIMnoejIn04APPKIjpMyQdnWlby7rNyQtE4+CV+j
188//! cFjqJbE/Xilcvqxt6DirjFCvYeKYl1uHLwIDAQAB
189//! -----END RSA PUBLIC KEY-----";
190//!
191//! let public_key = PublicKey::from_pkcs1_pem(pem)?;
192//! # Ok(())
193//! # }
194//! ```
195//!
196//! ## PKCS#8 RSA Key Encoding
197//!
198//! PKCS#8 is a private key format with support for multiple algorithms.
199//! Like PKCS#1, it can be encoded as binary (DER) or text (PEM).
200//!
201//! You can recognize PEM encoded PKCS#8 keys because they *don't* have
202//! an algorithm name in the type label, e.g.:
203//!
204//! ```text
205//! -----BEGIN PRIVATE KEY-----
206//! ```
207//!
208//! The following traits can be used to decode/encode [`PrivateKey`] and
209//! [`PublicKey`] as PKCS#8. Note that [`pkcs8`] is re-exported from the
210//! toplevel of the `rsa` crate:
211//!
212//! - [`pkcs8::DecodePrivateKey`]: decode private keys from PKCS#8
213//! - [`pkcs8::EncodePrivateKey`]: encode private keys to PKCS#8
214//! - [`pkcs8::DecodePublicKey`]: decode public keys from PKCS#8
215//! - [`pkcs8::EncodePublicKey`]: encode public keys to PKCS#8
216//!
217//! ### Example
218//!
219#![cfg_attr(feature = "encoding", doc = "```")]
220#![cfg_attr(not(feature = "encoding"), doc = "```ignore")]
221//! # fn main() -> Result<(), rsa::pkcs8::Error> {
222//! use rsa::{PublicKey, pkcs8::DecodePublicKey};
223//!
224//! let pem = "-----BEGIN PUBLIC KEY-----
225//! MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtsQsUV8QpqrygsY+2+JC
226//! Q6Fw8/omM71IM2N/R8pPbzbgOl0p78MZGsgPOQ2HSznjD0FPzsH8oO2B5Uftws04
227//! LHb2HJAYlz25+lN5cqfHAfa3fgmC38FfwBkn7l582UtPWZ/wcBOnyCgb3yLcvJrX
228//! yrt8QxHJgvWO23ITrUVYszImbXQ67YGS0YhMrbixRzmo2tpm3JcIBtnHrEUMsT0N
229//! fFdfsZhTT8YbxBvA8FdODgEwx7u/vf3J9qbi4+Kv8cvqyJuleIRSjVXPsIMnoejI
230//! n04APPKIjpMyQdnWlby7rNyQtE4+CV+jcFjqJbE/Xilcvqxt6DirjFCvYeKYl1uH
231//! LwIDAQAB
232//! -----END PUBLIC KEY-----";
233//!
234//! let public_key = PublicKey::from_public_key_pem(pem)?;
235//! # Ok(())
236//! # }
237//! ```
238//!
239//! [RFC8017]: https://www.rfc-editor.org/rfc/rfc8017.html
240//!
241// TODO(tarcieri): figure out why rustdoc isn't rendering these links correctly
242//! [`pkcs8::DecodePublicKey`]: https://docs.rs/pkcs8/latest/pkcs8/trait.DecodePublicKey.html
243//! [`pkcs8::EncodePublicKey`]: https://docs.rs/pkcs8/latest/pkcs8/trait.EncodePublicKey.html
244
245#[cfg(doctest)]
246pub struct ReadmeDoctests;
247
248#[macro_use]
249extern crate alloc;
250#[cfg(feature = "std")]
251extern crate std;
252
253pub use crypto_bigint::BoxedUint;
254pub use crypto_common::Generate;
255pub use rand_core;
256pub use signature;
257
258mod algorithms;
259pub mod errors;
260pub mod oaep;
261pub mod pss;
262pub mod traits;
263
264#[cfg(feature = "pkcs1v15")]
265pub mod pkcs1v15;
266
267#[cfg(not(feature = "getrandom"))]
268mod dummy_rng;
269mod encoding;
270mod private_key;
271mod public_key;
272
273#[cfg(feature = "encoding")]
274pub use pkcs1;
275#[cfg(feature = "encoding")]
276pub use pkcs8;
277pub use sha2;
278
279pub use crate::{
280 errors::{Error, Result},
281 oaep::Oaep,
282 private_key::PrivateKey,
283 pss::Pss,
284 public_key::PublicKey,
285 traits::keys::CrtValue,
286};
287
288#[cfg(feature = "pkcs1v15")]
289pub use crate::pkcs1v15::{Pkcs1v15Encrypt, Pkcs1v15Sign};
290
291#[cfg(feature = "hazmat")]
292pub mod hazmat;
293
294/// Deprecated alias for [`PrivateKey`].
295#[deprecated(since = "0.10.0", note = "use `rsa::PrivateKey` instead")]
296pub type RsaPrivateKey = PrivateKey;
297
298/// Deprecated alias for [`PublicKey`].
299#[deprecated(since = "0.10.0", note = "use `rsa::PublicKey` instead")]
300pub type RsaPublicKey = PublicKey;