Skip to main content

paysec_crypto/
lib.rs

1use std::error::Error;
2
3/// Base trait implemented by cryptographic providers.
4pub trait CryptoProvider {
5    type Error: Error + 'static;
6}
7
8/// AES single-block encryption and decryption.
9///
10/// The key type is intentionally generic so providers can operate on
11/// clear key material, opaque key handles, or other key representations.
12pub trait AesBlockCipher<K: ?Sized>: CryptoProvider {
13    fn encrypt_block(&self, key: &K, block: &[u8; 16]) -> Result<[u8; 16], Self::Error>;
14
15    fn decrypt_block(&self, key: &K, block: &[u8; 16]) -> Result<[u8; 16], Self::Error>;
16}
17
18/// AES-CBC encryption and decryption without padding.
19///
20/// Input data must be aligned to the AES block size.
21pub trait AesCbc<K: ?Sized>: CryptoProvider {
22    fn encrypt_cbc(&self, key: &K, iv: &[u8; 16], plaintext: &[u8])
23    -> Result<Vec<u8>, Self::Error>;
24
25    fn decrypt_cbc(
26        &self,
27        key: &K,
28        iv: &[u8; 16],
29        ciphertext: &[u8],
30    ) -> Result<Vec<u8>, Self::Error>;
31}
32
33/// AES-CMAC calculation.
34pub trait AesCmac<K: ?Sized>: CryptoProvider {
35    fn calculate_cmac(&self, key: &K, message: &[u8]) -> Result<[u8; 16], Self::Error>;
36}
37
38/// Supported AES key sizes.
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub enum AesKeySize {
41    Bits128,
42    Bits192,
43    Bits256,
44}
45
46impl AesKeySize {
47    pub const fn bytes(self) -> usize {
48        match self {
49            Self::Bits128 => 16,
50            Self::Bits192 => 24,
51            Self::Bits256 => 32,
52        }
53    }
54}
55
56impl TryFrom<usize> for AesKeySize {
57    type Error = &'static str;
58
59    fn try_from(value: usize) -> Result<Self, Self::Error> {
60        match value {
61            16 => Ok(Self::Bits128),
62            24 => Ok(Self::Bits192),
63            32 => Ok(Self::Bits256),
64            _ => Err("unsupported AES key length"),
65        }
66    }
67}
68
69/// Derive a key using one or more AES-CMAC derivation inputs.
70///
71/// The derived key type is provider-specific. Software providers may return
72/// raw key material, while an HSM provider may return an opaque key handle.
73pub trait AesCmacKeyDerivation<K: ?Sized>: CryptoProvider {
74    type DerivedKey;
75
76    fn derive_key_cmac(
77        &self,
78        key: &K,
79        derivation_inputs: &[&[u8]],
80        output_len: usize,
81    ) -> Result<Self::DerivedKey, Self::Error>;
82}