Expand description
Implements SHA2 as per NIST FIPS 180-4.
§Examples
§Hash
Hash functionality is accessed via the bouncycastle_core::traits::Hash trait,
which is implemented by SHA224, SHA256, SHA384 and SHA512.
The simplest usage is via the static functions.
use bouncycastle_core::traits::Hash;
use bouncycastle_sha2 as sha2;
let data: &[u8] = b"Hello, world!";
let output: Vec<u8> = sha2::SHA256::new().hash(data);More advanced usage will require creating a SHA3 or SHAKE object to hold state between successive calls, for example if input is received in chunks and not all available at the same time:
use bouncycastle_sha2 as sha2;
use bouncycastle_core::traits::Hash;
let data: &[u8] = b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F
\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F
\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F
\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F";
let mut sha2 = sha2::SHA256::new();
for chunk in data.chunks(16) {
sha2.do_update(chunk);
}
let output: Vec<u8> = sha2.do_final();§Suspending and resuming execution
When hashing a large message, it can be advantageous to be able to suspend the operation to a cache and resume it later; for example if waiting for the message to stream over a slow network connection.
For this reason, all SHA2 algorithms impl Suspendable.
use bouncycastle_sha2 as sha2;
use bouncycastle_core::traits::{Hash, Suspendable};
let msg_part1 = b"The quick brown fox";
let msg_part2 = b" jumped over the lazy dog";
let mut sha2 = sha2::SHA256::new();
sha2.do_update(msg_part1);
// suspend the in-progress extract while "waiting" for the second part of the message.
let serialized_state = sha2.suspend();
// ...
// do other things in the meantime
// ...
// ... later, possibly on another host: resume from the serialized state.
let mut sha2_resumed = sha2::SHA256::from_suspended(serialized_state).unwrap();
sha2_resumed.do_update(msg_part2);
let h: Vec<u8> = sha2_resumed.do_final();Structs§
- SHA224
Params - The parameters for SHA224.
- SHA256
Internal - Internal struct for SHA256. This uses a private bound so that you cannot instantiate it directly and have to use the provided and NIST-approved parameters.
- SHA256
Params - The parameters for SHA256.
- SHA384
Params - The parameters for SHA384.
- SHA512
Internal - Internal struct for SHA512. This uses a private bound so that you cannot instantiate it directly and have to use the provided and NIST-approved parameters.
- SHA512
Params - The parameters for SHA512.
Constants§
- SHA224_
NAME - SHA256_
NAME - SHA384_
NAME - SHA512_
NAME - SUSPENDED_
SHA256_ STATE_ LEN - Length in bytes of the serialized state of SHA224 and SHA256.
- SUSPENDED_
SHA512_ STATE_ LEN - Length in bytes of the serialized state of SHA384 and SHA512.