[][src]Module win_crypto_ng::hash

Cryptographic hash algorithms & MAC functions

Cryptographic hash algorithms are mathematical algorithms that map data of arbitrary size to a fixed size value. There are one-way functions practically infeasible to invert.

Message authentication code (MAC) is a short piece of information attached to a message confirming its authenticity and data integrity.

Usage

The first step is to create an instance of the algorithm needed. All the hash algorithms supported are defined in the HashAlgorithmId enum. For MACs, see the MacAlgorithmId 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, an instance of an hash can be created. It's worth noting that hash and MAC instances share the underlying Hash type.

Using the hash method, it is possible to hash per block. For example, if the user wants to hash a large file, it can call the hash multiple times with only a subset of the file, limiting the memory usage. The final result will be exactly the same as if the whole file was loaded and hash was called once.

To get the hash value, the user must call the finish method. This effectively consumes the hash instance. To start the calculation of a new hash, a new instance must be created from the algorithm.

The following example hashes a string with the SHA-256 algorithm:

use win_crypto_ng::hash::{HashAlgorithm, HashAlgorithmId};

const DATA: &'static str = "This is a test.";

let algo = HashAlgorithm::open(HashAlgorithmId::Sha256).unwrap();
let mut hash = algo.new_hash().unwrap();
hash.hash(DATA.as_bytes()).unwrap();
let result = hash.finish().unwrap();

assert_eq!(result.as_slice(), &[
    0xA8, 0xA2, 0xF6, 0xEB, 0xE2, 0x86, 0x69, 0x7C,
    0x52, 0x7E, 0xB3, 0x5A, 0x58, 0xB5, 0x53, 0x95,
    0x32, 0xE9, 0xB3, 0xAE, 0x3B, 0x64, 0xD4, 0xEB,
    0x0A, 0x46, 0xFB, 0x65, 0x7B, 0x41, 0x56, 0x2C,
]);

The example below computes a simple MAC value from null input, using the AES-GMAC algorithm:

use win_crypto_ng::hash::{HashAlgorithm, MacAlgorithmId};

const SECRET: &[u8] = &[
  0xcf, 0x06, 0x3a, 0x34, 0xd4, 0xa9, 0xa7, 0x6c,
  0x2c, 0x86, 0x78, 0x7d, 0x3f, 0x96, 0xdb, 0x71,
];
const IV: &[u8] = &[
  0x11, 0x3b, 0x97, 0x85, 0x97, 0x18, 0x64, 0xc8,
  0x3b, 0x01, 0xc7, 0x87
];

let algo = HashAlgorithm::open(MacAlgorithmId::AesGmac).unwrap();
let mut mac = algo.new_mac(SECRET, Some(IV)).unwrap();
mac.hash(&[]).unwrap();
let result = mac.finish().unwrap();

assert_eq!(result.as_slice(), &[
  0x72, 0xac, 0x84, 0x93, 0xe3, 0xa5, 0x22, 0x8b,
  0x5d, 0x13, 0x0a, 0x69, 0xd2, 0x51, 0x0e, 0x42,
]);

Structs

Hash

Hashing operation

HashAlgorithm

Hashing algorithm

Enums

HashAlgorithmId

Hashing algorithm identifiers

MacAlgorithmId

MAC (Message authentication code) algorithm identifiers

Traits

AlgorithmKind

Algorithm kind used with hashing facilities.