emerald-vault-core 0.26.6

Ethereum secure account management core libary
Documentation
/*
Copyright 2019 ETCDEV GmbH

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
//! # Advanced encryption standard (AES) cipher

use super::Error;
use aes_ctr::stream_cipher::generic_array::GenericArray;
use aes_ctr::stream_cipher::{NewFixStreamCipher, StreamCipherCore};
use aes_ctr::Aes128Ctr;
use std::fmt;
use std::str::FromStr;

/// `AES128_CRT` cipher name
pub const AES128_CTR_CIPHER_NAME: &str = "aes-128-ctr";

/// Cipher type
#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
pub enum Cipher {
    /// AES-CTR (specified in (RFC 3686)[https://tools.ietf.org/html/rfc3686])
    #[serde(rename = "aes-128-ctr")]
    Aes128Ctr,
}

impl Cipher {
    /// Encrypt given text with provided key and initial vector
    pub fn encrypt(&self, data: &[u8], key: &[u8], iv: &[u8]) -> Vec<u8> {
        let key = GenericArray::from_slice(key);
        let iv = GenericArray::from_slice(iv);
        let mut buf = data.to_vec();
        let mut ctr = Aes128Ctr::new(key, iv);
        ctr.apply_keystream(&mut buf);
        buf
    }
}

impl Default for Cipher {
    fn default() -> Self {
        Cipher::Aes128Ctr
    }
}

impl FromStr for Cipher {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            _ if s == AES128_CTR_CIPHER_NAME => Ok(Cipher::Aes128Ctr),
            _ => Err(Error::UnsupportedCipher(s.to_string())),
        }
    }
}

impl fmt::Display for Cipher {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Cipher::Aes128Ctr => f.write_str(AES128_CTR_CIPHER_NAME),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tests::*;

    #[test]
    fn should_encrypt_with_aes_ctr() {
        let data = to_16bytes("6bc1bee22e409f96e93d7e117393172a");
        let key = to_16bytes("2b7e151628aed2a6abf7158809cf4f3c");
        let iv = to_16bytes("f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff");

        assert_eq!(
            Cipher::Aes128Ctr.encrypt(&data, &key, &iv),
            Vec::from_hex("874d6191b620e3261bef6864990db6ce").unwrap()
        );
    }
}