gmcrypto-core 1.3.0

Constant-time-designed pure-Rust SM2/SM3/SM4 primitives (no_std + alloc) with an in-CI dudect timing-leak regression harness
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
//! SM2 sign and verify (GB/T 32918.2-2017).

use crate::asn1::sig::encode_sig;
use crate::sm2::curve::{Fn, Fp, GX_HEX, GY_HEX, b};
use crate::sm2::private_key::Sm2PrivateKey;
use crate::sm2::public_key::Sm2PublicKey;
use crate::sm2::scalar_mul::mul_g;
use crate::sm3::{DIGEST_SIZE, Sm3};
use alloc::vec::Vec;
use crypto_bigint::U256;
use rand_core::TryCryptoRng;
use subtle::{Choice, ConditionallySelectable, ConstantTimeEq, ConstantTimeLess, CtOption};
use zeroize::Zeroize;

/// Default signer ID per GM/T 0009: 16 ASCII bytes "1234567812345678".
pub const DEFAULT_SIGNER_ID: &[u8; 16] = b"1234567812345678";

/// Maximum signer-ID length in bytes.
///
/// Per GM/T 0009, the `Z_A` computation prepends `ENTL_A`, the ID's
/// bit-length encoded as a 16-bit big-endian field. The byte length
/// must therefore satisfy `id.len() * 8 ≤ u16::MAX`, i.e.
/// `id.len() ≤ 8191`. Inputs above this would silently wrap to a
/// non-spec `ENTL_A` in earlier code paths; sign / verify now reject
/// such inputs at the API boundary.
pub const MAX_ID_LEN: usize = (u16::MAX as usize) / 8;

/// Compute `Z_A`: `SM3(ENTL_A || ID_A || a || b || x_G || y_G || x_A || y_A)`.
///
/// `ENTL_A` is the 16-bit big-endian bit-length of `ID_A`.
///
/// # Panics
///
/// Panics if the public key point is not finite (at infinity), or if
/// `id.len() > MAX_ID_LEN` (8191 bytes — the largest length whose
/// bit-count fits in `u16`). API-level callers (`sign_with_id`,
/// `verify_with_id`) reject over-length IDs before reaching this
/// function, so the assertion only fires on direct misuse.
#[must_use]
pub fn compute_z(public: &Sm2PublicKey, id: &[u8]) -> [u8; DIGEST_SIZE] {
    assert!(
        id.len() <= MAX_ID_LEN,
        "id.len() exceeds MAX_ID_LEN — ENTL_A would silently wrap"
    );
    let mut h = Sm3::new();

    // ENTL_A: 16-bit BE bit-length of ID. The above assertion guarantees
    // the multiplication does not overflow `u16`.
    #[allow(clippy::cast_possible_truncation)]
    let entl: u16 = (id.len() as u16) * 8;
    h.update(&entl.to_be_bytes());
    h.update(id);

    // a ≡ -3 (mod p), encoded as 32 BE bytes of (p - 3).
    let three = U256::from_u64(3);
    let p_minus_three = Fp::MODULUS.as_ref().wrapping_sub(&three);
    h.update(&p_minus_three.to_be_bytes());

    // b
    h.update(&b().retrieve().to_be_bytes());

    // (x_G, y_G)
    h.update(&U256::from_be_hex(GX_HEX).to_be_bytes());
    h.update(&U256::from_be_hex(GY_HEX).to_be_bytes());

    // (x_A, y_A)
    let (px, py) = public.point().to_affine().expect("public key is finite");
    h.update(&px.retrieve().to_be_bytes());
    h.update(&py.retrieve().to_be_bytes());

    h.finalize()
}

/// Fixed-K signing retry budget. v0.1 = 2.
pub(crate) const SIGN_RETRY_BUDGET: usize = 2;

/// Sign `message` with `id` under `key`.
///
/// Returns a DER-encoded `SEQUENCE { r, s }` signature, or
/// [`crate::Error::Failed`] if the `SIGN_RETRY_BUDGET` was exhausted
/// (probability ~9·2^-512 with a uniform CSPRNG).
///
/// # Constant-time contract
///
/// Unconditionally runs `SIGN_RETRY_BUDGET` iterations regardless of
/// which (if any) iteration produced a valid signature.
///
/// # Errors
///
/// Returns [`crate::Error::Failed`] if `id.len() > MAX_ID_LEN` (the
/// `ENTL_A` field is 16-bit), if the supplied RNG fails (its
/// `try_fill_bytes` errored — the failure is collapsed to `Failed`,
/// never propagated as a panic), or if every retry in the budget
/// produced an invalid candidate (`r == 0`,
/// `r + k == n`, or `s == 0`). Failure modes are deliberately collapsed
/// to one variant per the failure-mode-invariant policy; see
/// `SECURITY.md`.
///
/// # RNG bound
///
/// `R: TryCryptoRng` is the **fallible** `rand_core` cryptographic-RNG
/// trait. This is a deliberate ecosystem coupling: `rand_core` is the
/// interop point for RNGs, and the fallible bound gives a defined,
/// no-panic path when the RNG fails (the error collapses to `Failed`).
pub fn sign_with_id<R: TryCryptoRng>(
    key: &Sm2PrivateKey,
    id: &[u8],
    message: &[u8],
    rng: &mut R,
) -> Result<Vec<u8>, crate::Error> {
    let (r, s) = sign_raw_with_id(key, id, message, rng)?;
    // `sign_raw_with_id` stays `U256`-typed (it is `#[doc(hidden)]`, dudect-only);
    // the public `encode_sig` boundary takes 32-byte big-endian scalars (v0.22).
    Ok(encode_sig(
        &crate::u256_to_be32(&r),
        &crate::u256_to_be32(&s),
    ))
}

/// Sign and return the raw `(r, s)` scalar pair *without* DER encoding.
///
/// This is the constant-time-relevant work in [`sign_with_id`]: it runs
/// the masked-select retry loop and produces a valid `(r, s)`. The DER
/// encoding step in [`sign_with_id`] is variable-time on `(r, s)` (which
/// is public output), so timing-leak detection harnesses should target
/// this function instead of [`sign_with_id`] to test the crypto path in
/// isolation.
///
/// **Not part of the public API — not covered by SemVer.** This surface is
/// provided solely for the in-repo dudect timing-leak harness; it is
/// `#[doc(hidden)]` (hidden from rustdoc) and may change or be removed in any
/// release, including patch releases, without notice. Application code must use
/// [`sign_with_id`].
///
/// # Errors
///
/// Same as [`sign_with_id`]: returns [`crate::Error::Failed`] if the
/// RNG fails or if every retry produced an invalid candidate (`r == 0`,
/// `r + k == n`, or `s == 0`).
#[doc(hidden)]
pub fn sign_raw_with_id<R: TryCryptoRng>(
    key: &Sm2PrivateKey,
    id: &[u8],
    message: &[u8],
    rng: &mut R,
) -> Result<(U256, U256), crate::Error> {
    if id.len() > MAX_ID_LEN {
        return Err(crate::Error::Failed);
    }
    let public = key.public_key();
    let z = compute_z(&public, id);

    let e_bytes = {
        let mut h = Sm3::new();
        h.update(&z);
        h.update(message);
        h.finalize()
    };
    let e_scalar = Fn::new(&U256::from_be_slice(&e_bytes));

    let mut chosen: CtOption<RsPair> = CtOption::new(RsPair::default(), Choice::from(0));
    for _ in 0..SIGN_RETRY_BUDGET {
        // `None` == an RNG failure (public, not secret-derived). Short-circuit
        // to `Failed` so a transient RNG error is never masked by a later
        // retry succeeding — honoring the A-3 / FFI no-panic-RNG contract
        // (the RNG must produce entropy on every attempt). Candidate
        // invalidity (`r`/`s`/exhaustion) stays a masked `CtOption`, not a
        // branch.
        let Some(candidate) = try_sign_once(key, &e_scalar, rng) else {
            return Err(crate::Error::Failed);
        };
        chosen = ct_or_else(chosen, candidate);
    }

    let pair: Option<RsPair> = chosen.into();
    let pair = pair.ok_or(crate::Error::Failed)?;
    Ok((pair.r, pair.s))
}

#[derive(Clone, Copy, Debug, Default)]
struct RsPair {
    r: U256,
    s: U256,
}

impl ConditionallySelectable for RsPair {
    fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self {
        Self {
            r: U256::conditional_select(&a.r, &b.r, choice),
            s: U256::conditional_select(&a.s, &b.s, choice),
        }
    }
}

/// Returns `None` on RNG failure (a *public* condition the caller short-
/// circuits to `Failed`); `Some(CtOption)` otherwise, where the `CtOption`
/// is the masked candidate signature (invalid if `r`/`s` rejected or the
/// nonce sampler exhausted its budget).
#[allow(clippy::similar_names, clippy::many_single_char_names)]
fn try_sign_once<R: TryCryptoRng>(
    key: &Sm2PrivateKey,
    e: &Fn,
    rng: &mut R,
) -> Option<CtOption<RsPair>> {
    // RNG FAILURE is public (not secret-derived): the `?` propagates it as
    // `None` so the caller fails the whole operation. Budget EXHAUSTION, by
    // contrast, IS secret-derived (it depends on the random nonce bytes), so
    // the sampler returns it as the `sample_ok` Choice rather than as `None`:
    // on exhaustion `k` is a dummy (1) and the FULL signing computation still
    // runs in constant time, with the result masked out by folding
    // `sample_ok` into `valid` below. No branch on the exhaustion bit.
    let (mut k, sample_ok) = sample_nonzero_scalar(rng)?;
    let kg = mul_g(&k);
    let (x1, _y1) = kg.to_affine().expect("k·G is finite for k != 0");

    let x1_in_n = Fn::new(&x1.retrieve());
    let r = *e + x1_in_n;

    let r_u = r.retrieve();
    let r_plus_k = (r + k).retrieve();
    let r_zero: Choice = r_u.ct_eq(&U256::ZERO);
    let rk_zero: Choice = r_plus_k.ct_eq(&U256::ZERO);
    let bad_r = r_zero | rk_zero;

    let d = key.scalar();
    let one = Fn::new(&U256::ONE);
    let mut one_plus_d = one + *d;
    let one_plus_d_inv = one_plus_d.invert();
    let mut rd = r * *d;
    let mut k_minus_rd = k - rd;

    let mut inv_unwrapped: Fn = one_plus_d_inv.unwrap_or(Fn::new(&U256::ONE));
    let inv_ok: Choice = one_plus_d_inv.is_some().into();

    let mut s = inv_unwrapped * k_minus_rd;
    let s_u = s.retrieve();
    let s_zero: Choice = s_u.ct_eq(&U256::ZERO);

    // Fold the sampler's `sample_ok` in: on budget exhaustion the dummy `k`
    // produced an (r, s) that must be rejected without a branch.
    let valid = !bad_r & !s_zero & inv_ok & sample_ok;
    let out = CtOption::new(RsPair { r: r_u, s: s_u }, valid);

    // B-4 (v0.23): wipe the secret-derived scalar intermediates. `Fn`
    // (`ConstMontyForm`) implements `zeroize::DefaultIsZeroes` under
    // crypto-bigint's `zeroize` feature (enabled in the workspace
    // `Cargo.toml`), giving a real `.zeroize()` on the Montgomery
    // representation. The nonce `k`, `1 + d` (which reveals `d`
    // additively), the inverse `(1+d)^-1`, `r·d`, `k − r·d`, and `s` are
    // all functions of the secret `k`/`d`; a nonce leak alone permits
    // private-key recovery from `(r, s)`. The public outputs `r_u`/`s_u`
    // (already in `out`) are deliberately NOT wiped. (The `subtle::CtOption`
    // `one_plus_d_inv` is `Copy` and holds the same inverse value as the
    // wiped `inv_unwrapped`; subtle exposes no `zeroize` on `CtOption`, so
    // that duplicate bit-pattern falls under the documented best-effort
    // stack-zeroization posture — see `SECURITY.md`.)
    k.zeroize();
    one_plus_d.zeroize();
    inv_unwrapped.zeroize();
    rd.zeroize();
    k_minus_rd.zeroize();
    s.zeroize();

    Some(out)
}

/// Fixed-budget constant-time nonzero-scalar sampler. Per-draw reject
/// probability ≈ 2^-32 (n ≈ 2^256 − 2^224), so a 4-draw budget exhausts
/// (all draws invalid) with probability ≈ 2^-128.
///
/// Returns:
/// - `None` **only** on RNG failure — a *public* (not secret-derived)
///   condition the caller may branch on (it collapses to `Failed`).
/// - `Some((k, sample_ok))` otherwise, where `sample_ok` is a constant-time
///   [`Choice`] that is set iff a valid draw was found. On exhaustion
///   (`sample_ok == 0`) `k` is a **dummy** scalar (1, a valid curve scalar
///   that cannot panic `mul_g`); the caller folds `sample_ok` into its own
///   validity mask instead of branching on the exhaustion bit (which IS
///   secret-derived). The loop always runs `NONCE_SAMPLE_BUDGET` iterations
///   and the first valid draw is kept by masked select — no `if`/`bool` on
///   secret-derived bytes.
pub(crate) const NONCE_SAMPLE_BUDGET: usize = 4;

pub(crate) fn sample_nonzero_scalar<R: TryCryptoRng>(rng: &mut R) -> Option<(Fn, Choice)> {
    let n = *Fn::MODULUS.as_ref();
    let mut chosen = U256::ONE;
    let mut found = Choice::from(0u8);
    for _ in 0..NONCE_SAMPLE_BUDGET {
        let mut buf = [0u8; 32];
        // RNG failure is NOT secret-derived: collapsing it to None here is
        // a public-path early return (becomes Error::Failed upstream). Wipe
        // both this draw's buffer AND any already-selected `chosen` scalar
        // (an earlier valid draw) before bailing.
        if rng.try_fill_bytes(&mut buf).is_err() {
            buf.zeroize();
            chosen.zeroize();
            return None;
        }
        let candidate = U256::from_be_slice(&buf);
        let valid = !candidate.ct_eq(&U256::ZERO) & candidate.ct_lt(&n);
        let take = valid & !found; // keep the FIRST valid draw
        chosen = U256::conditional_select(&chosen, &candidate, take);
        found |= valid;
        buf.zeroize();
    }
    // Always return the (possibly dummy) scalar + the CT validity bit;
    // budget exhaustion is folded into the caller's mask, never branched.
    let k = Fn::new(&chosen);
    chosen.zeroize();
    Some((k, found))
}

fn ct_or_else<T: ConditionallySelectable + Default>(a: CtOption<T>, b: CtOption<T>) -> CtOption<T> {
    let a_some = a.is_some();
    let b_some = b.is_some();
    let a_val = a.unwrap_or_else(T::default);
    let b_val = b.unwrap_or_else(T::default);
    let chosen = T::conditional_select(&b_val, &a_val, a_some);
    let some = a_some | b_some;
    CtOption::new(chosen, some)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::sm2::private_key::Sm2PrivateKey;
    use core::convert::Infallible;
    use getrandom::SysRng;
    use rand_core::{TryCryptoRng, TryRng};

    struct SequenceRng {
        values: [U256; NONCE_SAMPLE_BUDGET],
        index: usize,
    }

    impl TryRng for SequenceRng {
        type Error = Infallible;

        fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
            Ok(0)
        }

        fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
            Ok(0)
        }

        fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Self::Error> {
            assert_eq!(dst.len(), 32);
            let value = self.values[self.index];
            self.index += 1;
            dst.copy_from_slice(&value.to_be_bytes());
            Ok(())
        }
    }

    impl TryCryptoRng for SequenceRng {}

    /// GB/T 32918.2 Appendix A.2: `Z_A` for ID="ALICE123@YAHOO.COM" and the
    /// sample private key D. Expected:
    /// 26db4bc1839bd22e97e1dab667ec5e0a730d5e16521398b4435c576a93afd7ed.
    #[test]
    fn z_appendix_a2() {
        let d =
            U256::from_be_hex("3945208F7B2144B13F36E38AC6D39F95889393692860B51A42FB81EF4DF7C5B8");
        let key = Sm2PrivateKey::from_scalar_inner(d).expect("valid scalar");
        let public = key.public_key();
        let z = compute_z(&public, b"ALICE123@YAHOO.COM");

        #[allow(clippy::format_collect)]
        let z_hex: alloc::string::String =
            z.iter().map(|byte| alloc::format!("{byte:02x}")).collect();
        assert_eq!(
            z_hex,
            "26db4bc1839bd22e97e1dab667ec5e0a730d5e16521398b4435c576a93afd7ed"
        );
    }

    /// Sign rejects IDs above `MAX_ID_LEN`. Earlier code paths silently
    /// wrapped the `ENTL_A` field via `wrapping_mul(8)`; the API now
    /// rejects at the boundary.
    #[test]
    fn sign_over_long_id_rejected() {
        let d =
            U256::from_be_hex("3945208F7B2144B13F36E38AC6D39F95889393692860B51A42FB81EF4DF7C5B8");
        let key = Sm2PrivateKey::from_scalar_inner(d).expect("valid scalar");
        let too_long = alloc::vec![0u8; MAX_ID_LEN + 1];
        let mut rng = SysRng;
        let result = sign_with_id(&key, &too_long, b"msg", &mut rng);
        assert_eq!(result, Err(crate::Error::Failed));
    }

    /// The fixed-budget masked sampler keeps the FIRST valid draw and
    /// rejects an out-of-range (`>= n`) first candidate via masked
    /// select. v0.23 (B-7): the sampler runs the full
    /// `NONCE_SAMPLE_BUDGET` regardless of which draw was valid (no
    /// data-dependent loop count), so the RNG is consumed exactly
    /// `NONCE_SAMPLE_BUDGET` times.
    #[test]
    fn sample_nonzero_scalar_rejects_candidates_above_order() {
        let n_plus_one = Fn::MODULUS.as_ref().wrapping_add(&U256::ONE);
        // First draw is out-of-range (rejected); second is the valid
        // value 2 (kept); the remaining draws are also valid but must
        // NOT displace the first-valid representative.
        let mut rng = SequenceRng {
            values: [
                n_plus_one,
                U256::from_u64(2),
                U256::from_u64(7),
                U256::from_u64(9),
            ],
            index: 0,
        };

        let (k, sample_ok) = sample_nonzero_scalar(&mut rng).expect("rng ok");
        assert!(bool::from(sample_ok), "a valid draw was found");
        assert_eq!(k.retrieve(), U256::from_u64(2), "first valid draw is kept");
        assert_eq!(
            rng.index, NONCE_SAMPLE_BUDGET,
            "fixed-budget sampler consumes exactly NONCE_SAMPLE_BUDGET draws"
        );
    }

    /// All-invalid draws exhaust the budget → `Some((dummy, sample_ok=0))`
    /// (NOT `None`, which is reserved for RNG failure). The exhaustion bit
    /// is folded into the caller's CT validity mask, never branched.
    /// Uses `n` itself (rejected by `< n`) for every draw.
    #[test]
    fn sample_nonzero_scalar_exhausts_budget_to_invalid_choice() {
        let n = *Fn::MODULUS.as_ref();
        let mut rng = SequenceRng {
            values: [n; NONCE_SAMPLE_BUDGET],
            index: 0,
        };
        let (_dummy, sample_ok) = sample_nonzero_scalar(&mut rng).expect("rng ok");
        assert!(!bool::from(sample_ok), "exhaustion yields sample_ok == 0");
        assert_eq!(rng.index, NONCE_SAMPLE_BUDGET);
    }

    /// An erroring RNG collapses to `None` (the no-panic RNG-failure
    /// path).
    #[test]
    fn sample_nonzero_scalar_rng_error_is_none() {
        struct ErrRng;
        impl TryRng for ErrRng {
            type Error = core::fmt::Error;
            fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
                Err(core::fmt::Error)
            }
            fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
                Err(core::fmt::Error)
            }
            fn try_fill_bytes(&mut self, _dst: &mut [u8]) -> Result<(), Self::Error> {
                Err(core::fmt::Error)
            }
        }
        impl TryCryptoRng for ErrRng {}
        assert!(sample_nonzero_scalar(&mut ErrRng).is_none());
    }
}

#[cfg(test)]
mod sign_tests {
    use super::*;
    use core::convert::Infallible;
    use rand_core::{TryCryptoRng, TryRng};

    /// Test-only RNG that always returns the same fixed scalar `k` from
    /// `fill_bytes`. The KAT only depends on the FIRST `fill_bytes` call.
    struct FixedScalarRng {
        k_bytes: [u8; 32],
    }
    impl FixedScalarRng {
        fn new(k_hex: &str) -> Self {
            let k = U256::from_be_hex(k_hex);
            Self {
                k_bytes: k.to_be_bytes().into(),
            }
        }
    }
    impl TryRng for FixedScalarRng {
        type Error = Infallible;

        fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
            Ok(0)
        }

        fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
            Ok(0)
        }

        fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Self::Error> {
            assert_eq!(dst.len(), 32);
            dst.copy_from_slice(&self.k_bytes);
            Ok(())
        }
    }

    impl TryCryptoRng for FixedScalarRng {}

    /// GB/T 32918.2 Appendix A.2 — fixed-k vector.
    /// D = 0x3945208F7B...
    /// k = 0x59276E27D506861A16680F3AD9C02DCFBFBF904F533DA0AC2EE1C9A45B58FF85
    /// Expected r = 0x88348A09A3E324C4FE946843123E40C175468F3E36481885844A144D2167EA4C
    /// Expected s = 0x0AD2CE552FD33EAB792E5A2805E0504D014C96135F8E03891087132ABB24D48D
    /// ID = "ALICE123@YAHOO.COM", message = "message digest"
    #[test]
    fn gbt32918_appendix_a2_fixed_k() {
        let d =
            U256::from_be_hex("3945208F7B2144B13F36E38AC6D39F95889393692860B51A42FB81EF4DF7C5B8");
        let key = Sm2PrivateKey::from_scalar_inner(d).expect("valid scalar");
        let id = b"ALICE123@YAHOO.COM";
        let message = b"message digest";
        let mut rng =
            FixedScalarRng::new("59276E27D506861A16680F3AD9C02DCFBFBF904F533DA0AC2EE1C9A45B58FF85");
        let der = sign_with_id(&key, id, message, &mut rng).expect("sign succeeds");
        let (r, s) = crate::asn1::sig::decode_sig(&der).expect("our own DER decodes");
        assert_eq!(
            r,
            crate::u256_to_be32(&U256::from_be_hex(
                "88348A09A3E324C4FE946843123E40C175468F3E36481885844A144D2167EA4C"
            )),
            "r mismatch"
        );
        assert_eq!(
            s,
            crate::u256_to_be32(&U256::from_be_hex(
                "0AD2CE552FD33EAB792E5A2805E0504D014C96135F8E03891087132ABB24D48D"
            )),
            "s mismatch"
        );
    }
}