logo
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//! Rivest–Shamir–Adleman (RSA) private keys.

use crate::{
    base64::{self, Decode},
    public::RsaPublicKey,
    MPInt, Result,
};
use core::fmt;
use zeroize::Zeroize;

/// RSA private key.
#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
#[derive(Clone)]
pub struct RsaPrivateKey {
    /// RSA private exponent.
    pub d: MPInt,

    /// CRT coefficient: `(inverse of q) mod p`.
    pub iqmp: MPInt,

    /// First prime factor of `n`.
    pub p: MPInt,

    /// Second prime factor of `n`.
    pub q: MPInt,
}

impl Decode for RsaPrivateKey {
    fn decode(decoder: &mut base64::Decoder<'_>) -> Result<Self> {
        let d = MPInt::decode(decoder)?;
        let iqmp = MPInt::decode(decoder)?;
        let p = MPInt::decode(decoder)?;
        let q = MPInt::decode(decoder)?;
        Ok(Self { d, iqmp, p, q })
    }
}

impl Drop for RsaPrivateKey {
    fn drop(&mut self) {
        self.d.zeroize();
        self.iqmp.zeroize();
        self.p.zeroize();
        self.q.zeroize();
    }
}

/// RSA private/public keypair.
#[derive(Clone)]
pub struct RsaKeypair {
    /// Public key.
    pub public: RsaPublicKey,

    /// Private key.
    pub private: RsaPrivateKey,
}

impl Decode for RsaKeypair {
    fn decode(decoder: &mut base64::Decoder<'_>) -> Result<Self> {
        let n = MPInt::decode(decoder)?;
        let e = MPInt::decode(decoder)?;
        let public = RsaPublicKey { n, e };
        let private = RsaPrivateKey::decode(decoder)?;
        Ok(RsaKeypair { public, private })
    }
}

impl fmt::Debug for RsaKeypair {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RsaKeypair")
            .field("public", &self.public)
            .finish_non_exhaustive()
    }
}