Skip to content

Commit

Permalink
feat: extension traits (#21)
Browse files Browse the repository at this point in the history
* feat: extension traits

* chore: run rustfmt
  • Loading branch information
mikesposito authored Dec 4, 2023
1 parent e925ee1 commit 07f9cdc
Show file tree
Hide file tree
Showing 13 changed files with 682 additions and 75 deletions.
32 changes: 13 additions & 19 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,33 +50,27 @@ Secured is straightforward to use from the command line. Here are the basic comm

To use Secured as a library in your Rust application, simply import the package and utilize its encryption and decryption functions as per your requirements.

```rust
use secured::enclave::Enclave;
use secured::cipher::Key;
#### Encrypting Data

fn main() {
// Key generation (32bytes for the key, 16 bytes for salt)
let key = Key::<32, 16>::new(b"my password", 900_000); // 900K rounds
```rust
use secured_enclave::{Enclave, Encryptable, KeyDerivationStrategy};

// Leave some readable metadata (but signed!)
let metadata = b"some metadata".to_vec();
let password = "strong_password";
let encrypted_string = "Hello, world!".encrypt(password.to_string(), KeyDerivationStrategy::default());
```

// Using Enclave for data encapsulation (&str metadata, 8-byte nonce)
let enclave =
Enclave::from_plain_bytes(metadata, key.pubk, b"Some bytes to encrypt".to_vec())
.unwrap();
#### Decrypting Data

// Get encrypted bytes (ciphertext)
println!("Encrypted bytes: {:?}", enclave.encrypted_bytes);
```rust
use secured_enclave::{Decryptable, EnclaveError};

// Decrypt Enclave
let decrypted_bytes = enclave.decrypt(key.pubk).unwrap();
let password = "strong_password";
let decrypted_result = encrypted_data.decrypt(password.to_string());

assert_eq!(decrypted_bytes, b"Some bytes to encrypt");
}
println!("Decrypted data: {:?}", String::from_utf8(decrypted_data).unwrap())
```

See [package documentation](https://docs.rs/secured/0.3.0/) for more information
See [Enclave documentation](enclave/README.md) for more advanced usage

## Contributing

Expand Down
21 changes: 21 additions & 0 deletions cipher/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Michele Esposito

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
110 changes: 104 additions & 6 deletions cipher/key/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,18 @@ impl<const P: usize, const S: usize> Key<P, S> {
///
/// # Panics
/// Panics if the key derivation fails.
pub fn new(password: &[u8], rounds: u32) -> Self {
pub fn new(password: &[u8], strategy: KeyDerivationStrategy) -> Self {
// Generate a random salt value
let salt = random_bytes::<S>();

// Derive the public key using PBKDF2 algorithm
let mut pubk = [0; P];
if pbkdf2::<Hmac<Sha256>>(password, &salt, rounds, &mut pubk).is_err() {
panic!("Key derivation failed")
match strategy {
KeyDerivationStrategy::PBKDF2(rounds) => {
if pbkdf2::<Hmac<Sha256>>(password, &salt, rounds as u32, &mut pubk).is_err() {
panic!("Key derivation failed")
}
}
}

Self { pubk, salt }
Expand All @@ -52,11 +56,16 @@ impl<const P: usize, const S: usize> Key<P, S> {
///
/// # Panics
/// Panics if the key derivation fails.
pub fn with_salt(password: &[u8], salt: [u8; S], rounds: u32) -> Self {
pub fn with_salt(password: &[u8], salt: [u8; S], strategy: KeyDerivationStrategy) -> Self {
// Derive the public key using PBKDF2 algorithm with the provided salt
let mut pubk = [0; P];
if pbkdf2::<Hmac<Sha256>>(password, &salt, rounds, &mut pubk).is_err() {
panic!("Key derivation failed")

match strategy {
KeyDerivationStrategy::PBKDF2(rounds) => {
if pbkdf2::<Hmac<Sha256>>(password, &salt, rounds as u32, &mut pubk).is_err() {
panic!("Key derivation failed")
}
}
}

Self { pubk, salt }
Expand All @@ -69,3 +78,92 @@ pub fn random_bytes<const S: usize>() -> [u8; S] {
OsRng.fill_bytes(&mut bytes);
bytes
}

#[derive(Clone, Debug)]
pub enum KeyDerivationStrategy {
PBKDF2(usize),
}

impl Default for KeyDerivationStrategy {
fn default() -> Self {
KeyDerivationStrategy::PBKDF2(900_000)
}
}

impl TryFrom<Vec<u8>> for KeyDerivationStrategy {
type Error = String;

fn try_from(bytes: Vec<u8>) -> Result<Self, String> {
match bytes[0] {
0 => {
let rounds_bytes = &bytes[1..];
let rounds = usize::from_be_bytes(rounds_bytes.try_into().or(Err("Invalid rounds bytes"))?);
Ok(KeyDerivationStrategy::PBKDF2(rounds))
}
_ => Err("Invalid key derivation strategy".to_string()),
}
}
}

impl From<KeyDerivationStrategy> for Vec<u8> {
fn from(strategy: KeyDerivationStrategy) -> Self {
match strategy {
KeyDerivationStrategy::PBKDF2(rounds) => [vec![0u8], rounds.to_be_bytes().to_vec()].concat(),
}
}
}

impl PartialEq for KeyDerivationStrategy {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(KeyDerivationStrategy::PBKDF2(rounds), KeyDerivationStrategy::PBKDF2(rounds2)) => {
rounds == rounds2
}
}
}
}

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

#[test]
fn test_key_derivation() {
let password = "password".as_bytes();

let key = Key::<32, 32>::new(password, KeyDerivationStrategy::PBKDF2(10_000));
let key2 = Key::<32, 32>::with_salt(password, key.salt, KeyDerivationStrategy::PBKDF2(10_000));

assert_eq!(key.pubk, key2.pubk);
}

#[test]
fn test_key_derivation_with_different_salt() {
let password = "password".as_bytes();

let key = Key::<32, 32>::new(password, KeyDerivationStrategy::PBKDF2(10_000));
let key2 = Key::<32, 32>::new(password, KeyDerivationStrategy::PBKDF2(10_000));

assert_ne!(key.pubk, key2.pubk);
}

#[test]
fn test_key_derivation_with_different_rounds() {
let password = "password".as_bytes();

let key = Key::<32, 32>::new(password, KeyDerivationStrategy::PBKDF2(10_000));
let key2 = Key::<32, 32>::new(password, KeyDerivationStrategy::PBKDF2(11_000));

assert_ne!(key.pubk, key2.pubk);
}

#[test]
fn test_key_strategy_serialization_deserialization() {
let strategy = KeyDerivationStrategy::PBKDF2(10_000);

let serialized: Vec<u8> = strategy.clone().into();
let deserialized = KeyDerivationStrategy::try_from(serialized).unwrap();

assert_eq!(strategy, deserialized);
}
}
4 changes: 2 additions & 2 deletions cipher/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@
//! let is_decryption_ok = verified_decrypted_data.is_ok();
//!
//! println!("Decrypted and verified data: {:?}", verified_decrypted_data.unwrap());
//!
//!
//! ```
//!
//! ## Modules
Expand All @@ -58,7 +58,7 @@
pub mod permutation;

pub use secured_cipher_key::{random_bytes, Key};
pub use secured_cipher_key::{random_bytes, Key, KeyDerivationStrategy};

pub use permutation::{ChaCha20, Permutation, Poly1305, SignedEnvelope};

Expand Down
10 changes: 5 additions & 5 deletions cipher/src/permutation/chacha20/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
mod core;
pub use core::{CHACHA20_NONCE_SIZE, permute, xor_bytes, Block, CONSTANTS, STATE_WORDS};
pub use core::{permute, xor_bytes, Block, CHACHA20_NONCE_SIZE, CONSTANTS, STATE_WORDS};

use super::Permutation;

Expand Down Expand Up @@ -37,10 +37,10 @@ impl ChaCha20 {
/// # Example
/// ```
/// use secured_cipher::{ChaCha20, Permutation};
///
///
/// let mut chacha20 = ChaCha20::new();
/// chacha20.init(&[0_u8; 32], &[0_u8; 12]);
///
///
/// let keystream_block = chacha20.next_keystream();
/// // `keystream_block` now contains the next 64 bytes of the keystream
/// ```
Expand Down Expand Up @@ -135,10 +135,10 @@ impl Permutation for ChaCha20 {
/// # Example
/// ```
/// use secured_cipher::{ChaCha20, Permutation};
///
///
/// let mut chacha20 = ChaCha20::new();
/// chacha20.init(&[0_u8; 32], &[0_u8; 12]);
///
///
/// let data = b"some plaintext data"; // Data to be encrypted or decrypted
/// let processed_data = chacha20.process(data);
/// // `processed_data` now contains the encrypted or decrypted output
Expand Down
2 changes: 1 addition & 1 deletion enclave/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ authors = ["mikesposito"]
edition = "2021"
license = "MIT"
repository = "https://github.com/mikesposito/secured/"
description = "Part of secured: a lightweight, easy-to-use Rust package for file encryption and decryption, suitable for both CLI and library integration in Rust applications."
description = "Ergonomic library for secure encryption and decryption of data in Rust."

[dependencies.secured-cipher]
version = "0.3.0"
Expand Down
21 changes: 21 additions & 0 deletions enclave/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Michele Esposito

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Loading

0 comments on commit 07f9cdc

Please sign in to comment.