wasi_crypto/asymmetric_common/
publickey.rs1use super::*;
2use crate::{AlgorithmType, CryptoCtx, HandleManagers};
3
4#[derive(Clone, Copy, Debug, Eq, PartialEq)]
5pub enum PublicKeyEncoding {
6 Raw,
7 Pkcs8,
8 Pem,
9 Sec,
10 Local,
11}
12
13#[derive(Clone)]
14pub enum PublicKey {
15 Signature(SignaturePublicKey),
16 KeyExchange(KxPublicKey),
17}
18
19impl PublicKey {
20 pub(crate) fn into_signature_public_key(self) -> Result<SignaturePublicKey, CryptoError> {
21 match self {
22 PublicKey::Signature(pk) => Ok(pk),
23 _ => bail!(CryptoError::InvalidHandle),
24 }
25 }
26
27 pub(crate) fn into_kx_public_key(self) -> Result<KxPublicKey, CryptoError> {
28 match self {
29 PublicKey::KeyExchange(pk) => Ok(pk),
30 _ => bail!(CryptoError::InvalidHandle),
31 }
32 }
33
34 fn import(
35 alg_type: AlgorithmType,
36 alg_str: &str,
37 encoded: &[u8],
38 encoding: PublicKeyEncoding,
39 ) -> Result<PublicKey, CryptoError> {
40 match alg_type {
41 AlgorithmType::Signatures => Ok(PublicKey::Signature(SignaturePublicKey::import(
42 SignatureAlgorithm::try_from(alg_str)?,
43 encoded,
44 encoding,
45 )?)),
46 AlgorithmType::KeyExchange => bail!(CryptoError::NotImplemented),
47 _ => bail!(CryptoError::InvalidOperation),
48 }
49 }
50
51 fn export(&self, encoding: PublicKeyEncoding) -> Result<Vec<u8>, CryptoError> {
52 match self {
53 PublicKey::Signature(pk) => pk.export(encoding),
54 PublicKey::KeyExchange(pk) => pk.export(encoding),
55 }
56 }
57
58 fn verify(handles: &HandleManagers, pk_handle: Handle) -> Result<(), CryptoError> {
59 match handles.publickey.get(pk_handle)? {
60 PublicKey::Signature(pk) => SignaturePublicKey::verify(pk),
61 PublicKey::KeyExchange(pk) => pk.verify(),
62 }
63 }
64}
65
66impl CryptoCtx {
67 pub fn publickey_import(
68 &self,
69 alg_type: AlgorithmType,
70 alg_str: &str,
71 encoded: &[u8],
72 encoding: PublicKeyEncoding,
73 ) -> Result<Handle, CryptoError> {
74 let pk = PublicKey::import(alg_type, alg_str, encoded, encoding)?;
75 let handle = self.handles.publickey.register(pk)?;
76 Ok(handle)
77 }
78
79 pub fn publickey_export(
80 &self,
81 pk_handle: Handle,
82 encoding: PublicKeyEncoding,
83 ) -> Result<Handle, CryptoError> {
84 let pk = self.handles.publickey.get(pk_handle)?;
85 let encoded = pk.export(encoding)?;
86 let array_output_handle = ArrayOutput::register(&self.handles, encoded)?;
87 Ok(array_output_handle)
88 }
89
90 pub fn publickey_verify(&self, pk: Handle) -> Result<(), CryptoError> {
91 PublicKey::verify(&self.handles, pk)
92 }
93
94 pub fn publickey_close(&self, pk: Handle) -> Result<(), CryptoError> {
95 self.handles.publickey.close(pk)
96 }
97}