arnaucube
arnaucube/miden-cryptoPublic Self-hosted repository
miden-crypto/src/dsa/rpo_falcon512/keys/secret_key.rs
src/dsa/rpo_falcon512/keys/secret_key.rsRaw
  1use super::{
  2    super::{
  3        math::{ffldl, ffsampling, gram, normalize_tree, FalconFelt, FastFft, LdlTree, Polynomial},
  4        signature::SignaturePoly,
  5        ByteReader, ByteWriter, Deserializable, DeserializationError, Nonce, Serializable,
  6        ShortLatticeBasis, Signature, Word, MODULUS, N, SIGMA, SIG_L2_BOUND,
  7    },
  8    PubKeyPoly, PublicKey,
  9};
 10use crate::dsa::rpo_falcon512::{
 11    hash_to_point::hash_to_point_rpo256, math::ntru_gen, SIG_NONCE_LEN, SK_LEN,
 12};
 13use alloc::{string::ToString, vec::Vec};
 14use num::Complex;
 15use num_complex::Complex64;
 16use rand::Rng;
 17
 18#[cfg(not(feature = "std"))]
 19use num::Float;
 20
 21// CONSTANTS
 22// ================================================================================================
 23
 24const WIDTH_BIG_POLY_COEFFICIENT: usize = 8;
 25const WIDTH_SMALL_POLY_COEFFICIENT: usize = 6;
 26
 27// SECRET KEY
 28// ================================================================================================
 29
 30/// The secret key is a quadruple [[g, -f], [G, -F]] of polynomials with integer coefficients. Each
 31/// polynomial is of degree at most N = 512 and computations with these polynomials is done modulo
 32/// the monic irreducible polynomial ϕ = x^N + 1. The secret key is a basis for a lattice and has
 33/// the property of being short with respect to a certain norm and an upper bound appropriate for
 34/// a given security parameter. The public key on the other hand is another basis for the same
 35/// lattice and can be described by a single polynomial h with integer coefficients modulo ϕ.
 36/// The two keys are related by the following relation:
 37///
 38/// 1. h = g /f [mod ϕ][mod p]
 39/// 2. f.G - g.F = p [mod ϕ]
 40///
 41/// where p = 12289 is the Falcon prime. Equation 2 is called the NTRU equation.
 42/// The secret key is generated by first sampling a random pair (f, g) of polynomials using
 43/// an appropriate distribution that yields short but not too short polynomials with integer
 44/// coefficients modulo ϕ. The NTRU equation is then used to find a matching pair (F, G).
 45/// The public key is then derived from the secret key using equation 1.
 46///
 47/// To allow for fast signature generation, the secret key is pre-processed into a more suitable
 48/// form, called the LDL tree, and this allows for fast sampling of short vectors in the lattice
 49/// using Fast Fourier sampling during signature generation (ffSampling algorithm 11 in [1]).
 50///
 51/// [1]: https://falcon-sign.info/falcon.pdf
 52#[derive(Debug, Clone)]
 53pub struct SecretKey {
 54    secret_key: ShortLatticeBasis,
 55    tree: LdlTree,
 56}
 57
 58#[allow(clippy::new_without_default)]
 59impl SecretKey {
 60    // CONSTRUCTORS
 61    // --------------------------------------------------------------------------------------------
 62
 63    /// Generates a secret key from OS-provided randomness.
 64    #[cfg(feature = "std")]
 65    pub fn new() -> Self {
 66        use rand::{rngs::StdRng, SeedableRng};
 67
 68        let mut rng = StdRng::from_entropy();
 69        Self::with_rng(&mut rng)
 70    }
 71
 72    /// Generates a secret_key using the provided random number generator `Rng`.
 73    pub fn with_rng<R: Rng>(rng: &mut R) -> Self {
 74        let basis = ntru_gen(N, rng);
 75        Self::from_short_lattice_basis(basis)
 76    }
 77
 78    /// Given a short basis [[g, -f], [G, -F]], computes the normalized LDL tree i.e., Falcon tree.
 79    fn from_short_lattice_basis(basis: ShortLatticeBasis) -> SecretKey {
 80        // FFT each polynomial of the short basis.
 81        let basis_fft = to_complex_fft(&basis);
 82        // compute the Gram matrix.
 83        let gram_fft = gram(basis_fft);
 84        // construct the LDL tree of the Gram matrix.
 85        let mut tree = ffldl(gram_fft);
 86        // normalize the leaves of the LDL tree.
 87        normalize_tree(&mut tree, SIGMA);
 88        Self { secret_key: basis, tree }
 89    }
 90
 91    // PUBLIC ACCESSORS
 92    // --------------------------------------------------------------------------------------------
 93
 94    /// Returns the polynomials of the short lattice basis of this secret key.
 95    pub fn short_lattice_basis(&self) -> &ShortLatticeBasis {
 96        &self.secret_key
 97    }
 98
 99    /// Returns the public key corresponding to this secret key.
100    pub fn public_key(&self) -> PublicKey {
101        self.compute_pub_key_poly().into()
102    }
103
104    /// Returns the LDL tree associated to this secret key.
105    pub fn tree(&self) -> &LdlTree {
106        &self.tree
107    }
108
109    // SIGNATURE GENERATION
110    // --------------------------------------------------------------------------------------------
111
112    /// Signs a message with this secret key.
113    #[cfg(feature = "std")]
114    pub fn sign(&self, message: Word) -> Signature {
115        use rand::{rngs::StdRng, SeedableRng};
116
117        let mut rng = StdRng::from_entropy();
118        self.sign_with_rng(message, &mut rng)
119    }
120
121    /// Signs a message with the secret key relying on the provided randomness generator.
122    pub fn sign_with_rng<R: Rng>(&self, message: Word, rng: &mut R) -> Signature {
123        let mut nonce_bytes = [0u8; SIG_NONCE_LEN];
124        rng.fill_bytes(&mut nonce_bytes);
125        let nonce = Nonce::new(nonce_bytes);
126
127        let h = self.compute_pub_key_poly();
128        let c = hash_to_point_rpo256(message, &nonce);
129        let s2 = self.sign_helper(c, rng);
130
131        Signature::new(nonce, h, s2)
132    }
133
134    // HELPER METHODS
135    // --------------------------------------------------------------------------------------------
136
137    /// Derives the public key corresponding to this secret key using h = g /f [mod ϕ][mod p].
138    pub fn compute_pub_key_poly(&self) -> PubKeyPoly {
139        let g: Polynomial<FalconFelt> = self.secret_key[0].clone().into();
140        let g_fft = g.fft();
141        let minus_f: Polynomial<FalconFelt> = self.secret_key[1].clone().into();
142        let f = -minus_f;
143        let f_fft = f.fft();
144        let h_fft = g_fft.hadamard_div(&f_fft);
145        h_fft.ifft().into()
146    }
147
148    /// Signs a message polynomial with the secret key.
149    ///
150    /// Takes a randomness generator implementing `Rng` and message polynomial representing `c`
151    /// the hash-to-point of the message to be signed. It outputs a signature polynomial `s2`.
152    fn sign_helper<R: Rng>(&self, c: Polynomial<FalconFelt>, rng: &mut R) -> SignaturePoly {
153        let one_over_q = 1.0 / (MODULUS as f64);
154        let c_over_q_fft = c.map(|cc| Complex::new(one_over_q * cc.value() as f64, 0.0)).fft();
155
156        // B = [[FFT(g), -FFT(f)], [FFT(G), -FFT(F)]]
157        let [g_fft, minus_f_fft, big_g_fft, minus_big_f_fft] = to_complex_fft(&self.secret_key);
158        let t0 = c_over_q_fft.hadamard_mul(&minus_big_f_fft);
159        let t1 = -c_over_q_fft.hadamard_mul(&minus_f_fft);
160
161        loop {
162            let bold_s = loop {
163                let z = ffsampling(&(t0.clone(), t1.clone()), &self.tree, rng);
164                let t0_min_z0 = t0.clone() - z.0;
165                let t1_min_z1 = t1.clone() - z.1;
166
167                // s = (t-z) * B
168                let s0 = t0_min_z0.hadamard_mul(&g_fft) + t1_min_z1.hadamard_mul(&big_g_fft);
169                let s1 =
170                    t0_min_z0.hadamard_mul(&minus_f_fft) + t1_min_z1.hadamard_mul(&minus_big_f_fft);
171
172                // compute the norm of (s0||s1) and note that they are in FFT representation
173                let length_squared: f64 =
174                    (s0.coefficients.iter().map(|a| (a * a.conj()).re).sum::<f64>()
175                        + s1.coefficients.iter().map(|a| (a * a.conj()).re).sum::<f64>())
176                        / (N as f64);
177
178                if length_squared > (SIG_L2_BOUND as f64) {
179                    continue;
180                }
181
182                break [-s0, s1];
183            };
184
185            let s2 = bold_s[1].ifft();
186            let s2_coef: [i16; N] = s2
187                .coefficients
188                .iter()
189                .map(|a| a.re.round() as i16)
190                .collect::<Vec<i16>>()
191                .try_into()
192                .expect("The number of coefficients should be equal to N");
193
194            if let Ok(s2) = SignaturePoly::try_from(&s2_coef) {
195                return s2;
196            }
197        }
198    }
199}
200
201// SERIALIZATION / DESERIALIZATION
202// ================================================================================================
203
204impl Serializable for SecretKey {
205    fn write_into<W: ByteWriter>(&self, target: &mut W) {
206        let basis = &self.secret_key;
207
208        // header
209        let n = basis[0].coefficients.len();
210        let l = n.checked_ilog2().unwrap() as u8;
211        let header: u8 = (5 << 4) | l;
212
213        let neg_f = &basis[1];
214        let g = &basis[0];
215        let neg_big_f = &basis[3];
216
217        let mut buffer = Vec::with_capacity(1281);
218        buffer.push(header);
219
220        let f_i8: Vec<i8> = neg_f.coefficients.iter().map(|&a| -a as i8).collect();
221        let f_i8_encoded = encode_i8(&f_i8, WIDTH_SMALL_POLY_COEFFICIENT).unwrap();
222        buffer.extend_from_slice(&f_i8_encoded);
223
224        let g_i8: Vec<i8> = g.coefficients.iter().map(|&a| a as i8).collect();
225        let g_i8_encoded = encode_i8(&g_i8, WIDTH_SMALL_POLY_COEFFICIENT).unwrap();
226        buffer.extend_from_slice(&g_i8_encoded);
227
228        let big_f_i8: Vec<i8> = neg_big_f.coefficients.iter().map(|&a| -a as i8).collect();
229        let big_f_i8_encoded = encode_i8(&big_f_i8, WIDTH_BIG_POLY_COEFFICIENT).unwrap();
230        buffer.extend_from_slice(&big_f_i8_encoded);
231        target.write_bytes(&buffer);
232    }
233}
234
235impl Deserializable for SecretKey {
236    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
237        let byte_vector: [u8; SK_LEN] = source.read_array()?;
238
239        // check length
240        if byte_vector.len() < 2 {
241            return  Err(DeserializationError::InvalidValue("Invalid encoding length: Failed to decode as length is different from the one expected".to_string()));
242        }
243
244        // read fields
245        let header = byte_vector[0];
246
247        // check fixed bits in header
248        if (header >> 4) != 5 {
249            return Err(DeserializationError::InvalidValue("Invalid header format".to_string()));
250        }
251
252        // check log n
253        let logn = (header & 15) as usize;
254        let n = 1 << logn;
255
256        // match against const variant generic parameter
257        if n != N {
258            return Err(DeserializationError::InvalidValue(
259                "Unsupported Falcon DSA variant".to_string(),
260            ));
261        }
262
263        if byte_vector.len() != SK_LEN {
264            return Err(DeserializationError::InvalidValue("Invalid encoding length: Failed to decode as length is different from the one expected".to_string()));
265        }
266
267        let chunk_size_f = ((n * WIDTH_SMALL_POLY_COEFFICIENT) + 7) >> 3;
268        let chunk_size_g = ((n * WIDTH_SMALL_POLY_COEFFICIENT) + 7) >> 3;
269        let chunk_size_big_f = ((n * WIDTH_BIG_POLY_COEFFICIENT) + 7) >> 3;
270
271        let f = decode_i8(&byte_vector[1..chunk_size_f + 1], WIDTH_SMALL_POLY_COEFFICIENT).unwrap();
272        let g = decode_i8(
273            &byte_vector[chunk_size_f + 1..(chunk_size_f + chunk_size_g + 1)],
274            WIDTH_SMALL_POLY_COEFFICIENT,
275        )
276        .unwrap();
277        let big_f = decode_i8(
278            &byte_vector[(chunk_size_f + chunk_size_g + 1)
279                ..(chunk_size_f + chunk_size_g + chunk_size_big_f + 1)],
280            WIDTH_BIG_POLY_COEFFICIENT,
281        )
282        .unwrap();
283
284        let f = Polynomial::new(f.iter().map(|&c| FalconFelt::new(c.into())).collect());
285        let g = Polynomial::new(g.iter().map(|&c| FalconFelt::new(c.into())).collect());
286        let big_f = Polynomial::new(big_f.iter().map(|&c| FalconFelt::new(c.into())).collect());
287
288        // big_g * f - g * big_f = p (mod X^n + 1)
289        let big_g = g.fft().hadamard_div(&f.fft()).hadamard_mul(&big_f.fft()).ifft();
290        let basis = [
291            g.map(|f| f.balanced_value()),
292            -f.map(|f| f.balanced_value()),
293            big_g.map(|f| f.balanced_value()),
294            -big_f.map(|f| f.balanced_value()),
295        ];
296        Ok(Self::from_short_lattice_basis(basis))
297    }
298}
299
300// HELPER FUNCTIONS
301// ================================================================================================
302
303/// Computes the complex FFT of the secret key polynomials.
304fn to_complex_fft(basis: &[Polynomial<i16>; 4]) -> [Polynomial<Complex<f64>>; 4] {
305    let [g, f, big_g, big_f] = basis.clone();
306    let g_fft = g.map(|cc| Complex64::new(*cc as f64, 0.0)).fft();
307    let minus_f_fft = f.map(|cc| -Complex64::new(*cc as f64, 0.0)).fft();
308    let big_g_fft = big_g.map(|cc| Complex64::new(*cc as f64, 0.0)).fft();
309    let minus_big_f_fft = big_f.map(|cc| -Complex64::new(*cc as f64, 0.0)).fft();
310    [g_fft, minus_f_fft, big_g_fft, minus_big_f_fft]
311}
312
313/// Encodes a sequence of signed integers such that each integer x satisfies |x| < 2^(bits-1)
314/// for a given parameter bits. bits can take either the value 6 or 8.
315pub fn encode_i8(x: &[i8], bits: usize) -> Option<Vec<u8>> {
316    let maxv = (1 << (bits - 1)) - 1_usize;
317    let maxv = maxv as i8;
318    let minv = -maxv;
319
320    for &c in x {
321        if c > maxv || c < minv {
322            return None;
323        }
324    }
325
326    let out_len = ((N * bits) + 7) >> 3;
327    let mut buf = vec![0_u8; out_len];
328
329    let mut acc = 0_u32;
330    let mut acc_len = 0;
331    let mask = ((1_u16 << bits) - 1) as u8;
332
333    let mut input_pos = 0;
334    for &c in x {
335        acc = (acc << bits) | (c as u8 & mask) as u32;
336        acc_len += bits;
337        while acc_len >= 8 {
338            acc_len -= 8;
339            buf[input_pos] = (acc >> acc_len) as u8;
340            input_pos += 1;
341        }
342    }
343    if acc_len > 0 {
344        buf[input_pos] = (acc >> (8 - acc_len)) as u8;
345    }
346
347    Some(buf)
348}
349
350/// Decodes a sequence of bytes into a sequence of signed integers such that each integer x
351/// satisfies |x| < 2^(bits-1) for a given parameter bits. bits can take either the value 6 or 8.
352pub fn decode_i8(buf: &[u8], bits: usize) -> Option<Vec<i8>> {
353    let mut x = [0_i8; N];
354
355    let mut i = 0;
356    let mut j = 0;
357    let mut acc = 0_u32;
358    let mut acc_len = 0;
359    let mask = (1_u32 << bits) - 1;
360    let a = (1 << bits) as u8;
361    let b = ((1 << (bits - 1)) - 1) as u8;
362
363    while i < N {
364        acc = (acc << 8) | (buf[j] as u32);
365        j += 1;
366        acc_len += 8;
367
368        while acc_len >= bits && i < N {
369            acc_len -= bits;
370            let w = (acc >> acc_len) & mask;
371
372            let w = w as u8;
373
374            let z = if w > b { w as i8 - a as i8 } else { w as i8 };
375
376            x[i] = z;
377            i += 1;
378        }
379    }
380
381    if (acc & ((1u32 << acc_len) - 1)) == 0 {
382        Some(x.to_vec())
383    } else {
384        None
385    }
386}