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
use super::*;
use crate::{AlgorithmType, CryptoCtx, HandleManagers};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PublicKeyEncoding {
Raw,
Pkcs8,
Pem,
Sec,
CompressedSec,
Local,
}
#[derive(Clone)]
pub enum PublicKey {
Signature(SignaturePublicKey),
KeyExchange(KxPublicKey),
}
impl PublicKey {
pub(crate) fn into_signature_public_key(self) -> Result<SignaturePublicKey, CryptoError> {
match self {
PublicKey::Signature(pk) => Ok(pk),
_ => bail!(CryptoError::InvalidHandle),
}
}
pub(crate) fn into_kx_public_key(self) -> Result<KxPublicKey, CryptoError> {
match self {
PublicKey::KeyExchange(pk) => Ok(pk),
_ => bail!(CryptoError::InvalidHandle),
}
}
fn import(
alg_type: AlgorithmType,
alg_str: &str,
encoded: &[u8],
encoding: PublicKeyEncoding,
) -> Result<PublicKey, CryptoError> {
match alg_type {
AlgorithmType::Signatures => Ok(PublicKey::Signature(SignaturePublicKey::import(
SignatureAlgorithm::try_from(alg_str)?,
encoded,
encoding,
)?)),
_ => bail!(CryptoError::InvalidOperation),
}
}
fn export(&self, encoding: PublicKeyEncoding) -> Result<Vec<u8>, CryptoError> {
match self {
PublicKey::Signature(pk) => pk.export(encoding),
PublicKey::KeyExchange(pk) => pk.export(encoding),
}
}
fn verify(handles: &HandleManagers, pk_handle: Handle) -> Result<(), CryptoError> {
match handles.publickey.get(pk_handle)? {
PublicKey::Signature(pk) => SignaturePublicKey::verify(pk),
PublicKey::KeyExchange(pk) => pk.verify(),
}
}
}
impl CryptoCtx {
pub fn publickey_import(
&self,
alg_type: AlgorithmType,
alg_str: &str,
encoded: &[u8],
encoding: PublicKeyEncoding,
) -> Result<Handle, CryptoError> {
let pk = PublicKey::import(alg_type, alg_str, encoded, encoding)?;
let handle = self.handles.publickey.register(pk)?;
Ok(handle)
}
pub fn publickey_export(
&self,
pk_handle: Handle,
encoding: PublicKeyEncoding,
) -> Result<Handle, CryptoError> {
let pk = self.handles.publickey.get(pk_handle)?;
let encoded = pk.export(encoding)?;
let array_output_handle = ArrayOutput::register(&self.handles, encoded)?;
Ok(array_output_handle)
}
pub fn publickey_verify(&self, pk: Handle) -> Result<(), CryptoError> {
PublicKey::verify(&self.handles, pk)
}
pub fn publickey_close(&self, pk: Handle) -> Result<(), CryptoError> {
self.handles.publickey.close(pk)
}
}