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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
use crate::error::*;
use asn1_rs::FromDer;
use der_parser::{
der::{parse_der_integer, parse_der_sequence_defined_g},
error::BerResult,
};
#[derive(Debug, PartialEq)]
pub enum PublicKey<'a> {
RSA(RSAPublicKey<'a>),
EC(ECPoint<'a>),
DSA(&'a [u8]),
GostR3410(&'a [u8]),
GostR3410_2012(&'a [u8]),
Unknown(&'a [u8]),
}
impl<'a> PublicKey<'a> {
pub fn key_size(&self) -> usize {
match self {
Self::EC(ec) => ec.key_size(),
Self::RSA(rsa) => rsa.key_size(),
Self::DSA(y) | Self::GostR3410(y) => y.len() * 8,
_ => 0,
}
}
}
#[derive(Debug, PartialEq)]
pub struct RSAPublicKey<'a> {
pub modulus: &'a [u8],
pub exponent: &'a [u8],
}
impl<'a> RSAPublicKey<'a> {
pub fn try_exponent(&self) -> Result<u64, X509Error> {
let mut buf = [0u8; 8];
if self.exponent.is_empty() || self.exponent[0] & 0x80 != 0 || self.exponent.len() > 8 {
return Err(X509Error::InvalidNumber);
}
buf[8_usize.saturating_sub(self.exponent.len())..].copy_from_slice(self.exponent);
let int = <u64>::from_be_bytes(buf);
Ok(int)
}
pub fn key_size(&self) -> usize {
if !self.modulus.is_empty() && self.modulus[0] & 0x80 == 0 {
let modulus = &self.modulus[1..];
8 * modulus.len()
} else {
0
}
}
}
fn parse_rsa_key(bytes: &[u8]) -> BerResult<RSAPublicKey> {
parse_der_sequence_defined_g(move |i, _| {
let (i, obj_modulus) = parse_der_integer(i)?;
let (i, obj_exponent) = parse_der_integer(i)?;
let modulus = obj_modulus.as_slice()?;
let exponent = obj_exponent.as_slice()?;
let key = RSAPublicKey { modulus, exponent };
Ok((i, key))
})(bytes)
}
impl<'a> FromDer<'a, X509Error> for RSAPublicKey<'a> {
fn from_der(bytes: &'a [u8]) -> X509Result<'a, Self> {
parse_rsa_key(bytes).map_err(|_| nom::Err::Error(X509Error::InvalidSPKI))
}
}
#[derive(Debug, PartialEq)]
pub struct ECPoint<'a> {
data: &'a [u8],
}
impl<'a> ECPoint<'a> {
pub fn data(&'a self) -> &'a [u8] {
self.data
}
pub fn key_size(&self) -> usize {
match self.data {
[] => {
0
}
[4, rem @ ..] => {
rem.len() * 8 / 2
}
[2..=3, rem @ ..] => {
rem.len() * 8
}
_ => {
0
}
}
}
}
impl<'a> From<&'a [u8]> for ECPoint<'a> {
fn from(data: &'a [u8]) -> Self {
ECPoint { data }
}
}