Skip to main content

rfc6979/
lib.rs

1#![no_std]
2#![doc = include_str!("../README.md")]
3#![doc(
4    html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/8f1a9894/logo.svg",
5    html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/8f1a9894/logo.svg"
6)]
7
8//! ## Usage
9//!
10//! See also: [`KGenerator`] documentation.
11//!
12//! ```
13//! use hex_literal::hex;
14//! use rfc6979::bigint::U256;
15//! use sha2::{Digest, Sha256};
16//!
17//! // NIST P-256 field modulus
18//! const NIST_P256_MODULUS: U256 = U256::from_be_hex(
19//!     "FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551"
20//! );
21//!
22//! // Private key for RFC6979 NIST P256/SHA256 test case (see RFC6979 Appendix A.2.5).
23//! // WARNING: don't hardcode private keys in your source code!
24//! const RFC6979_KEY: [u8; 32] =
25//!     hex!("C9AFA9D845BA75166B5C215767B1D6934E50C3DB36E89B127B8A622B120F6721");
26//!
27//! // Test message for RFC6979 NIST P256/SHA256 test case
28//! const RFC6979_MSG: &[u8] = b"sample";
29//!
30//! // Expected K for RFC6979 NIST P256/SHA256 test case
31//! const RFC6979_EXPECTED_K: [u8; 32] =
32//!     hex!("A6E3C57DD01ABE90086538398355DD4C3B17AA873382B0F24D6129493D8AAD60");
33//!
34//! let h = Sha256::digest(RFC6979_MSG);
35//! let aad = b"";
36//! let mut kgen = rfc6979::KGenerator::<Sha256, U256>::new(&RFC6979_KEY, &h, aad, &NIST_P256_MODULUS);
37//!
38//! let mut k = [0u8; U256::BYTES];
39//! kgen.fill_next_k(&mut k);
40//! assert_eq!(k, RFC6979_EXPECTED_K);
41//! ```
42
43mod hmac_drbg;
44
45pub use bigint;
46pub use hmac;
47pub use hmac::digest::array::typenum::consts;
48
49use crate::hmac_drbg::HmacDrbg;
50use bigint::{Encoding, Limb, Unsigned};
51use core::fmt;
52use hmac::digest::{Digest, OutputSizeUser, block_api::BlockSizeUser};
53
54/// Deterministic generator for the ephemeral scalar `k` as used by (EC)DSA.
55pub struct KGenerator<'a, D: OutputSizeUser, U> {
56    drbg: HmacDrbg<D>,
57    q: &'a U,
58}
59
60impl<'a, D, U> KGenerator<'a, D, U>
61where
62    D: BlockSizeUser + Digest,
63    U: Unsigned + Encoding,
64{
65    /// Initialize `k` generator.
66    ///
67    /// Accepts the following parameters and inputs:
68    ///
69    /// - `x`: secret key
70    /// - `h`: raw hash/digest of input message
71    /// - `data`: additional associated data, e.g. CSRNG output used as added entropy
72    /// - `q`: field modulus
73    pub fn new(x: &[u8], h: &[u8], data: &[u8], q: &'a U) -> Self {
74        // Process `h` through `bits2octets`
75        let mut h_scratch = q.to_be_bytes();
76        let h_ref = &mut h_scratch.as_mut()[..x.len()];
77        bits2octets(h, q, h_ref);
78
79        let drbg = HmacDrbg::<D>::new(x, h_ref, data);
80        Self { drbg, q }
81    }
82
83    /// Generate a candidate `k` value.
84    ///
85    /// This may be called repeatedly in the event a particular `k` is unsuitable, e.g. the
86    /// resulting `r` value is zero.
87    pub fn fill_next_k(&mut self, k: &mut [u8]) {
88        debug_assert_eq!(self.q.bits().div_ceil(8).try_into(), Ok(k.len()));
89
90        loop {
91            self.drbg.fill_bytes(k);
92            let candidate_k = bits2int(k, self.q);
93            if ((!candidate_k.is_zero()) & candidate_k.ct_lt(self.q)).to_bool() {
94                int2octets(&candidate_k, self.q, k);
95                return;
96            }
97        }
98    }
99}
100
101impl<'a, D, U> fmt::Debug for KGenerator<'a, D, U>
102where
103    D: BlockSizeUser + Digest,
104    U: Unsigned + Encoding,
105{
106    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
107        f.debug_struct("KGenerator").finish_non_exhaustive()
108    }
109}
110
111/// `bits2int` transform as defined in [RFC6979 §2.3.2]: "Bit String to Integer"
112///
113/// From the RFC:
114///
115/// >  The bits2int transform takes as input a sequence of blen bits and
116/// >  outputs a non-negative integer that is less than 2^qlen.  It consists
117/// >  of the following steps:
118/// >
119/// >  1. The sequence is first truncated or expanded to length qlen:
120/// >
121/// >  *  if qlen < blen, then the qlen leftmost bits are kept, and
122/// >     subsequent bits are discarded;
123/// >
124/// >  *  otherwise, qlen-blen bits (of value zero) are added to the
125/// >     left of the sequence (i.e., before the input bits in the
126/// >     sequence order).
127/// >
128/// >  2. The resulting sequence is then converted to an integer value
129/// >     using the big-endian convention: if input bits are called b_0
130/// >     (leftmost) to b_(qlen-1) (rightmost), then the resulting value
131/// >     is:
132/// >
133/// >        b_0*2^(qlen-1) + b_1*2^(qlen-2) + ... + b_(qlen-1)*2^0
134/// >
135/// >  The bits2int transform can also be described in the following way:
136/// >  the input bit sequence (of length blen) is transformed into an
137/// >  integer using the big-endian convention.  Then, if blen is greater
138/// >  than qlen, the resulting integer is divided by two to the power
139/// >  blen-qlen (Euclidian division: the remainder is discarded); in many
140/// >  software implementations of arithmetics on big integers, that
141/// >  division is equivalent to a "right shift" by blen-qlen bits.
142///
143/// [RFC6979 §2.3.2]: https://datatracker.ietf.org/doc/html/rfc6979#section-2.3.2
144#[inline]
145#[allow(clippy::as_conversions, clippy::cast_possible_truncation)]
146fn bits2int<U>(mut b: &[u8], q: &U) -> U
147where
148    U: Unsigned + Encoding,
149{
150    debug_assert!(!b.is_empty());
151
152    let qlen = q.bits();
153    let mut blen = u32::try_from(b.len())
154        .ok()
155        .and_then(|len| len.checked_mul(8))
156        .expect("overflow");
157
158    let bits_diff = blen.saturating_sub(qlen);
159
160    // Ensure `b` is within one octet of the length of `q`. This helps ensure we don't exceed the
161    // capacity of `U`. This effectively emulates the right shift described in the RFC by truncating
162    // the least significant bytes.
163    let bytes_to_discard = (bits_diff >> 3) as usize;
164    if bytes_to_discard > 0 {
165        b = &b[..b.len() - bytes_to_discard];
166        blen -= (bytes_to_discard as u32) * 8;
167    }
168
169    let mut int = U::from_be_slice_truncated(b, blen);
170    int.shr_assign(blen.saturating_sub(qlen));
171    int
172}
173
174/// `int2octets` transform as defined in [RFC6979 §2.3.3]: "Integer to Octet String"
175///
176/// From the RFC:
177///
178/// > An integer value x less than q (and, in particular, a value that has
179/// > been taken modulo q) can be converted into a sequence of rlen bits,
180/// > where rlen = 8*ceil(qlen/8).  This is the sequence of bits obtained
181/// > by big-endian encoding.  In other words, the sequence bits x_i (for i
182/// > ranging from 0 to rlen-1) are such that:
183/// >
184/// > x = x_0*2^(rlen-1) + x_1*2^(rlen-2) + ... + x_(rlen-1)
185/// >
186/// > We call this transform int2octets.  Since rlen is a multiple of 8
187/// > (the smallest multiple of 8 that is not smaller than qlen), then the
188/// > resulting sequence of bits is also a sequence of octets, hence the
189/// > name.
190///
191/// [RFC6979 §2.3.3]: https://datatracker.ietf.org/doc/html/rfc6979#section-2.3.3
192#[allow(clippy::as_conversions)]
193fn int2octets<'a, U: Unsigned>(x: &U, q: &U, out: &'a mut [u8]) -> &'a [u8] {
194    debug_assert!(x < q);
195    let qlen = q.bits();
196    let rlen = qlen.div_ceil(8) as usize; // NOTE: rlen in RFC is bits; we use bytes
197
198    debug_assert!(out.len() >= rlen);
199    let out = &mut out[..rlen];
200
201    let xlimbs: &[Limb] = x.as_ref();
202    for (limb, chunk) in xlimbs.iter().zip(out.rchunks_mut(Limb::BYTES)) {
203        let bytes = limb.to_be_bytes();
204        let offset = Limb::BYTES.saturating_sub(chunk.len());
205        chunk.copy_from_slice(&bytes[offset..]);
206    }
207
208    out
209}
210
211/// `bits2octets` transform as defined in [RFC6979 §2.3.4]: "Bit String to Octet String"
212///
213/// From the RFC:
214///
215/// > The bits2octets transform takes as input a sequence of blen bits and
216/// > outputs a sequence of rlen bits.  It consists of the following steps:
217/// >
218/// > 1. The input sequence b is converted into an integer value z1
219/// >    through the bits2int transform:
220/// >
221/// >       z1 = bits2int(b)
222/// >
223/// > 2. z1 is reduced modulo q, yielding z2 (an integer between 0 and
224/// >    q-1, inclusive):
225/// >
226/// >       z2 = z1 mod q
227/// >
228/// >    Note that since z1 is less than 2^qlen, that modular reduction
229/// >    can be implemented with a simple conditional subtraction:
230/// >    z2 = z1-q if that value is non-negative; otherwise, z2 = z1.
231/// >
232/// > 3.  z2 is transformed into a sequence of octets (a sequence of rlen
233/// >    bits) by applying int2octets.
234///
235/// [RFC6979 §2.3.3]: https://datatracker.ietf.org/doc/html/rfc6979#section-2.3.3
236fn bits2octets<'a, U>(b: &[u8], q: &U, out: &'a mut [u8]) -> &'a [u8]
237where
238    U: Unsigned + Encoding,
239{
240    let z1 = bits2int(b, q);
241    let mut z2 = z1.wrapping_sub(q);
242
243    // Perform modular reduction via conditional subtraction, since we know `z1` is the same bit
244    // length as `q` and therefore only one such subtraction is required.
245    // (see description of this approach in the rustdoc)
246    z2.ct_assign(&z1, z1.ct_lt(q));
247    int2octets(&z2, q, out)
248}
249
250#[cfg(test)]
251mod tests {
252    mod bits2int {
253        use crate::bits2int;
254        use bigint::{BitOps, BoxedUint, U256};
255
256        #[test]
257        fn left_pads_when_blen_is_shorter_than_qlen() {
258            let q = U256::from_u64(0x800);
259            assert_eq!(bits2int(&[0x2a], &q), U256::from_u64(0x2a));
260        }
261
262        #[test]
263        fn keeps_exact_qlen_bits() {
264            let q = U256::from_u64(0x80);
265            assert_eq!(bits2int(&[0xab], &q), U256::from_u64(0xab));
266        }
267
268        // K-163 inspired test case
269        #[test]
270        fn discards_trailing_bytes_then_shifts_remaining_bits() {
271            let q = U256::ONE.shl_vartime(162);
272            let b = [0xff; 32];
273
274            assert_eq!(
275                bits2int(&b, &q),
276                U256::from_be_hex(
277                    "000000000000000000000007FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
278                )
279            );
280        }
281
282        #[test]
283        fn truncates_leftmost_bits_on_byte_boundary() {
284            let q = U256::from_u64(0x80);
285            assert_eq!(bits2int(&[0xab, 0xcd], &q), U256::from_u64(0xab));
286        }
287
288        #[test]
289        fn truncates_leftmost_bits_across_partial_byte() {
290            let q = U256::from_u64(0x800);
291            assert_eq!(bits2int(&[0xab, 0xcd], &q), U256::from_u64(0xabc));
292        }
293
294        #[test]
295        fn boxed_matches_fixed_for_short_input() {
296            let q = U256::from_be_hex(
297                "FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551",
298            );
299            let q_boxed = BoxedUint::from_be_slice(&q.to_be_bytes(), q.bits_precision()).unwrap();
300            let h = [0xab; 20];
301            assert_eq!(bits2int(&h, &q_boxed), bits2int(&h, &q),);
302        }
303    }
304
305    mod int2octets {
306        use crate::int2octets;
307        use bigint::U256;
308
309        #[test]
310        fn encodes_single_octet() {
311            let q = U256::from_u64(0x80);
312            let x = U256::from_u64(0x2a);
313            let mut out = [0u8; 32];
314            assert_eq!(int2octets(&x, &q, &mut out), &[0x2a]);
315        }
316
317        #[test]
318        fn left_pads_to_qlen_octets() {
319            let q = U256::from_u64(0x800);
320            let x = U256::from_u64(0x2a);
321            let mut out = [0u8; 32];
322            assert_eq!(int2octets(&x, &q, &mut out), &[0x00, 0x2a]);
323        }
324
325        #[test]
326        fn int2octets_preserves_full_width_value() {
327            let q = U256::from_u64(0x800);
328            let x = U256::from_u64(0x7ff);
329            let mut out = [0u8; 32];
330            assert_eq!(int2octets(&x, &q, &mut out), &[0x07, 0xff]);
331        }
332    }
333
334    mod bits2octets {
335        use crate::bits2octets;
336        use bigint::{BoxedUint, U256};
337
338        const EXAMPLE_Q: U256 =
339            U256::from_be_hex("FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551");
340
341        #[test]
342        fn already_reduced() {
343            let q = U256::from_u64(0x80);
344            let mut out = [0u8; 32];
345            assert_eq!(bits2octets(&[0x2a], &q, &mut out), &[0x2a]);
346        }
347
348        #[test]
349        fn needs_reduction() {
350            let q = U256::from_u64(0x80);
351            let mut out = [0u8; 32];
352            assert_eq!(bits2octets(&[0xff], &q, &mut out), &[0x7f]);
353        }
354
355        #[test]
356        fn left_pads_when_blen_is_shorter_than_qlen() {
357            let h = [0xab; 20];
358            let mut out = [0u8; 32];
359
360            assert_eq!(
361                bits2octets(&h, &EXAMPLE_Q, &mut out),
362                &[
363                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab,
364                    0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab,
365                ],
366            );
367        }
368
369        #[test]
370        fn boxed_left_pads_short_hash_to_rlen() {
371            let boxed_q = BoxedUint::from_be_slice(&EXAMPLE_Q.to_be_bytes(), 256).unwrap();
372            let h = [0xab; 20];
373            let mut out = [0u8; 32];
374
375            assert_eq!(
376                bits2octets(&h, &boxed_q, &mut out),
377                &[
378                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab,
379                    0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab,
380                ],
381            );
382        }
383
384        #[test]
385        fn boxed_160_bit_hash_with_256_bit_q() {
386            let q = U256::from_be_hex(
387                "87A8E61DB4B6663CFFBBD19C6519599998CEEF608660DD0F25D2CE4EDDBF8A9B",
388            );
389
390            let boxed_q = BoxedUint::from_be_slice(&q.to_be_bytes(), 256).unwrap();
391
392            let h = [
393                0x81, 0x53, 0x2b, 0x5b, 0xe0, 0x21, 0xe9, 0xb6, 0xe9, 0x87, 0xf3, 0x37, 0x66, 0x31,
394                0x97, 0x4e, 0xa3, 0x1b, 0x72, 0x37,
395            ];
396
397            let mut out = [0u8; 32];
398            let actual = bits2octets(&h, &boxed_q, &mut out);
399            assert_eq!(&actual[..12], &[0u8; 12]);
400            assert_eq!(&actual[12..], &h);
401        }
402    }
403}