Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AES electronic codebook implementation and example #145

Merged
merged 3 commits into from
May 28, 2020
Merged
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ members = [
"examples/rtfm-demo",
"examples/spi-demo",
"examples/twi-ssd1306",
"examples/ecb-demo",
]

[profile.dev]
Expand Down
28 changes: 28 additions & 0 deletions examples/ecb-demo/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
[package]
name = "ecb-demo"
version = "0.0.1"
edition = "2018"
authors = [ "Thales Fragoso <thales.fragosoz@gmail.com>"]

[dependencies]
cortex-m = "0.6.2"
cortex-m-rt = "0.6.12"
rtt-target = {version = "0.2.0", features = ["cortex-m"] }

nrf52810-hal = { path = "../../nrf52810-hal", features = ["rt"], optional = true }
nrf52832-hal = { path = "../../nrf52832-hal", features = ["rt"], optional = true }
nrf52840-hal = { path = "../../nrf52840-hal", features = ["rt"], optional = true }
nrf52833-hal = { path = "../../nrf52833-hal", features = ["rt"], optional = true }
nrf51-hal = { path = "../../nrf51-hal", features = ["rt"], optional = true}

[[bin]]
name = "ecb-demo"
doc = false
test = false

[features]
51 = ["nrf51-hal"]
52810 = ["nrf52810-hal"]
52832 = ["nrf52832-hal"]
52840 = ["nrf52840-hal"]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We now have support for the 52833 as well

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also the new HAL needs to reexport this

52833 = ["nrf52833-hal"]
46 changes: 46 additions & 0 deletions examples/ecb-demo/Embed.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
[probe]
# The index of the probe in the connected probe list.
# probe_index = 0
# The protocol to be used for communicating with the target.
protocol = "Swd"
# The speed in kHz of the data link to the target.
# speed = 1337

[flashing]
# Whether or not the target should be flashed.
enabled = true
# Whether or not the target should be halted after flashing.
halt_afterwards = false
# Whether or not bytes erased but not rewritten with data from the ELF
# should be restored with their contents before erasing.
restore_unwritten_bytes = false
# The path where an SVG of the assembled flash layout should be written to.
# flash_layout_output_path = "out.svg"

[general]
# The chip name of the chip to be debugged.
# chip = "nRF52832"
# A list of chip descriptions to be loaded during runtime.
chip_descriptions = []
# The default log level to be used.
log_level = "Warn"

[rtt]
# Whether or not an RTTUI should be opened after flashing.
# This is exclusive and cannot be used with GDB at the moment.
enabled = true
# A list of channel associations to be displayed. If left empty, all channels are displayed.
channels = [
# { up = 0, down = 0, name = "name" }
]
# The duration in ms for which the logger should retry to attach to RTT.
timeout = 3000
# Whether timestamps in the RTTUI are enabled
show_timestamps = true

[gdb]
# Whether or not a GDB server should be opened after flashing.
# This is exclusive and cannot be used with RTT at the moment.
enabled = false
# The connection string in host:port format wher the GDB server will open a socket.
# gdb_connection_string
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it normal to check this file into git?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, this file is meant to be checked into git, assuming you/your users use cargo embed :)

19 changes: 19 additions & 0 deletions examples/ecb-demo/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# AES electronic codebook mode encryption demo

Choose the microcontroller with one of the following features:
- 51
- 52810
- 52832
- 52840

Also, if using `cargo-embed`, change the `chip` and `protocol` fields in [Embed.toml](Embed.toml).

This demo uses the [rtt-target](https://crates.io/crates/rtt-target) crate for communication.

If using `cargo-embed`, just run

```console
$ cargo embed --release --features=52832 --target=thumbv7em-none-eabihf
```

Replace `52832` and `thumbv7em-none-eabihf` with the correct feature and target for your microcontroller.
64 changes: 64 additions & 0 deletions examples/ecb-demo/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
#![no_std]
#![no_main]

// Import the right HAL/PAC crate, depending on the target chip
#[cfg(feature = "51")]
pub use nrf51_hal as hal;
#[cfg(feature = "52810")]
pub use nrf52810_hal as hal;
#[cfg(feature = "52832")]
pub use nrf52832_hal as hal;
#[cfg(feature = "52833")]
pub use nrf52833_hal as hal;
#[cfg(feature = "52840")]
pub use nrf52840_hal as hal;

use {
core::{
panic::PanicInfo,
sync::atomic::{compiler_fence, Ordering},
},
cortex_m_rt::entry,
hal::{Clocks, Ecb},
rtt_target::{rprint, rprintln, rtt_init_print},
};

const MSG: [u8; 16] = *b"Message to encry";
const KEY: [u8; 16] = *b"aaaaaaaaaaaaaaaa";
const CIPHER_MSG: [u8; 16] = [
0xFE, 0xF1, 0x63, 0x82, 0xB4, 0x54, 0x6B, 0xE4, 0xEB, 0x9A, 0x5C, 0x0E, 0xB6, 0x0E, 0x49, 0x2F,
];

#[entry]
fn main() -> ! {
let p = hal::pac::Peripherals::take().unwrap();

let _clocks = Clocks::new(p.CLOCK).enable_ext_hfosc();
rtt_init_print!();

let mut ecb = Ecb::init(p.ECB);

loop {
rprintln!("Starting Encryption\n");
rprintln!("Clear text: {}", core::str::from_utf8(&MSG[..]).unwrap());

let cipher_text = ecb.encrypt_block(MSG, KEY).unwrap();
rprint!("Cipher Text: ");
for number in cipher_text.iter() {
rprint!("{:x} ", *number);
}
assert_eq!(cipher_text, CIPHER_MSG);
rprintln!("\r\n Encryption Done\n");

cortex_m::asm::delay(136_000_000);
}
}

#[inline(never)]
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
rprintln!("{}", info);
loop {
compiler_fence(Ordering::SeqCst);
}
}
98 changes: 98 additions & 0 deletions nrf-hal-common/src/ecb.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
//! HAL interface to the AES electronic codebook mode encryption.
//!
//! The ECB encryption block supports 128 bit AES encryption (encryption only, not decryption).

use crate::target::ECB;
use core::sync::atomic::{compiler_fence, Ordering};

/// Error type to represent a sharing conflict during encryption.
#[derive(Debug, Copy, Clone)]
pub struct EncryptionError {}

/// A safe, blocking wrapper around the AES-ECB peripheral.
///
/// It's really just blockwise AES and not an ECB stream cipher. Blocks can be
/// encrypted by calling `crypt_block`.
pub struct Ecb {
regs: ECB,
}

impl Ecb {
/// Takes ownership of the `ECB` peripheral, returning a safe wrapper.
pub fn init(regs: ECB) -> Self {
// Disable all interrupts
regs.intenclr
.write(|w| w.endecb().clear().errorecb().clear());

// NOTE(unsafe) 1 is a valid pattern to write to this register
regs.tasks_stopecb.write(|w| unsafe { w.bits(1) });
Self { regs }
}

/// Destroys `self`, giving the `ECB` peripheral back.
pub fn into_inner(self) -> ECB {
// Clear all events
self.regs.events_endecb.reset();
self.regs.events_errorecb.reset();

self.regs
}

/// Blocking encryption.
///
/// Encrypts a `block` with `key`.
///
/// # Errors
///
/// An error will be returned when the AES hardware raises an `ERRORECB`
/// event. This can happen when an operation is started that shares the AES
/// hardware resources with the AES ECB peripheral while an encryption
/// operation is running.
pub fn encrypt_block(
&mut self,
block: [u8; 16],
key: [u8; 16],
) -> Result<[u8; 16], EncryptionError> {
#[repr(C)]
struct EcbData {
key: [u8; 16],
clear_text: [u8; 16],
cipher_text: [u8; 16],
}

// We allocate the DMA'd buffer on the stack, which means that we must
// not panic or return before the AES operation is finished.
let mut buf = EcbData {
key,
clear_text: block,
cipher_text: [0; 16],
};

// NOTE(unsafe) Any 32bits pattern is safe to write to this register
self.regs
.ecbdataptr
.write(|w| unsafe { w.bits(&mut buf as *mut _ as u32) });

// Clear all events
self.regs.events_endecb.reset();
self.regs.events_errorecb.reset();

// "Preceding reads and writes cannot be moved past subsequent writes."
compiler_fence(Ordering::Release);
// NOTE(unsafe) 1 is a valid pattern to write to this register
self.regs.tasks_startecb.write(|w| unsafe { w.bits(1) });

while self.regs.events_endecb.read().bits() == 0
&& self.regs.events_errorecb.read().bits() == 0
{}

// "Subsequent reads and writes cannot be moved ahead of preceding reads."
compiler_fence(Ordering::Acquire);

if self.regs.events_errorecb.read().bits() == 1 {
// It's ok to return here, the events will be cleared before the next encryption
return Err(EncryptionError {});
}
Ok(buf.cipher_text)
}
}
2 changes: 2 additions & 0 deletions nrf-hal-common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ pub mod adc;
pub mod clocks;
#[cfg(not(feature = "51"))]
pub mod delay;
#[cfg(not(feature = "9160"))]
pub mod ecb;
pub mod gpio;
#[cfg(not(feature = "9160"))]
pub mod rng;
Expand Down
1 change: 1 addition & 0 deletions nrf51-hal/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ pub mod prelude {

pub use crate::adc::Adc;
pub use crate::clocks::Clocks;
pub use crate::ecb::Ecb;
pub use crate::rtc::Rtc;
pub use crate::spi::Spi;
pub use crate::temp::Temp;
Expand Down
1 change: 1 addition & 0 deletions nrf52810-hal/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ pub mod prelude {

pub use crate::clocks::Clocks;
pub use crate::delay::Delay;
pub use crate::ecb::Ecb;
pub use crate::saadc::Saadc;
pub use crate::spim::Spim;
pub use crate::temp::Temp;
Expand Down
1 change: 1 addition & 0 deletions nrf52832-hal/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ pub mod prelude {

pub use crate::clocks::Clocks;
pub use crate::delay::Delay;
pub use crate::ecb::Ecb;
pub use crate::rtc::Rtc;
pub use crate::saadc::Saadc;
pub use crate::spim::Spim;
Expand Down
1 change: 1 addition & 0 deletions nrf52833-hal/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ pub mod prelude {

pub use crate::clocks::Clocks;
pub use crate::delay::Delay;
pub use crate::ecb::Ecb;
pub use crate::saadc::Saadc;
pub use crate::spim::Spim;
pub use crate::temp::Temp;
Expand Down
1 change: 1 addition & 0 deletions nrf52840-hal/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ pub mod prelude {

pub use crate::clocks::Clocks;
pub use crate::delay::Delay;
pub use crate::ecb::Ecb;
pub use crate::saadc::Saadc;
pub use crate::spim::Spim;
pub use crate::temp::Temp;
Expand Down
2 changes: 2 additions & 0 deletions scripts/build.sh
Original file line number Diff line number Diff line change
Expand Up @@ -43,5 +43,7 @@ echo Building examples/twi-ssd1306...
cargo build --manifest-path examples/twi-ssd1306/Cargo.toml
echo Building examples/twi-ssd1306...
cargo build --manifest-path examples/twi-ssd1306/Cargo.toml --no-default-features --features="52840" --target thumbv7em-none-eabi
echo Building examples/ecb-demo...
cargo build --manifest-path examples/ecb-demo/Cargo.toml --features=52832
echo Checking source code formatting...
cargo +stable fmt -- --check