use std::sync::Arc;
use async_trait::async_trait;
use zeroize::Zeroizing;
use crate::{
CryptoAlgorithm, EncryptionOracle, HSM, InterfaceError, InterfaceResult, KeyMetadata, KeyType,
encryption_oracle::EncryptedContent,
};
pub struct HsmEncryptionOracle {
hsm: Arc<dyn HSM + Send + Sync>,
}
impl HsmEncryptionOracle {
pub fn new(hsm: Arc<dyn HSM + Send + Sync>) -> Self {
HsmEncryptionOracle { hsm }
}
}
#[async_trait]
impl EncryptionOracle for HsmEncryptionOracle {
async fn encrypt(
&self,
uid: &str,
data: &[u8],
cryptographic_algorithm: Option<CryptoAlgorithm>,
authenticated_encryption_additional_data: Option<&[u8]>,
) -> InterfaceResult<EncryptedContent> {
if authenticated_encryption_additional_data.is_some() {
return Err(InterfaceError::InvalidRequest(
"Additional authenticated data are not supported on HSMs for now".to_owned(),
));
}
let (slot_id, key_id) = parse_uid(uid)?;
let cryptographic_algorithm = if let Some(ca) = cryptographic_algorithm {
ca
} else {
match self.hsm.get_key_type(slot_id, &key_id).await? {
None => {
return Err(InterfaceError::InvalidRequest(
"The key {}type is not known".to_owned(),
))
}
Some(key_type) => match key_type {
KeyType::AesKey => CryptoAlgorithm::AesGcm,
KeyType::RsaPublicKey => CryptoAlgorithm::RsaOaep,
KeyType::RsaPrivateKey => {
return Err(InterfaceError::Default(
"An RSA private key cannot be used to decrypt".to_owned(),
))
}
},
}
};
self.hsm
.encrypt(slot_id, &key_id, cryptographic_algorithm, data)
.await
}
async fn decrypt(
&self,
uid: &str,
data: &[u8],
cryptographic_algorithm: Option<CryptoAlgorithm>,
authenticated_encryption_additional_data: Option<&[u8]>,
) -> InterfaceResult<Zeroizing<Vec<u8>>> {
if authenticated_encryption_additional_data.is_some() {
return Err(InterfaceError::InvalidRequest(
"Additional authenticated data are not supported on HSMs for now".to_owned(),
));
}
let (slot_id, key_id) = parse_uid(uid)?;
let cryptographic_algorithm = if let Some(ca) = cryptographic_algorithm {
ca
} else {
match self.hsm.get_key_type(slot_id, &key_id).await? {
None => {
return Err(InterfaceError::InvalidRequest(
"The key {}type is not known".to_owned(),
))
}
Some(key_type) => match key_type {
KeyType::AesKey => CryptoAlgorithm::AesGcm,
KeyType::RsaPrivateKey => CryptoAlgorithm::RsaOaep,
KeyType::RsaPublicKey => {
return Err(InterfaceError::Default(
"An RSA public key cannot be used to decrypt".to_owned(),
))
}
},
}
};
self.hsm
.decrypt(slot_id, &key_id, cryptographic_algorithm, data)
.await
}
async fn get_key_type(&self, key_id: &str) -> InterfaceResult<Option<KeyType>> {
let (slot_id, key_id) = parse_uid(key_id)?;
self.hsm.get_key_type(slot_id, &key_id).await
}
async fn get_key_metadata(&self, key_id: &str) -> InterfaceResult<Option<KeyMetadata>> {
let (slot_id, key_id) = parse_uid(key_id)?;
self.hsm.get_key_metadata(slot_id, &key_id).await
}
}
fn parse_uid(uid: &str) -> InterfaceResult<(usize, Vec<u8>)> {
let (slot_id, key_id) = uid
.trim_start_matches("hsm::")
.split_once("::")
.ok_or_else(|| {
InterfaceError::InvalidRequest(
"An HSM create request must have a uid in the form of 'hsm::<slot_id>::<key_id>'"
.to_owned(),
)
})?;
let slot_id = slot_id.parse::<usize>().map_err(|e| {
InterfaceError::InvalidRequest(format!("The slot_id must be a valid unsigned integer: {e}"))
})?;
Ok((slot_id, key_id.as_bytes().to_vec()))
}