1use crate::{Error, Mpint, Result};
4use core::hash::{Hash, Hasher};
5use encoding::{Decode, Decoder, Encode, Reader};
6
7#[cfg(feature = "dsa")]
8use encoding::Uint;
9
10#[derive(Clone, Debug, Encode, Eq, Ord, PartialEq, PartialOrd)]
14pub struct DsaPublicKey {
15 p: Mpint,
17
18 q: Mpint,
20
21 g: Mpint,
24
25 y: Mpint,
27}
28
29impl DsaPublicKey {
30 pub fn new(p: Mpint, q: Mpint, g: Mpint, y: Mpint) -> Result<Self> {
41 if p.is_zero() || q.is_zero() || g.is_zero() || y.is_zero() {
42 return Err(Error::FormatEncoding);
43 }
44 Ok(Self { p, q, g, y })
45 }
46
47 #[must_use]
49 pub fn p(&self) -> &Mpint {
50 &self.p
51 }
52
53 #[must_use]
55 pub fn q(&self) -> &Mpint {
56 &self.q
57 }
58
59 #[must_use]
62 pub fn g(&self) -> &Mpint {
63 &self.g
64 }
65
66 #[must_use]
68 pub fn y(&self) -> &Mpint {
69 &self.y
70 }
71}
72
73impl Decode for DsaPublicKey {
74 type Error = Error;
75
76 fn decode(reader: &mut Decoder<impl Reader>) -> Result<Self> {
77 let p = Mpint::decode(reader)?;
78 let q = Mpint::decode(reader)?;
79 let g = Mpint::decode(reader)?;
80 let y = Mpint::decode(reader)?;
81 Self::new(p, q, g, y)
82 }
83}
84
85impl Hash for DsaPublicKey {
86 #[inline]
87 fn hash<H: Hasher>(&self, state: &mut H) {
88 self.p.as_bytes().hash(state);
89 self.q.as_bytes().hash(state);
90 self.g.as_bytes().hash(state);
91 self.y.as_bytes().hash(state);
92 }
93}
94
95#[cfg(feature = "dsa")]
96impl TryFrom<DsaPublicKey> for dsa::VerifyingKey {
97 type Error = Error;
98
99 fn try_from(key: DsaPublicKey) -> Result<dsa::VerifyingKey> {
100 dsa::VerifyingKey::try_from(&key)
101 }
102}
103
104#[cfg(feature = "dsa")]
105impl TryFrom<&DsaPublicKey> for dsa::VerifyingKey {
106 type Error = Error;
107
108 fn try_from(key: &DsaPublicKey) -> Result<dsa::VerifyingKey> {
109 let p = Uint::from(&key.p);
110 let q = Uint::from(&key.q);
111 let g = Uint::from(&key.g);
112 let y = Uint::from(&key.y);
113
114 let components = dsa::Components::from_components(p, q, g)?;
115 dsa::VerifyingKey::from_components(components, y).map_err(|_| Error::Crypto)
116 }
117}
118
119#[cfg(feature = "dsa")]
120impl TryFrom<dsa::VerifyingKey> for DsaPublicKey {
121 type Error = Error;
122
123 fn try_from(key: dsa::VerifyingKey) -> Result<DsaPublicKey> {
124 DsaPublicKey::try_from(&key)
125 }
126}
127
128#[cfg(feature = "dsa")]
129impl TryFrom<&dsa::VerifyingKey> for DsaPublicKey {
130 type Error = Error;
131
132 fn try_from(key: &dsa::VerifyingKey) -> Result<DsaPublicKey> {
133 Self::new(
134 key.components().p().as_ref().try_into()?,
135 key.components().q().as_ref().try_into()?,
136 key.components().g().as_ref().try_into()?,
137 key.y().as_ref().try_into()?,
138 )
139 }
140}