[][src]Struct cocoon::Cocoon

pub struct Cocoon<'a, R: CryptoRng + RngCore + Clone, M> { /* fields omitted */ }

Stores data securely inside of encrypted container.

Basic Usage

let cocoon = Cocoon::new(b"password");

let wrapped = cocoon.wrap(b"my secret data")?;
assert_ne!(&wrapped, b"my secret data");

let unwrapped = cocoon.unwrap(&wrapped)?;
assert_eq!(unwrapped, b"my secret data");

Scroll down to Features and Methods Mapping, and also see crate's documentation for more use cases.

Optimization

Whenever a new container is created a new encryption key is generated from a supplied password using Key Derivation Function (KDF). By default, PBKDF2 is used with 100 000 iterations of SHA256. The reason for that is security: slower KDF - slower attacker brute-forces the password. However, you may find it a bit slow for debugging during development. If you experience a slower runtime, try to use one of the two approaches to speed it up.

Optimize Both cocoon And sha2

Add these lines to Cargo.toml:

[profile.dev.package.cocoon]
opt-level = 3

[profile.dev.package.sha2]
opt-level = 3

Use Less KDF Iterations

You can configure Cocoon to use fewer iterations for KDF with Cocoon::with_weak_kdf. Be careful, lower count of KDF iterations generate a weaker encryption key, therefore try to use it in debug build only.

// Attention: don't use a weak password in real life!
let password = [1, 2, 3, 4, 5, 6];

let mut cocoon = if cfg!(debug_assertions) {
    Cocoon::new(&password).with_weak_kdf()
} else {
    Cocoon::new(&password)
};

Using As a Struct Field

Currently, Cocoon is not supposed to be used within the data types as a structure member. Cocoon doesn't clone a password, instead, it uses a password reference and shares its lifetime. Also, Cocoon uses generics to evade dynamic dispatching and resolve variants at compile-time, so it makes its declaration in structures a little bit tricky. A convenient way to declare Cocoon as a structure member could be introduced once it's needed by semantic, e.g. with introducing of KDF caching.

Default Configuration

OptionValue
CipherChacha20Poly1305
Key derivationPBKDF2 with 100 000 iterations
Random generatorThreadRng

Features and Methods Mapping

Note: This is a not complete list of API methods. Please, refer to the current documentation below to get familiarized with the full set of methods.

Method ↓ / Feature →stdalloc"no_std"
Cocoon::new✔️
Cocoon::from_seed✔️✔️✔️
Cocoon::from_crypto_rng✔️✔️✔️
Cocoon::from_entropy✔️1✔️1✔️1
Cocoon::parse_only2✔️✔️✔️
Cocoon::encrypt✔️✔️✔️
Cocoon::decrypt2✔️✔️✔️
Cocoon::wrap✔️✔️
Cocoon::unwrap2✔️✔️
Cocoon::dump✔️
Cocoon::parse2✔️

  1. from_entropy is enabled when getrandom feature is enabled. 

  2. parse_only makes decryption API accessible only. 

Implementations

impl<'a> Cocoon<'a, ThreadRng, Creation>[src]

pub fn new(password: &'a [u8]) -> Self[src]

This is supported on feature="std" only.

Creates a new Cocoon with ThreadRng random generator under the hood and a Default Configuration.

  • password - a shared reference to a password

Examples

use cocoon::Cocoon;

let cocoon = Cocoon::new(b"my secret password");

impl<'a> Cocoon<'a, StdRng, Creation>[src]

pub fn from_seed(password: &'a [u8], seed: [u8; 32]) -> Self[src]

Creates a new Cocoon seeding a random generator using the given buffer.

  • password - a shared reference to a password
  • seed - 32 bytes of a random seed obtained from an external RNG

This method can be used when ThreadRng is not accessible with no std.

Examples

use cocoon::Cocoon;
use rand::Rng;

// Seed can be obtained by any cryptographically secure random generator.
// ThreadRng is used just for example.
let seed = rand::thread_rng().gen::<[u8; 32]>();

let cocoon = Cocoon::from_seed(b"password", seed);

WARNING: Use this method carefully, don't feed it with a static seed unless testing! See SeedableRng::from_seed, which is under the hood, for more details.

pub fn from_rng<R: RngCore>(password: &'a [u8], rng: R) -> Result<Self, Error>[src]

Creates a new Cocoon applying a third party random generator.

  • password - a shared reference to a password
  • rng - a source of random bytes

This method can be used when ThreadRng is not accessible in build with no std.

Examples

use cocoon::Cocoon;
use rand;

let cocoon = Cocoon::from_rng(b"password", good_rng).unwrap();

References

Also, see Cocoon::from_crypto_rng which doesn't fail.

pub fn from_entropy(password: &'a [u8]) -> Self[src]

This is supported on feature="getrandom" only.

Creates a new Cocoon with OS random generator using getrandom crate via SeedableRng::from_entropy.

  • password - a shared reference to a password

The method can be used to create Cocoon when ThreadRng is not accessible in build with no std.

Examples

use cocoon::Cocoon;

let cocoon = Cocoon::from_entropy(b"password");

impl<'a> Cocoon<'a, NoRng, Parsing>[src]

pub fn parse_only(password: &'a [u8]) -> Self[src]

Creates a Cocoon instance allowing to only decrypt a container. It makes only decryption methods accessible at compile-time: Cocoon::unwrap, Cocoon::parse and Cocoon::decrypt.

  • password - a shared reference to a password

All encryption methods need a cryptographic random generator to generate a salt and a nonce, at the same time the random generator is not needed for parsing.

The wrap/encrypt/dump methods are not accessible at compile-time when Cocoon::parse_only is used. Therefore the compilation of the following code snippet fails.

This example deliberately fails to compile
use cocoon::Cocoon;

let cocoon = Cocoon::parse_only(b"password");

// The compilation process fails here denying to use any encryption method.
cocoon.wrap(b"my data");

Meanwhile, decryption methods are accessible.

This example panics
use cocoon::{Cocoon, Error};

let cocoon = Cocoon::parse_only(b"password");

cocoon.decrypt(&mut data, &detached_prefix)?;

impl<'a, R: CryptoRng + RngCore + Clone> Cocoon<'a, R, Creation>[src]

pub fn from_crypto_rng(password: &'a [u8], rng: R) -> Self[src]

Creates a new Cocoon using a third party cryptographically secure random generator. Unlike Cocoon::from_rng this method never fails.

  • password - a shared reference to a password
  • rng - a cryptographically strong random generator

Examples

use cocoon::Cocoon;

let cocoon = Cocoon::from_crypto_rng(b"password", good_rng);

impl<'a, R: CryptoRng + RngCore + Clone> Cocoon<'a, R, Creation>[src]

pub fn with_cipher(self, cipher: CocoonCipher) -> Self[src]

Sets an encryption algorithm to wrap data on.

Examples

use cocoon::{Cocoon, CocoonCipher};

let cocoon = Cocoon::new(b"password").with_cipher(CocoonCipher::Aes256Gcm);
cocoon.wrap(b"my secret data");

pub fn with_weak_kdf(self) -> Self[src]

Reduces the number of iterations for key derivation function (KDF).

⚠️ This modifier could be used for testing in debug mode, and it should not be used in production and release builds.

Examples

use cocoon::Cocoon;

let cocoon = Cocoon::new(b"password").with_weak_kdf();
cocoon.wrap(b"my secret data").expect("New container");

pub fn wrap(&self, data: &[u8]) -> Result<Vec<u8>, Error>[src]

This is supported on feature="alloc" or feature="std" only.

Wraps data to an encrypted container.

  • data - a sensitive user data

Examples:

let cocoon = Cocoon::new(b"password");

let wrapped = cocoon.wrap(b"my secret data")?;
assert_ne!(&wrapped, b"my secret data");

pub fn dump(&self, data: Vec<u8>, writer: &mut impl Write) -> Result<(), Error>[src]

This is supported on feature="std" only.

Encrypts data in place, taking ownership over the buffer, and dumps the container into File, Cursor, or any other writer.

  • data - a sensitive data inside of Vec to be encrypted in place
  • writer - File, Cursor, or any other output

A data is going to be encrypted in place and stored in a file using the "cocoon" format.

Examples

let mut data = b"my secret data".to_vec();
let cocoon = Cocoon::new(b"password");

cocoon.dump(data, &mut file)?;

pub fn encrypt(&self, data: &mut [u8]) -> Result<[u8; 60], Error>[src]

Encrypts data in place and returns a detached prefix of the container.

The prefix is needed to decrypt data with Cocoon::decrypt. This method doesn't use memory allocation and it is suitable in the build with no std and no alloc.

Examples

let mut data = "my secret data".to_owned().into_bytes();
let cocoon = Cocoon::from_crypto_rng(b"password", good_rng);

let detached_prefix = cocoon.encrypt(&mut data)?;
assert_ne!(data, b"my secret data");

impl<'a, R: CryptoRng + RngCore + Clone, M> Cocoon<'a, R, M>[src]

Parsing methods are always accessible. They don't need random generator in general.

pub fn unwrap(&self, container: &[u8]) -> Result<Vec<u8>, Error>[src]

This is supported on feature="alloc" or feature="std" only.

Unwraps data from the encrypted container (see Cocoon::wrap).

Examples

let cocoon = Cocoon::new(b"password");

let unwrapped = cocoon.unwrap(&wrapped)?;
assert_eq!(unwrapped, b"my secret data");

pub fn parse(&self, reader: &mut impl Read) -> Result<Vec<u8>, Error>[src]

This is supported on feature="std" only.

Parses container from the reader (file, cursor, etc.), validates format, allocates memory and places decrypted data there.

Examples

let mut data = b"my secret data".to_vec();
let cocoon = Cocoon::new(b"password");

let data = cocoon.parse(&mut file)?;
assert_eq!(&data, b"my secret data");

pub fn decrypt(
    &self,
    data: &mut [u8],
    detached_prefix: &[u8]
) -> Result<(), Error>
[src]

Decrypts data in place using the parts returned by Cocoon::encrypt method.

The method doesn't use memory allocation and is suitable for "no std" and "no alloc" build.

Examples

let mut data = "my secret data".to_owned().into_bytes();
let cocoon = Cocoon::from_crypto_rng(b"password", good_rng);

let detached_prefix = cocoon.encrypt(&mut data)?;
assert_ne!(data, b"my secret data");

cocoon.decrypt(&mut data, &detached_prefix)?;
assert_eq!(data, b"my secret data");

Auto Trait Implementations

impl<'a, R, M> RefUnwindSafe for Cocoon<'a, R, M> where
    M: RefUnwindSafe,
    R: RefUnwindSafe

impl<'a, R, M> Send for Cocoon<'a, R, M> where
    M: Send,
    R: Send

impl<'a, R, M> Sync for Cocoon<'a, R, M> where
    M: Sync,
    R: Sync

impl<'a, R, M> Unpin for Cocoon<'a, R, M> where
    M: Unpin,
    R: Unpin

impl<'a, R, M> UnwindSafe for Cocoon<'a, R, M> where
    M: UnwindSafe,
    R: UnwindSafe

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> From<T> for T[src]

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T> Same<T> for T

type Output = T

Should always be Self

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.

impl<V, T> VZip<V> for T where
    V: MultiLane<T>,