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 are 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
221 .coefficients
222 .iter()
223 .map(|&a| FalconFelt::new(-a).balanced_value() as i8)
224 .collect();
225 let f_i8_encoded = encode_i8(&f_i8, WIDTH_SMALL_POLY_COEFFICIENT).unwrap();
226 buffer.extend_from_slice(&f_i8_encoded);
227
228 let g_i8: Vec<i8> = g
229 .coefficients
230 .iter()
231 .map(|&a| FalconFelt::new(a).balanced_value() as i8)
232 .collect();
233 let g_i8_encoded = encode_i8(&g_i8, WIDTH_SMALL_POLY_COEFFICIENT).unwrap();
234 buffer.extend_from_slice(&g_i8_encoded);
235
236 let big_f_i8: Vec<i8> = neg_big_f
237 .coefficients
238 .iter()
239 .map(|&a| FalconFelt::new(-a).balanced_value() as i8)
240 .collect();
241 let big_f_i8_encoded = encode_i8(&big_f_i8, WIDTH_BIG_POLY_COEFFICIENT).unwrap();
242 buffer.extend_from_slice(&big_f_i8_encoded);
243 target.write_bytes(&buffer);
244 }
245}
246
247impl Deserializable for SecretKey {
248 fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
249 let byte_vector: [u8; SK_LEN] = source.read_array()?;
250
251 // check length
252 if byte_vector.len() < 2 {
253 return Err(DeserializationError::InvalidValue("Invalid encoding length: Failed to decode as length is different from the one expected".to_string()));
254 }
255
256 // read fields
257 let header = byte_vector[0];
258
259 // check fixed bits in header
260 if (header >> 4) != 5 {
261 return Err(DeserializationError::InvalidValue("Invalid header format".to_string()));
262 }
263
264 // check log n
265 let logn = (header & 15) as usize;
266 let n = 1 << logn;
267
268 // match against const variant generic parameter
269 if n != N {
270 return Err(DeserializationError::InvalidValue(
271 "Unsupported Falcon DSA variant".to_string(),
272 ));
273 }
274
275 if byte_vector.len() != SK_LEN {
276 return Err(DeserializationError::InvalidValue("Invalid encoding length: Failed to decode as length is different from the one expected".to_string()));
277 }
278
279 let chunk_size_f = ((n * WIDTH_SMALL_POLY_COEFFICIENT) + 7) >> 3;
280 let chunk_size_g = ((n * WIDTH_SMALL_POLY_COEFFICIENT) + 7) >> 3;
281 let chunk_size_big_f = ((n * WIDTH_BIG_POLY_COEFFICIENT) + 7) >> 3;
282
283 let f = decode_i8(&byte_vector[1..chunk_size_f + 1], WIDTH_SMALL_POLY_COEFFICIENT).unwrap();
284 let g = decode_i8(
285 &byte_vector[chunk_size_f + 1..(chunk_size_f + chunk_size_g + 1)],
286 WIDTH_SMALL_POLY_COEFFICIENT,
287 )
288 .unwrap();
289 let big_f = decode_i8(
290 &byte_vector[(chunk_size_f + chunk_size_g + 1)
291 ..(chunk_size_f + chunk_size_g + chunk_size_big_f + 1)],
292 WIDTH_BIG_POLY_COEFFICIENT,
293 )
294 .unwrap();
295
296 let f = Polynomial::new(f.iter().map(|&c| FalconFelt::new(c.into())).collect());
297 let g = Polynomial::new(g.iter().map(|&c| FalconFelt::new(c.into())).collect());
298 let big_f = Polynomial::new(big_f.iter().map(|&c| FalconFelt::new(c.into())).collect());
299
300 // big_g * f - g * big_f = p (mod X^n + 1)
301 let big_g = g.fft().hadamard_div(&f.fft()).hadamard_mul(&big_f.fft()).ifft();
302 let basis = [
303 g.map(|f| f.balanced_value()),
304 -f.map(|f| f.balanced_value()),
305 big_g.map(|f| f.balanced_value()),
306 -big_f.map(|f| f.balanced_value()),
307 ];
308 Ok(Self::from_short_lattice_basis(basis))
309 }
310}
311
312// HELPER FUNCTIONS
313// ================================================================================================
314
315/// Computes the complex FFT of the secret key polynomials.
316fn to_complex_fft(basis: &[Polynomial<i16>; 4]) -> [Polynomial<Complex<f64>>; 4] {
317 let [g, f, big_g, big_f] = basis.clone();
318 let g_fft = g.map(|cc| Complex64::new(*cc as f64, 0.0)).fft();
319 let minus_f_fft = f.map(|cc| -Complex64::new(*cc as f64, 0.0)).fft();
320 let big_g_fft = big_g.map(|cc| Complex64::new(*cc as f64, 0.0)).fft();
321 let minus_big_f_fft = big_f.map(|cc| -Complex64::new(*cc as f64, 0.0)).fft();
322 [g_fft, minus_f_fft, big_g_fft, minus_big_f_fft]
323}
324
325/// Encodes a sequence of signed integers such that each integer x satisfies |x| < 2^(bits-1)
326/// for a given parameter bits. bits can take either the value 6 or 8.
327pub fn encode_i8(x: &[i8], bits: usize) -> Option<Vec<u8>> {
328 let maxv = (1 << (bits - 1)) - 1_usize;
329 let maxv = maxv as i8;
330 let minv = -maxv;
331
332 for &c in x {
333 if c > maxv || c < minv {
334 return None;
335 }
336 }
337
338 let out_len = ((N * bits) + 7) >> 3;
339 let mut buf = vec![0_u8; out_len];
340
341 let mut acc = 0_u32;
342 let mut acc_len = 0;
343 let mask = ((1_u16 << bits) - 1) as u8;
344
345 let mut input_pos = 0;
346 for &c in x {
347 acc = (acc << bits) | (c as u8 & mask) as u32;
348 acc_len += bits;
349 while acc_len >= 8 {
350 acc_len -= 8;
351 buf[input_pos] = (acc >> acc_len) as u8;
352 input_pos += 1;
353 }
354 }
355 if acc_len > 0 {
356 buf[input_pos] = (acc >> (8 - acc_len)) as u8;
357 }
358
359 Some(buf)
360}
361
362/// Decodes a sequence of bytes into a sequence of signed integers such that each integer x
363/// satisfies |x| < 2^(bits-1) for a given parameter bits. bits can take either the value 6 or 8.
364pub fn decode_i8(buf: &[u8], bits: usize) -> Option<Vec<i8>> {
365 let mut x = [0_i8; N];
366
367 let mut i = 0;
368 let mut j = 0;
369 let mut acc = 0_u32;
370 let mut acc_len = 0;
371 let mask = (1_u32 << bits) - 1;
372 let a = (1 << bits) as u8;
373 let b = ((1 << (bits - 1)) - 1) as u8;
374
375 while i < N {
376 acc = (acc << 8) | (buf[j] as u32);
377 j += 1;
378 acc_len += 8;
379
380 while acc_len >= bits && i < N {
381 acc_len -= bits;
382 let w = (acc >> acc_len) & mask;
383
384 let w = w as u8;
385
386 let z = if w > b { w as i8 - a as i8 } else { w as i8 };
387
388 x[i] = z;
389 i += 1;
390 }
391 }
392
393 if (acc & ((1u32 << acc_len) - 1)) == 0 {
394 Some(x.to_vec())
395 } else {
396 None
397 }
398}