ms-pkca 0.1.0-dev

PKINIT (RFC 4556) client — PA-PK-AS-REQ / PA-PK-AS-REP with X.509 cert + UnPAC-the-hash (pre-alpha)
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
//! CMS EnvelopedData (RFC 5652 §6) decrypt for the PA-PK-AS-REP.encKeyPack path.
//!
//! Windows KDCs answer PKINIT AS-REQs in one of two shapes: the DH branch
//! (already fully wired in [`crate::network::process_as_rep`]) or an
//! `encKeyPack` where the KDC wraps a Kerberos [`ReplyKeyPack`] inside a CMS
//! EnvelopedData.  This module implements the client side of the second
//! branch: RSA-unwrap the CEK, AES-CBC-decrypt the content, peel an optional
//! inner SignedData layer, and hand back the Kerberos reply-key bytes.
//!
//! # Scope this ships (0.1.0-dev)
//!
//! * **Outer wrapping**: `ContentInfo(id-envelopedData)`.
//! * **RecipientInfo**: `KeyTransRecipientInfo` (ktri) with `rsaEncryption`
//!   key wrap.  Both `RecipientIdentifier` variants
//!   (`issuerAndSerialNumber` and `subjectKeyIdentifier`) parse; we do not
//!   match the identifier against a cert store — we try each ktri in order
//!   and stop on the first that RSA-unwraps cleanly.  This means a wrong
//!   private key surfaces as [`Error::Rsa`] rather than an identity
//!   mismatch.
//! * **Content encryption**: aes-128-CBC / aes-192-CBC / aes-256-CBC with
//!   PKCS#7 padding.  Algorithm parameters carry the IV as an
//!   `OCTET STRING`.  This is the shape a real Windows KDC emits.
//! * **Plaintext body**: either a raw `ReplyKeyPack` SEQUENCE, or a nested
//!   `ContentInfo(id-signedData)` whose eContent is the `ReplyKeyPack`.
//!   RFC 4556 §3.2.3.2 defines the nested `EnvelopedData(SignedData(rkeyData))`
//!   layering — we detect the outer `ContentInfo` and unwrap it.  KDC
//!   signature verification on the inner `SignedData` is a 0.2 concern; we
//!   trust the eContent for now.
//!
//! # Not supported (yet)
//!
//! * `kari` / `kekri` / `pwri` / `ori` RecipientInfo variants (skipped when
//!   encountered — treated as "not our recipient").
//! * OAEP-wrapped RSA CEKs (`id-RSAES-OAEP`).  Windows still emits PKCS#1
//!   v1.5 by default; add OAEP in 0.2 if a KDC starts advertising it.
//! * `originatorInfo`, `unprotectedAttrs` (parsed as opaque and ignored).
//! * AES-GCM / AES-CCM / RC2 / 3DES content encryption.

use cbc::cipher::{block_padding::Pkcs7, BlockDecryptMut, KeyIvInit};
use rsa::{Pkcs1v15Encrypt, RsaPrivateKey};

use crate::der_walk::{extract_signed_data_econtent, tlv_expect_tag, tlv_split};
use crate::error::{Error, Result};
use crate::oid;

type Aes128CbcDec = cbc::Decryptor<aes::Aes128>;
type Aes192CbcDec = cbc::Decryptor<aes::Aes192>;
type Aes256CbcDec = cbc::Decryptor<aes::Aes256>;

/// Decrypt a CMS `ContentInfo` of type `id-envelopedData` carrying a
/// `ReplyKeyPack`, as produced by the KDC in `PA-PK-AS-REP.encKeyPack`
/// (RFC 4556 §3.2.3.2).
///
/// Returns the extracted `EncryptionKey.keyvalue` — the raw Kerberos
/// reply-key bytes the caller then uses to decrypt the AS-REP enc-part.
///
/// # Errors
/// * [`Error::AsRepParse`] — a DER walk step failed, an unexpected OID
///   appeared, or the ReplyKeyPack shape is wrong.
/// * [`Error::Rsa`] — every candidate `KeyTransRecipientInfo` was present
///   but none unwrapped with the supplied private key.
/// * [`Error::Crypto`] — AES-CBC key/IV validation or padding check failed.
pub fn decrypt_enc_key_pack(content_info: &[u8], client_rsa: &RsaPrivateKey) -> Result<Vec<u8>> {
    let parsed = parse_enveloped(content_info, client_rsa)?;
    if parsed.cek.len() != parsed.expected_cek_len {
        return Err(Error::AsRepParse(format!(
            "unwrapped CEK is {} bytes, content-encryption algorithm expects {}",
            parsed.cek.len(),
            parsed.expected_cek_len
        )));
    }
    let plaintext = decrypt_aes_cbc(&parsed.cek, parsed.iv, parsed.ciphertext)?;
    let reply_key_pack_der = if looks_like_signed_data_contentinfo(&plaintext) {
        extract_signed_data_econtent(&plaintext)?
    } else {
        plaintext
    };
    reply_key_pack_extract_key(&reply_key_pack_der)
}

/// Convenience: the same call, but also returns the parsed Kerberos etype
/// number so the caller doesn't need to re-parse the ReplyKeyPack.
pub fn decrypt_enc_key_pack_full(
    content_info: &[u8],
    client_rsa: &RsaPrivateKey,
) -> Result<ReplyKey> {
    let parsed = parse_enveloped(content_info, client_rsa)?;
    if parsed.cek.len() != parsed.expected_cek_len {
        return Err(Error::AsRepParse(format!(
            "unwrapped CEK is {} bytes, content-encryption algorithm expects {}",
            parsed.cek.len(),
            parsed.expected_cek_len
        )));
    }
    let plaintext = decrypt_aes_cbc(&parsed.cek, parsed.iv, parsed.ciphertext)?;
    let reply_key_pack_der = if looks_like_signed_data_contentinfo(&plaintext) {
        extract_signed_data_econtent(&plaintext)?
    } else {
        plaintext
    };
    reply_key_pack_extract(&reply_key_pack_der)
}

/// The Kerberos reply-key returned by [`decrypt_enc_key_pack_full`].
///
/// `etype` is the Kerberos encryption-type number (e.g. 18 for
/// aes256-cts-hmac-sha1-96) — carried inside `EncryptionKey.keytype`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReplyKey {
    pub etype: i32,
    pub key: Vec<u8>,
}

// ---------------------------------------------------------------------------
// Internals — the layered walk.

struct ParsedEnvelope<'a> {
    cek: Vec<u8>,
    iv: &'a [u8],
    ciphertext: &'a [u8],
    expected_cek_len: usize,
}

fn parse_enveloped<'a>(
    content_info: &'a [u8],
    client_rsa: &RsaPrivateKey,
) -> Result<ParsedEnvelope<'a>> {
    // ContentInfo ::= SEQUENCE { contentType OID, content [0] EXPLICIT ANY }
    let (ci_body, _) = tlv_expect_tag(content_info, 0x30)?;
    let (ct_oid_val, after_ct_oid) = tlv_expect_tag(ci_body, 0x06)?;
    if ct_oid_val != oid::CMS_ENVELOPED_DATA.as_bytes() {
        return Err(Error::AsRepParse(
            "ContentInfo.contentType is not id-envelopedData".into(),
        ));
    }
    let (ctx0_body, _) = tlv_expect_tag(after_ct_oid, 0xA0)?;

    // EnvelopedData ::= SEQUENCE {
    //     version                CMSVersion,
    //     originatorInfo    [0] IMPLICIT OriginatorInfo OPTIONAL,   -- 0xA0 if present
    //     recipientInfos         SET OF RecipientInfo,              -- 0x31
    //     encryptedContentInfo   EncryptedContentInfo,              -- 0x30
    //     unprotectedAttrs  [1] IMPLICIT UnprotectedAttributes OPTIONAL }
    let (ed_body, _) = tlv_expect_tag(ctx0_body, 0x30)?;
    let (_ver, cursor_after_ver) = tlv_split(ed_body)?;
    let mut cursor = cursor_after_ver;
    if cursor.first().copied() == Some(0xA0) {
        // originatorInfo present but not modeled — skip whole TLV.
        let (_orig, rest) = tlv_split(cursor)?;
        cursor = rest;
    }
    let (ris_body, after_ris) = tlv_expect_tag(cursor, 0x31)?;
    let cek = unwrap_cek_from_recipient_infos(ris_body, client_rsa)?;

    // EncryptedContentInfo ::= SEQUENCE {
    //     contentType                 ContentType,             -- OID
    //     contentEncryptionAlgorithm  AlgorithmIdentifier,     -- SEQUENCE
    //     encryptedContent       [0] IMPLICIT OCTET STRING OPTIONAL }  -- 0x80
    let (eci_body, _) = tlv_expect_tag(after_ris, 0x30)?;
    let (_ec_type, after_ec_type) = tlv_expect_tag(eci_body, 0x06)?;
    let (alg_body, after_alg) = tlv_expect_tag(after_ec_type, 0x30)?;
    let (alg_oid, after_alg_oid) = tlv_expect_tag(alg_body, 0x06)?;
    // AES-CBC parameters ::= OCTET STRING (SIZE(16))  -- the IV
    let (iv_body, _) = tlv_expect_tag(after_alg_oid, 0x04)?;
    // encryptedContent is IMPLICIT [0] OCTET STRING → primitive context [0] = 0x80
    let (ct_body, _) = tlv_expect_tag(after_alg, 0x80)?;
    let expected_cek_len = match_aes_cbc_key_len(alg_oid)?;

    Ok(ParsedEnvelope {
        cek,
        iv: iv_body,
        ciphertext: ct_body,
        expected_cek_len,
    })
}

fn unwrap_cek_from_recipient_infos(ris: &[u8], client_rsa: &RsaPrivateKey) -> Result<Vec<u8>> {
    // RecipientInfo ::= CHOICE {
    //     ktri            KeyTransRecipientInfo,                -- SEQUENCE, tag 0x30
    //     kari       [1]  KeyAgreeRecipientInfo,                -- 0xA1
    //     kekri      [2]  KEKRecipientInfo,                     -- 0xA2
    //     pwri       [3]  PasswordRecipientInfo,                -- 0xA3
    //     ori        [4]  OtherRecipientInfo }                  -- 0xA4
    //
    // We only wire ktri.  Other variants get skipped as "not our recipient".
    // If none of the ktri entries unwrap with our RSA key, surface the last
    // RSA error so the caller can distinguish "wrong key" from "no ktri".
    let mut cursor = ris;
    let mut last_err: Option<Error> = None;
    while !cursor.is_empty() {
        let first = cursor[0];
        let (ri_body, rest) = tlv_split(cursor)?;
        cursor = rest;
        if first != 0x30 {
            continue;
        }
        // KeyTransRecipientInfo ::= SEQUENCE {
        //     version         CMSVersion,                       -- INTEGER
        //     rid             RecipientIdentifier,
        //     keyEncryptionAlgorithm AlgorithmIdentifier,
        //     encryptedKey    OCTET STRING }
        let (_ver, after_ver) = tlv_split(ri_body)?;
        // rid: SEQUENCE (issuerAndSerialNumber) OR [0] IMPLICIT OCTET STRING (SKI).
        // We accept either shape and don't match against a cert here.
        let (_rid, after_rid) = tlv_split(after_ver)?;
        let (kea_body, after_kea) = tlv_expect_tag(after_rid, 0x30)?;
        let (kea_oid, _) = tlv_expect_tag(kea_body, 0x06)?;
        if kea_oid != oid::RSA_ENCRYPTION.as_bytes() {
            // OAEP or something else — skip this recipient.
            continue;
        }
        let (ek_body, _) = tlv_expect_tag(after_kea, 0x04)?;
        match client_rsa.decrypt(Pkcs1v15Encrypt, ek_body) {
            Ok(cek) => return Ok(cek),
            Err(e) => {
                last_err = Some(Error::Rsa(format!("encryptedKey RSA-unwrap: {e}")));
            }
        }
    }
    Err(last_err.unwrap_or_else(|| {
        Error::AsRepParse(
            "no compatible KeyTransRecipientInfo (rsaEncryption) in EnvelopedData".into(),
        )
    }))
}

fn match_aes_cbc_key_len(oid_bytes: &[u8]) -> Result<usize> {
    if oid_bytes == oid::AES256_CBC.as_bytes() {
        Ok(32)
    } else if oid_bytes == oid::AES192_CBC.as_bytes() {
        Ok(24)
    } else if oid_bytes == oid::AES128_CBC.as_bytes() {
        Ok(16)
    } else {
        Err(Error::AsRepParse(
            "unsupported content-encryption OID (want aes{128,192,256}-CBC)".into(),
        ))
    }
}

fn decrypt_aes_cbc(key: &[u8], iv: &[u8], ct: &[u8]) -> Result<Vec<u8>> {
    if iv.len() != 16 {
        return Err(Error::Crypto(format!(
            "AES-CBC IV len {} (expected 16)",
            iv.len()
        )));
    }
    // Ciphertext must be a positive multiple of the AES block size; if it
    // isn't, the RustCrypto call would fail internally — surface that as
    // a clear structural error.
    if ct.is_empty() || ct.len() % 16 != 0 {
        return Err(Error::Crypto(format!(
            "AES-CBC ciphertext len {} is not a positive multiple of 16",
            ct.len()
        )));
    }
    match key.len() {
        16 => Aes128CbcDec::new_from_slices(key, iv)
            .map_err(|e| Error::Crypto(format!("aes-128-cbc init: {e}")))?
            .decrypt_padded_vec_mut::<Pkcs7>(ct)
            .map_err(|e| Error::Crypto(format!("aes-128-cbc decrypt: {e}"))),
        24 => Aes192CbcDec::new_from_slices(key, iv)
            .map_err(|e| Error::Crypto(format!("aes-192-cbc init: {e}")))?
            .decrypt_padded_vec_mut::<Pkcs7>(ct)
            .map_err(|e| Error::Crypto(format!("aes-192-cbc decrypt: {e}"))),
        32 => Aes256CbcDec::new_from_slices(key, iv)
            .map_err(|e| Error::Crypto(format!("aes-256-cbc init: {e}")))?
            .decrypt_padded_vec_mut::<Pkcs7>(ct)
            .map_err(|e| Error::Crypto(format!("aes-256-cbc decrypt: {e}"))),
        n => Err(Error::Crypto(format!("unsupported AES key len {n}"))),
    }
}

fn looks_like_signed_data_contentinfo(bytes: &[u8]) -> bool {
    // Peek: `SEQUENCE { OID id-signedData, [0] EXPLICIT ... }`.  A raw
    // ReplyKeyPack is a SEQUENCE whose first field is a [0] EXPLICIT
    // EncryptionKey (0xA0), never an OID (0x06) — so the two shapes are
    // trivially distinguishable at the second TLV.
    let Ok((body, _)) = tlv_expect_tag(bytes, 0x30) else {
        return false;
    };
    let Ok((oid_val, _)) = tlv_expect_tag(body, 0x06) else {
        return false;
    };
    oid_val == oid::CMS_SIGNED_DATA.as_bytes()
}

/// Parse `ReplyKeyPack` → `EncryptionKey.keyvalue` (Kerberos reply-key bytes).
///
/// ```text
/// ReplyKeyPack ::= SEQUENCE {
///     replyKey    [0] EncryptionKey,
///     asChecksum  [1] Checksum
/// }
/// EncryptionKey ::= SEQUENCE {
///     keytype     [0] Int32,
///     keyvalue    [1] OCTET STRING
/// }
/// ```
fn reply_key_pack_extract_key(bytes: &[u8]) -> Result<Vec<u8>> {
    Ok(reply_key_pack_extract(bytes)?.key)
}

/// Same as [`reply_key_pack_extract_key`] but also returns the keytype (etype).
fn reply_key_pack_extract(bytes: &[u8]) -> Result<ReplyKey> {
    let (rkp_body, _) = tlv_expect_tag(bytes, 0x30)?;
    // [0] EXPLICIT SEQUENCE(EncryptionKey)
    let (rk_ctx_body, _) = tlv_expect_tag(rkp_body, 0xA0)?;
    let (ek_body, _) = tlv_expect_tag(rk_ctx_body, 0x30)?;

    // Iterate EncryptionKey fields; carry along keytype + keyvalue as we
    // find their explicit-tag wrappers.  Kerberos uses EXPLICIT context tags
    // by default (no `AUTOMATIC TAGS` in the RFC 4556 module).
    let mut cursor = ek_body;
    let mut keytype: Option<i32> = None;
    let mut keyvalue: Option<Vec<u8>> = None;
    while !cursor.is_empty() {
        let first = cursor[0];
        let (field_body, rest) = tlv_split(cursor)?;
        match first {
            0xA0 => {
                // [0] EXPLICIT INTEGER
                let (int_body, _) = tlv_expect_tag(field_body, 0x02)?;
                keytype = Some(decode_der_int_i32(int_body)?);
            }
            0xA1 => {
                // [1] EXPLICIT OCTET STRING
                let (kv_body, _) = tlv_expect_tag(field_body, 0x04)?;
                keyvalue = Some(kv_body.to_vec());
            }
            _ => {
                // Unknown / future field — ignore.
            }
        }
        cursor = rest;
    }

    let key = keyvalue
        .ok_or_else(|| Error::AsRepParse("ReplyKeyPack.replyKey has no [1] keyvalue".into()))?;
    let etype = keytype
        .ok_or_else(|| Error::AsRepParse("ReplyKeyPack.replyKey has no [0] keytype".into()))?;
    Ok(ReplyKey { etype, key })
}

/// Decode a DER INTEGER value (two's-complement, big-endian) as i32.
///
/// Kerberos etypes fit comfortably in a small i32 (values like 17, 18, 23),
/// so we cap the width here — anything longer is a structural error.
fn decode_der_int_i32(bytes: &[u8]) -> Result<i32> {
    if bytes.is_empty() {
        return Err(Error::AsRepParse("INTEGER: zero-length value".into()));
    }
    if bytes.len() > 5 {
        return Err(Error::AsRepParse(format!(
            "INTEGER too wide for i32 ({} bytes)",
            bytes.len()
        )));
    }
    // Sign-extend from the MSB of the first byte.
    let mut acc: i32 = if bytes[0] & 0x80 != 0 { -1 } else { 0 };
    for &b in bytes {
        acc = (acc.wrapping_shl(8)) | (b as i32 & 0xFF);
    }
    Ok(acc)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn match_aes_cbc_key_len_covers_all_three_sizes() {
        assert_eq!(
            match_aes_cbc_key_len(oid::AES128_CBC.as_bytes()).unwrap(),
            16
        );
        assert_eq!(
            match_aes_cbc_key_len(oid::AES192_CBC.as_bytes()).unwrap(),
            24
        );
        assert_eq!(
            match_aes_cbc_key_len(oid::AES256_CBC.as_bytes()).unwrap(),
            32
        );
        // Bogus OID (id-data) rejected.
        assert!(match_aes_cbc_key_len(oid::CMS_DATA.as_bytes()).is_err());
    }

    #[test]
    fn decode_der_int_handles_edge_values() {
        assert_eq!(decode_der_int_i32(&[0x00]).unwrap(), 0);
        assert_eq!(decode_der_int_i32(&[0x12]).unwrap(), 18);
        assert_eq!(decode_der_int_i32(&[0x17]).unwrap(), 23);
        // Negative: 0xFF = -1
        assert_eq!(decode_der_int_i32(&[0xFF]).unwrap(), -1);
        // DER positive with leading 00 pad: 00 80 = 128
        assert_eq!(decode_der_int_i32(&[0x00, 0x80]).unwrap(), 128);
        // Reject wrong-length inputs.
        assert!(decode_der_int_i32(&[]).is_err());
        assert!(decode_der_int_i32(&[0; 6]).is_err());
    }

    #[test]
    fn reply_key_pack_roundtrip_extracts_key_and_etype() {
        // Hand-build ReplyKeyPack DER:
        //   SEQUENCE {
        //     [0] EXPLICIT SEQUENCE {                -- EncryptionKey
        //       [0] EXPLICIT INTEGER 18,             -- keytype = aes256
        //       [1] EXPLICIT OCTET STRING <32 bytes> -- keyvalue
        //     },
        //     [1] EXPLICIT SEQUENCE {                -- asChecksum
        //       [0] EXPLICIT INTEGER 16,             -- cksumtype
        //       [1] EXPLICIT OCTET STRING <4 bytes>  -- checksum
        //     }
        //   }
        let keyvalue = [0xAAu8; 32];
        let cksum = [0x11u8, 0x22, 0x33, 0x44];

        let ek_inner = concat_der(&[
            explicit_tag(0, &[0x02, 0x01, 18]),
            explicit_tag(1, &wrap_tag(0x04, &keyvalue)),
        ]);
        let ek = wrap_tag(0x30, &ek_inner);

        let cksum_inner = concat_der(&[
            explicit_tag(0, &[0x02, 0x01, 16]),
            explicit_tag(1, &wrap_tag(0x04, &cksum)),
        ]);
        let cksum_seq = wrap_tag(0x30, &cksum_inner);

        let rkp_inner = concat_der(&[explicit_tag(0, &ek), explicit_tag(1, &cksum_seq)]);
        let rkp = wrap_tag(0x30, &rkp_inner);

        let out = reply_key_pack_extract(&rkp).unwrap();
        assert_eq!(out.etype, 18);
        assert_eq!(out.key, keyvalue.to_vec());
    }

    #[test]
    fn looks_like_signed_data_distinguishes_shapes() {
        // A raw ReplyKeyPack starts with SEQUENCE { [0] ... }, so its second
        // TLV tag byte is 0xA0, not 0x06.  A ContentInfo(id-signedData)
        // starts with SEQUENCE { OID 1.2.840.113549.1.7.2, ... }.
        let raw_rkp = wrap_tag(0x30, &explicit_tag(0, &[0x30, 0x00]));
        assert!(!looks_like_signed_data_contentinfo(&raw_rkp));

        let signed_ci_body = concat_der(&[
            wrap_tag(0x06, oid::CMS_SIGNED_DATA.as_bytes()),
            explicit_tag(0, &[0x30, 0x00]),
        ]);
        let signed_ci = wrap_tag(0x30, &signed_ci_body);
        assert!(looks_like_signed_data_contentinfo(&signed_ci));
    }

    // -- tiny DER building blocks for the unit tests above --

    fn concat_der(parts: &[Vec<u8>]) -> Vec<u8> {
        let mut out = Vec::new();
        for p in parts {
            out.extend_from_slice(p);
        }
        out
    }

    fn wrap_tag(tag: u8, body: &[u8]) -> Vec<u8> {
        let mut out = vec![tag];
        encode_len_into(&mut out, body.len());
        out.extend_from_slice(body);
        out
    }

    fn explicit_tag(tag_number: u8, body: &[u8]) -> Vec<u8> {
        // Constructed context-specific [N]: tag = 0xA0 | N
        wrap_tag(0xA0 | tag_number, body)
    }

    fn encode_len_into(dst: &mut Vec<u8>, len: usize) {
        if len < 0x80 {
            dst.push(len as u8);
        } else if len < 0x100 {
            dst.push(0x81);
            dst.push(len as u8);
        } else if len < 0x10000 {
            dst.push(0x82);
            dst.push((len >> 8) as u8);
            dst.push(len as u8);
        } else {
            panic!("test helper: unsupported len {len}");
        }
    }
}