jose/crypto/backend/interface/rsa.rs
1//! The interfaces for RSA.
2
3use alloc::vec::Vec;
4
5use secrecy::SecretSlice;
6
7use crate::{crypto::Result, jwa};
8
9/// Part of the [`PrivateKeyComponents`], which includes additional information
10/// about the prime numbers.
11#[derive(Clone)]
12pub(crate) struct PrivateKeyPrimeComponents {
13 pub p: SecretSlice<u8>,
14 pub q: SecretSlice<u8>,
15 pub dp: SecretSlice<u8>,
16 pub dq: SecretSlice<u8>,
17 pub qi: SecretSlice<u8>,
18}
19
20/// The components of a private key.
21///
22/// All fields in this struct are of type `Vec<u8>` and are
23/// big integers represented in big endian bytes.
24#[derive(Clone)]
25pub(crate) struct PrivateKeyComponents {
26 pub d: SecretSlice<u8>,
27 pub prime: PrivateKeyPrimeComponents,
28}
29
30/// The components of a public key.
31///
32/// All fields in this struct are of type `Vec<u8>` and are
33/// big integers represented in big endian bytes.
34#[derive(Clone, PartialEq, Eq)]
35pub(crate) struct PublicKeyComponents {
36 pub n: Vec<u8>,
37 pub e: Vec<u8>,
38}
39
40/// The common operations for an RSA private key.
41pub(crate) trait PrivateKey: Sized {
42 /// The signature type that is produced by this key.
43 type Signature: Into<Vec<u8>> + AsRef<[u8]>;
44
45 /// The public key type.
46 type PublicKey: PublicKey;
47
48 /// Generates a new rsa private key with the given number of bits.
49 fn generate(bits: usize) -> Result<Self>;
50
51 /// Creates a new RSA private key from the given private & public key
52 /// components.
53 fn from_components(private: PrivateKeyComponents, public: PublicKeyComponents) -> Result<Self>;
54
55 /// Creates a new public key from this private key.
56 fn to_public_key(&self) -> Self::PublicKey;
57
58 /// Returns the private key components.
59 fn private_components(&self) -> Result<PrivateKeyComponents>;
60
61 /// Returns the public key components.
62 fn public_components(&self) -> PublicKeyComponents;
63
64 /// Signs the given data using this key.
65 ///
66 /// This operation **must** be re-usable, meaning this method can be
67 /// called multiple times with different data to sign.
68 fn sign(&mut self, alg: jwa::RsaSigning, data: &[u8]) -> Result<Self::Signature>;
69}
70
71/// The common operations for an RSA public key.
72pub(crate) trait PublicKey: Sized {
73 /// Creates a new RSA public key from the given public key components.
74 fn from_components(components: PublicKeyComponents) -> Result<Self>;
75
76 /// Returns the public key components.
77 fn components(&self) -> PublicKeyComponents;
78
79 /// Verifies if the message is valid for the given signature and algorithm.
80 ///
81 /// Returns `true` if the signature is valid, `false` otherwise.
82 fn verify(&mut self, alg: jwa::RsaSigning, msg: &[u8], signature: &[u8]) -> Result<bool>;
83}