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
use crate::{Error, Result};
use core::cmp::Ordering;
use der::{
asn1::{Any, ObjectIdentifier},
Decodable, Decoder, DerOrd, Encodable, Sequence, ValueOrd,
};
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct AlgorithmIdentifier<'a> {
pub oid: ObjectIdentifier,
pub parameters: Option<Any<'a>>,
}
impl<'a> AlgorithmIdentifier<'a> {
pub fn assert_algorithm_oid(&self, expected_oid: ObjectIdentifier) -> Result<ObjectIdentifier> {
if self.oid == expected_oid {
Ok(expected_oid)
} else {
Err(Error::OidUnknown { oid: expected_oid })
}
}
pub fn assert_parameters_oid(
&self,
expected_oid: ObjectIdentifier,
) -> Result<ObjectIdentifier> {
let actual_oid = self.parameters_oid()?;
if actual_oid == expected_oid {
Ok(actual_oid)
} else {
Err(Error::OidUnknown { oid: expected_oid })
}
}
pub fn assert_oids(
&self,
algorithm: ObjectIdentifier,
parameters: ObjectIdentifier,
) -> Result<()> {
self.assert_algorithm_oid(algorithm)?;
self.assert_parameters_oid(parameters)?;
Ok(())
}
pub fn parameters_any(&self) -> Result<Any<'a>> {
self.parameters.ok_or(Error::AlgorithmParametersMissing)
}
pub fn parameters_oid(&self) -> Result<ObjectIdentifier> {
Ok(ObjectIdentifier::try_from(self.parameters_any()?)?)
}
}
impl<'a> Decodable<'a> for AlgorithmIdentifier<'a> {
fn decode(decoder: &mut Decoder<'a>) -> der::Result<Self> {
decoder.sequence(|decoder| {
let oid = decoder.decode()?;
let parameters = decoder.decode()?;
Ok(Self { oid, parameters })
})
}
}
impl<'a> Sequence<'a> for AlgorithmIdentifier<'a> {
fn fields<F, T>(&self, f: F) -> der::Result<T>
where
F: FnOnce(&[&dyn Encodable]) -> der::Result<T>,
{
f(&[&self.oid, &self.parameters])
}
}
impl<'a> TryFrom<&'a [u8]> for AlgorithmIdentifier<'a> {
type Error = Error;
fn try_from(bytes: &'a [u8]) -> Result<Self> {
Ok(Self::from_der(bytes)?)
}
}
impl ValueOrd for AlgorithmIdentifier<'_> {
fn value_cmp(&self, other: &Self) -> der::Result<Ordering> {
match self.oid.der_cmp(&other.oid)? {
Ordering::Equal => self.parameters.der_cmp(&other.parameters),
other => Ok(other),
}
}
}