1
use generic_array::GenericArray;
2
use hpke::kem::{DhP256HkdfSha256, Kem as KemTrait};
3
use hpke::{Deserializable, Serializable};
4
use serde::de::Error;
5
use serde::{Deserialize, Deserializer, Serialize, Serializer};
6

            
7
// Helpful aliases for the HPKE types we use in vault encryption
8

            
9
pub(crate) type VaultP256Kem = DhP256HkdfSha256;
10
pub(crate) type VaultP256PublicKey = <DhP256HkdfSha256 as KemTrait>::PublicKey;
11
pub(crate) type VaultP256PrivateKey = <DhP256HkdfSha256 as KemTrait>::PrivateKey;
12
pub(crate) type VaultP256EncappedKey = <DhP256HkdfSha256 as KemTrait>::EncappedKey;
13

            
14
// A previous version of hpke had serde impls. For backwards compatibility, we re-implement that
15
// here. All this is is casting to/from GenericArray, and using GenericArray's serde impl, just as
16
// the original did it:
17
// https://github.com/rozbb/rust-hpke/blob/57fce26b436f47846ee4f9a972ea0675786101c9/src/serde_impls.rs#L42-L74
18

            
19
// We put everything in its own module so we can use the `with` field attribute
20
// https://serde.rs/field-attrs.html#with
21

            
22
// Impl serde for $t: hpke::{Serializable, Deserializable}
23
macro_rules! impl_serde {
24
    ($modname:ident, $t:ty) => {
25
        pub(crate) mod $modname {
26
            use super::*;
27

            
28
45060
            pub(crate) fn serialize<S: Serializer>(
29
45060
                val: &$t,
30
45060
                serializer: S,
31
45060
            ) -> Result<S::Ok, S::Error> {
32
45060
                let arr = val.to_bytes();
33
45060
                arr.serialize(serializer)
34
45060
            }
35

            
36
10941
            pub(crate) fn deserialize<'de, D: Deserializer<'de>>(
37
10941
                deserializer: D,
38
10941
            ) -> Result<$t, D::Error> {
39
10941
                let arr = GenericArray::<u8, <$t as Serializable>::OutputSize>::deserialize(
40
10941
                    deserializer,
41
10941
                )?;
42
10941
                <$t>::from_bytes(&arr).map_err(D::Error::custom)
43
10941
            }
44
        }
45
    };
46
}
47

            
48
impl_serde!(serde_pubkey, VaultP256PublicKey);
49
impl_serde!(serde_privkey, VaultP256PrivateKey);
50
impl_serde!(serde_encapped_key, VaultP256EncappedKey);