Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 37 additions & 25 deletions src/rust/src/backend/cmac.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,22 +14,54 @@ use crate::{exceptions, types};
module = "cryptography.hazmat.bindings._rust.openssl.cmac",
name = "CMAC"
)]
struct Cmac {
pub(crate) struct Cmac {
ctx: Option<cryptography_openssl::cmac::Cmac>,
}

impl Cmac {
fn new_bytes(key: &[u8], cipher: &openssl::cipher::CipherRef) -> CryptographyResult<Self> {
pub(crate) fn new_bytes(
key: &[u8],
cipher: &openssl::cipher::CipherRef,
) -> CryptographyResult<Self> {
let ctx = cryptography_openssl::cmac::Cmac::new(key, cipher)?;
Ok(Cmac { ctx: Some(ctx) })
}

fn update_bytes(&mut self, data: &[u8]) -> CryptographyResult<()> {
pub(crate) fn new_with_algorithm(
py: pyo3::Python<'_>,
algorithm: &pyo3::Bound<'_, pyo3::PyAny>,
) -> CryptographyResult<Self> {
if !algorithm.is_instance(&types::BLOCK_CIPHER_ALGORITHM.get(py)?)? {
return Err(CryptographyError::from(
pyo3::exceptions::PyTypeError::new_err(
"Expected instance of BlockCipherAlgorithm.",
),
));
}

let cipher = cipher_registry::get_cipher(py, algorithm.clone(), types::CBC.get(py)?)?
.ok_or_else(|| {
exceptions::UnsupportedAlgorithm::new_err((
"CMAC is not supported with this algorithm",
exceptions::Reasons::UNSUPPORTED_CIPHER,
))
})?;

let key = algorithm
.getattr(pyo3::intern!(py, "key"))?
.extract::<CffiBuf<'_>>()?;

Cmac::new_bytes(key.as_bytes(), cipher)
}

pub(crate) fn update_bytes(&mut self, data: &[u8]) -> CryptographyResult<()> {
self.get_mut_ctx()?.update(data)?;
Ok(())
}

fn finalize_bytes(&mut self) -> CryptographyResult<cryptography_openssl::hmac::DigestBytes> {
pub(crate) fn finalize_bytes(
&mut self,
) -> CryptographyResult<cryptography_openssl::hmac::DigestBytes> {
let data = self.get_mut_ctx()?.finish()?;
self.ctx = None;
Ok(data)
Expand Down Expand Up @@ -61,27 +93,7 @@ impl Cmac {
) -> CryptographyResult<Self> {
let _ = backend;

if !algorithm.is_instance(&types::BLOCK_CIPHER_ALGORITHM.get(py)?)? {
return Err(CryptographyError::from(
pyo3::exceptions::PyTypeError::new_err(
"Expected instance of BlockCipherAlgorithm.",
),
));
}

let cipher = cipher_registry::get_cipher(py, algorithm.clone(), types::CBC.get(py)?)?
.ok_or_else(|| {
exceptions::UnsupportedAlgorithm::new_err((
"CMAC is not supported with this algorithm",
exceptions::Reasons::UNSUPPORTED_CIPHER,
))
})?;

let key = algorithm
.getattr(pyo3::intern!(py, "key"))?
.extract::<CffiBuf<'_>>()?;

Cmac::new_bytes(key.as_bytes(), cipher)
Cmac::new_with_algorithm(py, &algorithm)
}

fn update(&mut self, data: CffiBuf<'_>) -> CryptographyResult<()> {
Expand Down