Module symmetric

Source
Expand description

Symmetric encryption algorithms

Symmetric encryption algorithms uses the same key (the shared-secret) to encrypt and decrypt the data. It is usually more performant and secure to use this type of encryption than using asymmetric encryption algorithms.

§Usage

The first step is to create an instance of the algorithm needed. All the block ciphers algorithms supported are defined in the SymmetricAlgorithmId enum. Since they encrypt per block, a chaining mode is also needed. All the supported chaining modes are defined in the ChainingMode enum.

The creation of an algorithm can be relatively time-intensive. Therefore, it is advised to cache and reuse the created algorithms.

Once the algorithm is created, multiple keys can be created. Each key is initialized with a secret of a specific size. To check what key sizes are supported, see SymmetricAlgorithm.valid_key_sizes.

With the key in hand, it is then possible to encrypt or decrypt data. Padding is always added to fit a whole block. If the data fits exactly in a block, an extra block of padding is added. When encrypting or decrypting, an initialization vector (IV) may be required.

The following example encrypts then decrypts a message using AES with CBC chaining mode:

use win_crypto_ng::symmetric::{ChainingMode, SymmetricAlgorithm, SymmetricAlgorithmId};
use win_crypto_ng::symmetric::Padding;

const KEY: &'static str = "0123456789ABCDEF";
const IV: &'static str = "asdfqwerasdfqwer";
const DATA: &'static str = "This is a test.";

let iv = IV.as_bytes().to_owned();

let algo = SymmetricAlgorithm::open(SymmetricAlgorithmId::Aes, ChainingMode::Cbc).unwrap();
let key = algo.new_key(KEY.as_bytes()).unwrap();
let ciphertext = key.encrypt(Some(&mut iv.clone()), DATA.as_bytes(), Some(Padding::Block)).unwrap();
let plaintext = key.decrypt(Some(&mut iv.clone()), ciphertext.as_slice(), Some(Padding::Block)).unwrap();

assert_eq!(std::str::from_utf8(&plaintext.as_slice()[..DATA.len()]).unwrap(), DATA);

Structs§

Aes
The advanced encryption standard symmetric encryption algorithm.
Des
The data encryption standard symmetric encryption algorithm.
DesX
The extended data encryption standard symmetric encryption algorithm.
DynamicKeyBits
Key length known at run-time.
Key
Handle to a symmetric key.
Rc2
The RC2 block symmetric encryption algorithm.
SymmetricAlgorithm
Symmetric algorithm
SymmetricAlgorithmKey
Symmetric algorithm key
TripleDes
The triple data encryption standard symmetric encryption algorithm.
TripleDes112
The 112-bit triple data encryption standard symmetric encryption algorithm.

Enums§

ChainingMode
Symmetric algorithm chaining modes
Padding
Padding to be used together with symmetric algorithms
SymmetricAlgorithmId
Symmetric algorithm identifiers

Traits§

Algorithm
Marker trait for a symmetric algorithm.
KeyBits
Marker trait denoting key size in bits.