sp800_185/
tuplehash.rs

1use tiny_keccak::XofReader;
2use ::cshake::CShake;
3use ::utils::{ left_encode, right_encode };
4
5
6/// Tuple Hash.
7///
8/// `TupleHash` is a SHA-3-derived hash function with variable-length output that is designed to
9/// simply hash a tuple of input strings, any or all of which may be empty strings, in an
10/// unambiguous way. Such a tuple may consist of any number of strings, including zero, and is
11/// represented as a sequence of strings or variables in parentheses like (“a”, “b”, “c”,...,“z”) in this
12/// document.
13/// `TupleHash` is designed to provide a generic, misuse-resistant way to combine a sequence of
14/// strings for hashing such that, for example, a `TupleHash` computed on the tuple ("abc" ,"d") will
15/// produce a different hash value than a `TupleHash` computed on the tuple ("ab","cd"), even though
16/// all the remaining input parameters are kept the same, and the two resulting concatenated strings,
17/// without string encoding, are identical.
18/// `TupleHash` supports two security strengths: 128 bits and 256 bits. Changing any input to the
19/// function, including the requested output length, will almost certainly change the final output.
20#[derive(Clone)]
21pub struct TupleHash(CShake);
22
23impl TupleHash {
24    #[inline]
25    pub fn new_tuplehash128(custom: &[u8]) -> Self {
26        TupleHash(CShake::new_cshake128(b"TupleHash", custom))
27    }
28
29    #[inline]
30    pub fn new_tuplehash256(custom: &[u8]) -> Self {
31        TupleHash(CShake::new_cshake256(b"TupleHash", custom))
32    }
33
34    pub fn update<T: AsRef<[u8]>>(&mut self, input: &[T]) {
35        let mut encbuf = [0; 9];
36
37        for buf in input {
38            let buf = buf.as_ref();
39            // encode_string(X[i])
40            let pos = left_encode(&mut encbuf, buf.len() as u64 * 8);
41            self.0.update(&encbuf[pos..]);
42            self.0.update(buf);
43        }
44    }
45
46    #[inline]
47    pub fn finalize(mut self, buf: &mut [u8]) {
48        self.with_bitlength(buf.len() as u64 * 8);
49        self.0.finalize(buf)
50    }
51
52    /// A function on bit strings in which the output can be extended to  any desired length.
53    ///
54    /// Some applications of `TupleHash` may not know the number of output bits they will need until
55    /// after the outputs begin to be produced. For these applications, `TupleHash` can also be used as a
56    /// XOF (i.e., the output can be extended to any desired length), which mimics the behavior of
57    /// cSHAKE.
58    #[inline]
59    pub fn xof(mut self) -> XofReader {
60        self.with_bitlength(0);
61        self.0.xof()
62    }
63
64    #[inline]
65    fn with_bitlength(&mut self, bitlength: u64) {
66        let mut encbuf = [0; 9];
67
68        // right_encode(L)
69        let pos = right_encode(&mut encbuf, bitlength);
70        self.0.update(&encbuf[pos..]);
71    }
72}