Skip to content

Commit 27dd5db

Browse files
author
Jakob Gerstmayer
committed
Added basic cbc encryption support
1 parent 165e52e commit 27dd5db

File tree

1 file changed

+61
-1
lines changed

1 file changed

+61
-1
lines changed

hal/src/aes.rs

Lines changed: 61 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -777,6 +777,66 @@ impl Aes {
777777
Ok(())
778778
}
779779

780+
781+
/// Encrypt using the Cipher block chaining (CBC) algorithm.
782+
///
783+
/// # Panics
784+
///
785+
/// * Key is not 128-bits long `[u32; 4]` or 256-bits long `[u32; 8]`.
786+
///
787+
/// # Example
788+
/// TODO CHANGE
789+
/// ```no_run
790+
/// use stm32wlxx_hal::{aes::Aes, pac};
791+
///
792+
/// let mut dp: pac::Peripherals = pac::Peripherals::take().unwrap();
793+
/// let mut aes: Aes = Aes::new(dp.AES, &mut dp.RCC);
794+
///
795+
/// const KEY: [u32; 4] = [0; 4];
796+
/// const IV: [u32, 4] = [0; 4];
797+
///
798+
/// let plaintext: [u32; 4] = [0xf34481ec, 0x3cc627ba, 0xcd5dc3fb, 0x08f273e6];
799+
/// let mut ciphertext: [u32; 4] = [0; 4];
800+
/// aes.(encrypt_cbc(&KEY, &IV, &plaintext, &mut ciphertext)?;
801+
/// # Ok::<(), stm32wlxx_hal::aes::Error>(())
802+
/// ```
803+
pub fn encrypt_cbc(
804+
&mut self,
805+
key: &[u32],
806+
iv: &[u32; 4],
807+
plaintext: &[u32; 4],
808+
ciphertext: &mut [u32; 4],
809+
) -> Result<(), Error> {
810+
const ALGO: Algorithm = Algorithm::Cbc;
811+
const CHMOD2: bool = ALGO.chmod2();
812+
const CHMOD10: u8 = ALGO.chmod10();
813+
const MODE: u8 = Mode::Encryption.bits();
814+
815+
let keysize: KeySize = self.set_key(key);
816+
817+
self.aes.cr.write(|w| {
818+
w.en().enabled();
819+
w.datatype().variant(self.swap_mode);
820+
w.mode().bits(MODE);
821+
w.chmod2().bit(CHMOD2);
822+
w.chmod().bits(CHMOD10);
823+
w.ccfc().clear();
824+
w.errc().clear();
825+
w.ccfie().disabled();
826+
w.errie().disabled();
827+
w.dmainen().disabled();
828+
w.dmaouten().disabled();
829+
w.gcmph().bits(0); // do not care for ECB
830+
w.keysize().variant(keysize);
831+
w.npblb().bits(0) // no padding
832+
});
833+
834+
self.set_din(plaintext);
835+
self.poll_completion()?;
836+
self.dout(ciphertext);
837+
Ok(())
838+
}
839+
780840
/// Encrypt using the Galois counter mode (GCM) algorithm in-place.
781841
///
782842
/// # Panics
@@ -913,7 +973,7 @@ impl Aes {
913973
w.errie().disabled();
914974
w.dmainen().disabled();
915975
w.dmaouten().disabled();
916-
w.gcmph().bits(0); // do not care for ECB
976+
w.gcmph().bits(0); // do not care for CBC
917977
w.keysize().variant(keysize);
918978
w.npblb().bits(0) // no padding
919979
});

0 commit comments

Comments
 (0)