ark_ff/fields/field_hashers/
mod.rs

1mod expander;
2
3use crate::{Field, PrimeField};
4
5use ark_std::vec::Vec;
6use digest::DynDigest;
7use expander::Expander;
8
9use self::expander::ExpanderXmd;
10
11/// Trait for hashing messages to field elements.
12pub trait HashToField<F: Field>: Sized {
13    /// Initialises a new hash-to-field helper struct.
14    ///
15    /// # Arguments
16    ///
17    /// * `domain` - bytes that get concatenated with the `msg` during hashing, in order to separate potentially interfering instantiations of the hasher.
18    fn new(domain: &[u8]) -> Self;
19
20    /// Hash an arbitrary `msg` to #`count` elements from field `F`.
21    fn hash_to_field(&self, msg: &[u8], count: usize) -> Vec<F>;
22}
23
24/// This field hasher constructs a Hash-To-Field based on a fixed-output hash function,
25/// like SHA2, SHA3 or Blake2.
26/// The implementation aims to follow the specification in [Hashing to Elliptic Curves (draft)](https://tools.ietf.org/pdf/draft-irtf-cfrg-hash-to-curve-13.pdf).
27///
28/// # Examples
29///
30/// ```
31/// use ark_ff::fields::field_hashers::{DefaultFieldHasher, HashToField};
32/// use ark_test_curves::bls12_381::Fq;
33/// use sha2::Sha256;
34///
35/// let hasher = <DefaultFieldHasher<Sha256> as HashToField<Fq>>::new(&[1, 2, 3]);
36/// let field_elements: Vec<Fq> = hasher.hash_to_field(b"Hello, World!", 2);
37///
38/// assert_eq!(field_elements.len(), 2);
39/// ```
40pub struct DefaultFieldHasher<H: Default + DynDigest + Clone, const SEC_PARAM: usize = 128> {
41    expander: ExpanderXmd<H>,
42    len_per_base_elem: usize,
43}
44
45impl<F: Field, H: Default + DynDigest + Clone, const SEC_PARAM: usize> HashToField<F>
46    for DefaultFieldHasher<H, SEC_PARAM>
47{
48    fn new(dst: &[u8]) -> Self {
49        // The final output of `hash_to_field` will be an array of field
50        // elements from F::BaseField, each of size `len_per_elem`.
51        let len_per_base_elem = get_len_per_elem::<F, SEC_PARAM>();
52
53        let expander = ExpanderXmd {
54            hasher: H::default(),
55            dst: dst.to_vec(),
56            block_size: len_per_base_elem,
57        };
58
59        DefaultFieldHasher {
60            expander,
61            len_per_base_elem,
62        }
63    }
64
65    fn hash_to_field(&self, message: &[u8], count: usize) -> Vec<F> {
66        let m = F::extension_degree() as usize;
67
68        // The user imposes a `count` of elements of F_p^m to output per input msg,
69        // each field element comprising `m` BasePrimeField elements.
70        let len_in_bytes = count * m * self.len_per_base_elem;
71        let uniform_bytes = self.expander.expand(message, len_in_bytes);
72
73        let mut output = Vec::with_capacity(count);
74        let mut base_prime_field_elems = Vec::with_capacity(m);
75        for i in 0..count {
76            base_prime_field_elems.clear();
77            for j in 0..m {
78                let elm_offset = self.len_per_base_elem * (j + i * m);
79                let val = F::BasePrimeField::from_be_bytes_mod_order(
80                    &uniform_bytes[elm_offset..][..self.len_per_base_elem],
81                );
82                base_prime_field_elems.push(val);
83            }
84            let f = F::from_base_prime_field_elems(&base_prime_field_elems).unwrap();
85            output.push(f);
86        }
87
88        output
89    }
90}
91
92/// This function computes the length in bytes that a hash function should output
93/// for hashing an element of type `Field`.
94/// See section 5.1 and 5.3 of the
95/// [IETF hash standardization draft](https://datatracker.ietf.org/doc/draft-irtf-cfrg-hash-to-curve/14/)
96fn get_len_per_elem<F: Field, const SEC_PARAM: usize>() -> usize {
97    // ceil(log(p))
98    let base_field_size_in_bits = F::BasePrimeField::MODULUS_BIT_SIZE as usize;
99    // ceil(log(p)) + security_parameter
100    let base_field_size_with_security_padding_in_bits = base_field_size_in_bits + SEC_PARAM;
101    // ceil( (ceil(log(p)) + security_parameter) / 8)
102    let bytes_per_base_field_elem =
103        ((base_field_size_with_security_padding_in_bits + 7) / 8) as u64;
104    bytes_per_base_field_elem as usize
105}