format services/aes

This commit is contained in:
bunnie 2024-01-14 22:03:57 +08:00
parent a6a28b9d9e
commit dbf8525572
6 changed files with 72 additions and 183 deletions

View file

@ -12,13 +12,12 @@
*/
mod soft;
pub use soft::{Aes128Soft, Aes192, Aes256Soft};
pub use cipher;
use cipher::{
consts::{U16, U8},
generic_array::GenericArray,
};
pub use soft::{Aes128Soft, Aes192, Aes256Soft};
/// 128-bit AES block
pub type Block = GenericArray<u8, U16>;
@ -32,23 +31,12 @@ mod vex;
// library is patched into functions that are oblivious to these features.
// so this library has to fall back on the legacy method of determining which build target
// is being specified.
#[cfg(all(
target_arch = "riscv32",
any(target_os = "none", target_os = "xous"),
))]
pub use vex::{Aes128, Aes256};
#[cfg(all(
not(target_arch = "riscv32"),
not(target_os = "none"),
not(target_os = "xous"),
))]
#[cfg(all(not(target_arch = "riscv32"), not(target_os = "none"), not(target_os = "xous"),))]
pub use soft::Aes128Soft as Aes128;
#[cfg(all(
not(target_arch = "riscv32"),
not(target_os = "none"),
not(target_os = "xous"),
))]
#[cfg(all(not(target_arch = "riscv32"), not(target_os = "none"), not(target_os = "xous"),))]
pub use soft::Aes256Soft as Aes256;
#[cfg(all(target_arch = "riscv32", any(target_os = "none", target_os = "xous"),))]
pub use vex::{Aes128, Aes256};
/// Size of an AES block (128-bits; 16-bytes)
pub const BLOCK_SIZE: usize = 16;

View file

@ -12,16 +12,18 @@
#[cfg_attr(target_pointer_width = "64", path = "soft/fixslice32.rs")]
pub(crate) mod fixslice;
use crate::Block;
use core::fmt;
use cipher::{
consts::{U16, U24, U32},
inout::InOut,
AlgorithmName, BlockBackend, BlockCipher, BlockClosure, BlockDecrypt, BlockEncrypt,
BlockSizeUser, Key, KeyInit, KeySizeUser, ParBlocksSizeUser,
AlgorithmName, BlockBackend, BlockCipher, BlockClosure, BlockDecrypt, BlockEncrypt, BlockSizeUser, Key,
KeyInit, KeySizeUser, ParBlocksSizeUser,
};
use core::fmt;
use fixslice::{BatchBlocks, FixsliceBlocks, FixsliceKeys128, FixsliceKeys192, FixsliceKeys256};
use crate::Block;
macro_rules! define_aes_impl {
(
$name:tt,
@ -38,26 +40,20 @@ macro_rules! define_aes_impl {
$doc:expr $(,)?
) => {
#[doc=$doc]
#[doc = "block cipher"]
///block cipher
#[derive(Clone)]
pub struct $name {
keys: $fixslice_keys,
}
impl $name {
pub fn key_size(&self) -> usize {
$key_bits as usize
}
pub fn key_size(&self) -> usize { $key_bits as usize }
#[inline(always)]
pub(crate) fn get_enc_backend(&self) -> $name_back_enc<'_> {
$name_back_enc(self)
}
pub(crate) fn get_enc_backend(&self) -> $name_back_enc<'_> { $name_back_enc(self) }
#[inline(always)]
pub(crate) fn get_dec_backend(&self) -> $name_back_dec<'_> {
$name_back_dec(self)
}
pub(crate) fn get_dec_backend(&self) -> $name_back_dec<'_> { $name_back_dec(self) }
}
impl KeySizeUser for $name {
@ -66,11 +62,7 @@ macro_rules! define_aes_impl {
impl KeyInit for $name {
#[inline]
fn new(key: &Key<Self>) -> Self {
Self {
keys: $fixslice_key_schedule(key.as_ref()),
}
}
fn new(key: &Key<Self>) -> Self { Self { keys: $fixslice_key_schedule(key.as_ref()) } }
}
impl BlockSizeUser for $name {
@ -97,16 +89,12 @@ macro_rules! define_aes_impl {
impl From<$name_enc> for $name {
#[inline]
fn from(enc: $name_enc) -> $name {
enc.inner
}
fn from(enc: $name_enc) -> $name { enc.inner }
}
impl From<&$name_enc> for $name {
#[inline]
fn from(enc: &$name_enc) -> $name {
enc.inner.clone()
}
fn from(enc: &$name_enc) -> $name { enc.inner.clone() }
}
impl fmt::Debug for $name {
@ -116,13 +104,11 @@ macro_rules! define_aes_impl {
}
impl AlgorithmName for $name {
fn write_alg_name(f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(stringify!($name))
}
fn write_alg_name(f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(stringify!($name)) }
}
#[doc=$doc]
#[doc = "block cipher (encrypt-only)"]
///block cipher (encrypt-only)
#[derive(Clone)]
pub struct $name_enc {
inner: $name,
@ -130,9 +116,7 @@ macro_rules! define_aes_impl {
impl $name_enc {
#[inline(always)]
pub(crate) fn get_enc_backend(&self) -> $name_back_enc<'_> {
self.inner.get_enc_backend()
}
pub(crate) fn get_enc_backend(&self) -> $name_back_enc<'_> { self.inner.get_enc_backend() }
}
impl BlockCipher for $name_enc {}
@ -172,7 +156,7 @@ macro_rules! define_aes_impl {
}
#[doc=$doc]
#[doc = "block cipher (decrypt-only)"]
///block cipher (decrypt-only)
#[derive(Clone)]
pub struct $name_dec {
inner: $name,
@ -180,9 +164,7 @@ macro_rules! define_aes_impl {
impl $name_dec {
#[inline(always)]
pub(crate) fn get_dec_backend(&self) -> $name_back_dec<'_> {
self.inner.get_dec_backend()
}
pub(crate) fn get_dec_backend(&self) -> $name_back_dec<'_> { self.inner.get_dec_backend() }
}
impl BlockCipher for $name_dec {}
@ -201,18 +183,12 @@ macro_rules! define_aes_impl {
impl From<$name_enc> for $name_dec {
#[inline]
fn from(enc: $name_enc) -> $name_dec {
Self { inner: enc.inner }
}
fn from(enc: $name_enc) -> $name_dec { Self { inner: enc.inner } }
}
impl From<&$name_enc> for $name_dec {
#[inline]
fn from(enc: &$name_enc) -> $name_dec {
Self {
inner: enc.inner.clone(),
}
}
fn from(enc: &$name_enc) -> $name_dec { Self { inner: enc.inner.clone() } }
}
impl BlockSizeUser for $name_dec {

View file

@ -15,10 +15,12 @@
#![allow(clippy::unreadable_literal)]
use crate::Block;
use core::convert::TryInto;
use cipher::{consts::U2, generic_array::GenericArray};
use crate::Block;
/// AES block batch size for this implementation
pub(crate) type FixsliceBlocks = U2;
@ -100,8 +102,7 @@ pub(crate) fn aes192_key_schedule(key: &[u8; 24]) -> FixsliceKeys192 {
loop {
for i in 0..8 {
rkeys[rk_off + i] =
(0x0f0f0f0f & (tmp[i] >> 4)) | (0xf0f0f0f0 & (rkeys[(rk_off - 8) + i] << 4));
rkeys[rk_off + i] = (0x0f0f0f0f & (tmp[i] >> 4)) | (0xf0f0f0f0 & (rkeys[(rk_off - 8) + i] << 4));
}
sub_bytes(&mut tmp);
@ -123,8 +124,7 @@ pub(crate) fn aes192_key_schedule(key: &[u8; 24]) -> FixsliceKeys192 {
let ui = tmp[i];
let mut ti = (0x0f0f0f0f & (rkeys[(rk_off - 16) + i] >> 4)) | (0xf0f0f0f0 & (ui << 4));
ti ^= 0x03030303 & (ui >> 6);
tmp[i] =
ti ^ (0xfcfcfcfc & (ti << 2)) ^ (0xf0f0f0f0 & (ti << 4)) ^ (0xc0c0c0c0 & (ti << 6));
tmp[i] = ti ^ (0xfcfcfcfc & (ti << 2)) ^ (0xf0f0f0f0 & (ti << 4)) ^ (0xc0c0c0c0 & (ti << 6));
}
rkeys[rk_off..(rk_off + 8)].copy_from_slice(&tmp);
rk_off += 8;
@ -961,13 +961,8 @@ fn sub_bytes_nots(state: &mut [u32]) {
///
/// Based on Käsper-Schwabe, similar to https://github.com/Ko-/aes-armcortexm.
macro_rules! define_mix_columns {
(
$name:ident,
$name_inv:ident,
$first_rotate:path,
$second_rotate:path
) => {
#[rustfmt::skip]
($name:ident, $name_inv:ident, $first_rotate:path, $second_rotate:path) => {
#[rustfmt::skip]
fn $name(state: &mut State) {
let (a0, a1, a2, a3, a4, a5, a6, a7) = (
state[0], state[1], state[2], state[3], state[4], state[5], state[6], state[7]
@ -1002,7 +997,7 @@ macro_rules! define_mix_columns {
state[7] = b7 ^ c6 ^ $second_rotate(c7);
}
#[rustfmt::skip]
#[rustfmt::skip]
fn $name_inv(state: &mut State) {
let (a0, a1, a2, a3, a4, a5, a6, a7) = (
state[0], state[1], state[2], state[3], state[4], state[5], state[6], state[7]
@ -1056,15 +1051,10 @@ macro_rules! define_mix_columns {
state[6] = d6 ^ e6 ^ $second_rotate(e6);
state[7] = d7 ^ e7 ^ $second_rotate(e7);
}
}
};
}
define_mix_columns!(
mix_columns_0,
inv_mix_columns_0,
rotate_rows_1,
rotate_rows_2
);
define_mix_columns!(mix_columns_0, inv_mix_columns_0, rotate_rows_1, rotate_rows_2);
define_mix_columns!(
mix_columns_1,
@ -1074,12 +1064,7 @@ define_mix_columns!(
);
#[cfg(not(aes_compact))]
define_mix_columns!(
mix_columns_2,
inv_mix_columns_2,
rotate_rows_and_columns_1_2,
rotate_rows_2
);
define_mix_columns!(mix_columns_2, inv_mix_columns_2, rotate_rows_and_columns_1_2, rotate_rows_2);
#[cfg(not(aes_compact))]
define_mix_columns!(
@ -1133,20 +1118,14 @@ fn shift_rows_3(state: &mut [u32]) {
}
#[inline(always)]
fn inv_shift_rows_1(state: &mut [u32]) {
shift_rows_3(state);
}
fn inv_shift_rows_1(state: &mut [u32]) { shift_rows_3(state); }
#[inline(always)]
fn inv_shift_rows_2(state: &mut [u32]) {
shift_rows_2(state);
}
fn inv_shift_rows_2(state: &mut [u32]) { shift_rows_2(state); }
#[cfg(not(aes_compact))]
#[inline(always)]
fn inv_shift_rows_3(state: &mut [u32]) {
shift_rows_1(state);
}
fn inv_shift_rows_3(state: &mut [u32]) { shift_rows_1(state); }
/// XOR the columns after the S-box during the key schedule round function.
///
@ -1160,8 +1139,7 @@ fn xor_columns(rkeys: &mut [u32], offset: usize, idx_xor: usize, idx_ror: u32) {
for i in 0..8 {
let off_i = offset + i;
let rk = rkeys[off_i - idx_xor] ^ (0x03030303 & ror(rkeys[off_i], idx_ror));
rkeys[off_i] =
rk ^ (0xfcfcfcfc & (rk << 2)) ^ (0xf0f0f0f0 & (rk << 4)) ^ (0xc0c0c0c0 & (rk << 6));
rkeys[off_i] = rk ^ (0xfcfcfcfc & (rk << 2)) ^ (0xf0f0f0f0 & (rk << 4)) ^ (0xc0c0c0c0 & (rk << 6));
}
}
@ -1313,29 +1291,19 @@ fn add_round_key(state: &mut State, rkey: &[u32]) {
}
#[inline(always)]
fn add_round_constant_bit(state: &mut [u32], bit: usize) {
state[bit] ^= 0x0000c000;
}
fn add_round_constant_bit(state: &mut [u32], bit: usize) { state[bit] ^= 0x0000c000; }
#[inline(always)]
fn ror(x: u32, y: u32) -> u32 {
x.rotate_right(y)
}
fn ror(x: u32, y: u32) -> u32 { x.rotate_right(y) }
#[inline(always)]
fn ror_distance(rows: u32, cols: u32) -> u32 {
(rows << 3) + (cols << 1)
}
fn ror_distance(rows: u32, cols: u32) -> u32 { (rows << 3) + (cols << 1) }
#[inline(always)]
fn rotate_rows_1(x: u32) -> u32 {
ror(x, ror_distance(1, 0))
}
fn rotate_rows_1(x: u32) -> u32 { ror(x, ror_distance(1, 0)) }
#[inline(always)]
fn rotate_rows_2(x: u32) -> u32 {
ror(x, ror_distance(2, 0))
}
fn rotate_rows_2(x: u32) -> u32 { ror(x, ror_distance(2, 0)) }
#[inline(always)]
#[rustfmt::skip]

View file

@ -1,13 +1,14 @@
#![cfg_attr(not(target_os = "none"), allow(dead_code))]
use crate::Block;
use cipher::{
consts::{U1, U16, U32},
generic_array::GenericArray,
inout::InOut,
AlgorithmName, BlockBackend, BlockCipher, BlockClosure, BlockDecrypt, BlockEncrypt,
BlockSizeUser, Key, KeyInit, KeySizeUser, ParBlocksSizeUser,
generic_array::GenericArray
AlgorithmName, BlockBackend, BlockCipher, BlockClosure, BlockDecrypt, BlockEncrypt, BlockSizeUser, Key,
KeyInit, KeySizeUser, ParBlocksSizeUser,
};
use crate::Block;
pub(crate) type BatchBlocks = GenericArray<Block, U1>;
use core::{arch::global_asm, convert::TryInto, fmt};
@ -306,8 +307,7 @@ pub(crate) const TD3: [u32; 256] = [
pub(crate) const RCON: [u32; 10] = [
0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000, 0x20000000, 0x40000000, 0x80000000,
0x1B000000,
0x36000000, /* for 128-bit blocks, Rijndael never uses more than 10 rcon values */
0x1B000000, 0x36000000, /* for 128-bit blocks, Rijndael never uses more than 10 rcon values */
];
global_asm!(
@ -315,77 +315,62 @@ global_asm!(
"vex_aes_enc_id_0:",
" .word 0x00b5050b", // vex_aes_enc_id a0, a1, a0, #0
" ret",
".global vex_aes_enc_id_1",
"vex_aes_enc_id_1:",
" .word 0x10b5050b", // vex_aes_enc_id a0, a1, a0, #1
" ret",
".global vex_aes_enc_id_2",
"vex_aes_enc_id_2:",
" .word 0x20b5050b", // vex_aes_enc_id a0, a1, a0, #2
" ret",
".global vex_aes_enc_id_3",
"vex_aes_enc_id_3:",
" .word 0x30b5050b", // vex_aes_enc_id a0, a1, a0, #3
" ret",
".global vex_aes_enc_id_last_0",
"vex_aes_enc_id_last_0:",
" .word 0x04b5050b", // vex_aes_enc_id_last a0, a1, a0, #0
" ret",
".global vex_aes_enc_id_last_1",
"vex_aes_enc_id_last_1:",
" .word 0x14b5050b", // vex_aes_enc_id_last a0, a1, a0, #1
" ret",
".global vex_aes_enc_id_last_2",
"vex_aes_enc_id_last_2:",
" .word 0x24b5050b", // vex_aes_enc_id_last a0, a1, a0, #2
" ret",
".global vex_aes_enc_id_last_3",
"vex_aes_enc_id_last_3:",
" .word 0x34b5050b", // vex_aes_enc_id_last a0, a1, a0, #3
" ret",
".global vex_aes_dec_id_0",
"vex_aes_dec_id_0:",
" .word 0x02b5050b", // vex_aes_dec_id a0, a1, a0, #0
" ret",
".global vex_aes_dec_id_1",
"vex_aes_dec_id_1:",
" .word 0x12b5050b", // vex_aes_dec_id a0, a1, a0, #1
" ret",
".global vex_aes_dec_id_2",
"vex_aes_dec_id_2:",
" .word 0x22b5050b", // vex_aes_dec_id a0, a1, a0, #2
" ret",
".global vex_aes_dec_id_3",
"vex_aes_dec_id_3:",
" .word 0x32b5050b", // vex_aes_dec_id a0, a1, a0, #3
" ret",
".global vex_aes_dec_id_last_0",
"vex_aes_dec_id_last_0:",
" .word 0x06b5050b", // vex_aes_dec_id_last a0, a1, a0, #0
" ret",
".global vex_aes_dec_id_last_1",
"vex_aes_dec_id_last_1:",
" .word 0x16b5050b", // vex_aes_dec_id_last a0, a1, a0, #1
" ret",
".global vex_aes_dec_id_last_2",
"vex_aes_dec_id_last_2:",
" .word 0x26b5050b", // vex_aes_dec_id_last a0, a1, a0, #2
" ret",
".global vex_aes_dec_id_last_3",
"vex_aes_dec_id_last_3:",
" .word 0x36b5050b", // vex_aes_dec_id_last a0, a1, a0, #3
@ -486,7 +471,7 @@ macro_rules! define_aes_impl {
$doc:expr $(,)?
) => {
#[doc=$doc]
#[doc = "block cipher"]
///block cipher
#[derive(Clone)]
pub struct $name {
enc_key: $vex_keys,
@ -494,30 +479,25 @@ macro_rules! define_aes_impl {
}
impl $name {
pub fn key_size(&self) -> usize {
$key_bits as usize
}
pub fn key_size(&self) -> usize { $key_bits as usize }
pub fn clear(&mut self) {
let nuke = self.enc_key.as_mut_ptr();
for i in 0..self.enc_key.len() {
unsafe{nuke.add(i).write_volatile(0)};
unsafe { nuke.add(i).write_volatile(0) };
}
let nuke = self.dec_key.as_mut_ptr();
for i in 0..self.dec_key.len() {
unsafe{nuke.add(i).write_volatile(0)};
unsafe { nuke.add(i).write_volatile(0) };
}
core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
}
#[inline(always)]
pub(crate) fn get_enc_backend(&self) -> $name_back_enc<'_> {
$name_back_enc(self)
}
pub(crate) fn get_enc_backend(&self) -> $name_back_enc<'_> { $name_back_enc(self) }
#[inline(always)]
pub(crate) fn get_dec_backend(&self) -> $name_back_dec<'_> {
$name_back_dec(self)
}
pub(crate) fn get_dec_backend(&self) -> $name_back_dec<'_> { $name_back_dec(self) }
}
impl KeySizeUser for $name {
@ -527,10 +507,7 @@ macro_rules! define_aes_impl {
impl KeyInit for $name {
#[inline]
fn new(key: &Key<Self>) -> Self {
Self {
enc_key: $vex_enc_key_schedule(key),
dec_key: $vex_dec_key_schedule(key),
}
Self { enc_key: $vex_enc_key_schedule(key), dec_key: $vex_dec_key_schedule(key) }
}
}
@ -558,16 +535,12 @@ macro_rules! define_aes_impl {
impl From<$name_enc> for $name {
#[inline]
fn from(enc: $name_enc) -> $name {
enc.inner
}
fn from(enc: $name_enc) -> $name { enc.inner }
}
impl From<&$name_enc> for $name {
#[inline]
fn from(enc: &$name_enc) -> $name {
enc.inner.clone()
}
fn from(enc: &$name_enc) -> $name { enc.inner.clone() }
}
impl fmt::Debug for $name {
@ -577,13 +550,11 @@ macro_rules! define_aes_impl {
}
impl AlgorithmName for $name {
fn write_alg_name(f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(stringify!($name))
}
fn write_alg_name(f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(stringify!($name)) }
}
#[doc=$doc]
#[doc = "block cipher (encrypt-only)"]
///block cipher (encrypt-only)
#[derive(Clone)]
pub struct $name_enc {
inner: $name,
@ -591,9 +562,7 @@ macro_rules! define_aes_impl {
impl $name_enc {
#[inline(always)]
pub(crate) fn get_enc_backend(&self) -> $name_back_enc<'_> {
self.inner.get_enc_backend()
}
pub(crate) fn get_enc_backend(&self) -> $name_back_enc<'_> { self.inner.get_enc_backend() }
}
impl BlockCipher for $name_enc {}
@ -633,7 +602,7 @@ macro_rules! define_aes_impl {
}
#[doc=$doc]
#[doc = "block cipher (decrypt-only)"]
///block cipher (decrypt-only)
#[derive(Clone)]
pub struct $name_dec {
inner: $name,
@ -641,9 +610,7 @@ macro_rules! define_aes_impl {
impl $name_dec {
#[inline(always)]
pub(crate) fn get_dec_backend(&self) -> $name_back_dec<'_> {
self.inner.get_dec_backend()
}
pub(crate) fn get_dec_backend(&self) -> $name_back_dec<'_> { self.inner.get_dec_backend() }
}
impl BlockCipher for $name_dec {}
@ -662,18 +629,12 @@ macro_rules! define_aes_impl {
impl From<$name_enc> for $name_dec {
#[inline]
fn from(enc: $name_enc) -> $name_dec {
Self { inner: enc.inner }
}
fn from(enc: $name_enc) -> $name_dec { Self { inner: enc.inner } }
}
impl From<&$name_enc> for $name_dec {
#[inline]
fn from(enc: &$name_enc) -> $name_dec {
Self {
inner: enc.inner.clone(),
}
}
fn from(enc: &$name_enc) -> $name_dec { Self { inner: enc.inner.clone() } }
}
impl BlockSizeUser for $name_dec {
@ -711,7 +672,7 @@ macro_rules! define_aes_impl {
impl<'a> BlockBackend for $name_back_enc<'a> {
#[inline(always)]
fn proc_block(&mut self, mut block: InOut<'_, '_, Block>) {
let res = $vex_encrypt(&self.0.enc_key, block.clone_in().as_slice(), $rounds);
let res = $vex_encrypt(&self.0.enc_key, block.clone_in().as_slice(), $rounds);
*block.get_out() = *Block::from_slice(&res);
}
@ -735,7 +696,7 @@ macro_rules! define_aes_impl {
impl<'a> BlockBackend for $name_back_dec<'a> {
#[inline(always)]
fn proc_block(&mut self, mut block: InOut<'_, '_, Block>) {
let res = $vex_decrypt(&self.0.dec_key, block.clone_in().as_slice(), $rounds);
let res = $vex_decrypt(&self.0.dec_key, block.clone_in().as_slice(), $rounds);
*block.get_out() = *Block::from_slice(&res);
}

View file

@ -3,9 +3,7 @@ use crate::vex::*;
/// AES-128 round keys
pub(crate) type VexKeys128 = [u32; 60];
pub fn aes128_enc_key_schedule(user_key: &[u8]) -> VexKeys128 {
set_encrypt_key_inner_128(user_key, true)
}
pub fn aes128_enc_key_schedule(user_key: &[u8]) -> VexKeys128 { set_encrypt_key_inner_128(user_key, true) }
fn set_encrypt_key_inner_128(user_key: &[u8], swap_final: bool) -> VexKeys128 {
let mut rk: VexKeys128 = [0; 60];

View file

@ -3,9 +3,7 @@ use crate::vex::*;
/// AES-256 round keys
pub(crate) type VexKeys256 = [u32; 60];
pub fn aes256_enc_key_schedule(user_key: &[u8]) -> VexKeys256 {
set_encrypt_key_inner_256(user_key, true)
}
pub fn aes256_enc_key_schedule(user_key: &[u8]) -> VexKeys256 { set_encrypt_key_inner_256(user_key, true) }
fn set_encrypt_key_inner_256(user_key: &[u8], swap_final: bool) -> VexKeys256 {
let mut rk: VexKeys256 = [0; 60];