ja4 0.1.0

A fast, pure-rust, no_std implementation of the JA4 TLS client fingerprinting algorithm.
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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
#![no_std]
#![forbid(unsafe_code)]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![warn(missing_debug_implementations, missing_docs, rust_2018_idioms)]

//! # ja4
//!
//! A high-performance, production-ready, `#![no_std]` Rust implementation of the JA4 TLS fingerprinting algorithm.
//!
//! JA4 is a standard for TLS client fingerprinting, providing a modular and human-readable representation
//! of client hello characteristics. Unlike JA3, JA4 is designed to normalize GREASE values, sort extensions,
//! and present the output in three distinct, readable sections:
//!
//! - **a**: Connection details (Protocol, TLS version, SNI presence, Cipher count, Extension count, ALPN)
//! - **b**: A truncated hash of the sorted list of cipher suites
//! - **c**: A truncated hash of the sorted list of extensions and signature algorithms
//!
//! ## Example
//!
//! ```rust
//! use ja4::parse_ja4;
//!
//! // Raw TLS ClientHello packet bytes (including TLS record header)
//! let client_hello_packet: &[u8] = &[
//!     0x16, 0x03, 0x01, 0x00, 0x2d, // TLS Record Header (Handshake, TLS 1.0, 45 bytes)
//!     0x01, 0x00, 0x00, 0x29,       // Handshake Header (ClientHello, 41 bytes)
//!     0x03, 0x03,                   // Client Version (TLS 1.2)
//!     // ... remaining packet bytes ...
//! #   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
//! #   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
//! #   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
//! #   0x00, 0x2f, 0x00, 0x00
//! ];
//!
//! // Parse TCP-based TLS ClientHello packet
//! if let Some(result) = parse_ja4(client_hello_packet, false) {
//!     println!("JA4 Fingerprint: {}", result);
//! }
//! ```

use sha2::{Digest, Sha256};

/// Helper to check if a 16-bit value is a TLS GREASE (Generate Random Extensions
/// And Sustain Extensibility) value.
///
/// GREASE values are specified in RFC 8701 as:
/// 0x0A0A, 0x1A1A, 0x2A2A, 0x3A3A, 0x4A4A, 0x5A5A, 0x6A6A, 0x7A7A,
/// 0x8A8A, 0x9A9A, 0xAAAA, 0xBABA, 0xCACA, 0xDADA, 0xEAEA, 0xFAFA.
#[inline(always)]
fn is_grease(val: u16) -> bool {
    (val & 0x0F0F) == 0x0A0A && ((val >> 8) == (val & 0xFF))
}

/// Helper function to format a `u16` value into a lowercase hex string (4 characters)
/// directly into a buffer slice.
#[inline(always)]
fn write_u16_hex(val: u16, buf: &mut [u8]) {
    const HEX_CHARS: &[u8; 16] = b"0123456789abcdef";
    buf[0] = HEX_CHARS[((val >> 12) & 0xF) as usize];
    buf[1] = HEX_CHARS[((val >> 8) & 0xF) as usize];
    buf[2] = HEX_CHARS[((val >> 4) & 0xF) as usize];
    buf[3] = HEX_CHARS[(val & 0xF) as usize];
}

/// Helper to read a single byte from a sliding slice, advancing it.
#[inline(always)]
fn read_u8(data: &mut &[u8]) -> Option<u8> {
    let (&first, rest) = data.split_first()?;
    *data = rest;
    Some(first)
}

/// Helper to read a big-endian u16 from a sliding slice, advancing it by 2 bytes.
#[inline(always)]
fn read_u16(data: &mut &[u8]) -> Option<u16> {
    if data.len() < 2 {
        return None;
    }
    let val = u16::from_be_bytes([data[0], data[1]]);
    *data = &data[2..];
    Some(val)
}

/// Helper to read/slice a specified number of bytes from a sliding slice, advancing it.
#[inline(always)]
fn read_slice<'a>(data: &mut &'a [u8], len: usize) -> Option<&'a [u8]> {
    if data.len() < len {
        return None;
    }
    let (left, right) = data.split_at(len);
    *data = right;
    Some(left)
}

/// The result of a successfully parsed and calculated JA4 TLS fingerprint.
///
/// Holds the 36-character ASCII representation of the JA4 fingerprint, which
/// is partitioned as `a_b_c`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Ja4Result {
    /// The 36-character ASCII representation of the JA4 fingerprint.
    pub fingerprint: [u8; 36],
}

impl Ja4Result {
    /// Returns the JA4 fingerprint as a static string slice.
    #[inline]
    pub fn as_str(&self) -> &str {
        // Safe to unwrap because we construct it using valid ASCII characters only.
        core::str::from_utf8(&self.fingerprint).unwrap_or("0000000000_000000000000_000000000000")
    }
}

impl core::fmt::Display for Ja4Result {
    /// Formats and writes the JA4 fingerprint string to the formatter.
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Parses a raw TLS ClientHello packet (including the 5-byte TLS record header for TCP)
/// and calculates the JA4 fingerprint.
///
/// # Arguments
/// * `packet` - A byte slice containing the TLS packet.
/// * `is_quic` - A boolean flag specifying whether the payload is from QUIC (no TLS record header)
///   or standard TCP (starts with a 5-byte TLS record header).
///
/// # Returns
/// * `Some(Ja4Result)` if parsing succeeds and a valid fingerprint is calculated.
/// * `None` if the packet is malformed, truncated, or is not a ClientHello message.
pub fn parse_ja4(packet: &[u8], is_quic: bool) -> Option<Ja4Result> {
    let mut data = packet;

    // If it's TCP TLS, it starts with a TLS Record header
    if !is_quic {
        let record_type = read_u8(&mut data)?;
        if record_type != 0x16 {
            return None;
        } // Not a handshake record
        
        let _record_version = read_u16(&mut data)?;
        let record_len = read_u16(&mut data)? as usize;
        
        // Constrain data to only the record payload length
        if data.len() < record_len {
            return None;
        }
        data = &data[..record_len];
    }

    // Read Handshake Message Type
    let msg_type = read_u8(&mut data)?;
    if msg_type != 0x01 {
        return None;
    } // Not a ClientHello

    // Read Handshake Message Length (3 bytes)
    if data.len() < 3 {
        return None;
    }
    let msg_len = ((data[0] as usize) << 16)
        | ((data[1] as usize) << 8)
        | (data[2] as usize);
    data = &data[3..];

    // Constrain data to exactly the handshake message bounds
    if data.len() < msg_len {
        return None;
    }
    data = &data[..msg_len];

    // Read Client Version (2 bytes)
    let client_version = read_u16(&mut data)?;

    // Skip Random Bytes (32 bytes)
    read_slice(&mut data, 32)?;

    // Skip Session ID (variable length, prefixed by 1 byte length)
    let session_id_len = read_u8(&mut data)? as usize;
    read_slice(&mut data, session_id_len)?;

    // Read Cipher Suites (variable length, prefixed by 2 bytes length)
    let ciphers_len = read_u16(&mut data)? as usize;
    if !ciphers_len.is_multiple_of(2) {
        return None;
    }
    let mut ciphers_data = read_slice(&mut data, ciphers_len)?;

    let mut ciphers = [0u16; 128];
    let mut ciphers_count = 0;
    while !ciphers_data.is_empty() {
        let cipher = read_u16(&mut ciphers_data)?;
        if !is_grease(cipher) && ciphers_count < 128 {
            ciphers[ciphers_count] = cipher;
            ciphers_count += 1;
        }
    }

    // Skip Compression Methods (variable length, prefixed by 1 byte length)
    let comp_len = read_u8(&mut data)? as usize;
    read_slice(&mut data, comp_len)?;

    let mut extensions = [0u16; 128];
    let mut extensions_count = 0;
    let mut total_ext_count = 0;
    let mut has_sni = false;
    let mut alpn = *b"00";

    let mut sig_algs = [0u16; 128];
    let mut sig_algs_count = 0;

    let mut highest_supported_version = None;

    // Parse Extensions (if present)
    if !data.is_empty() {
        if data.len() < 2 {
            return None;
        }
        let ext_total_len = read_u16(&mut data)? as usize;
        if data.len() < ext_total_len {
            return None;
        }
        let mut ext_data = &data[..ext_total_len];

        while !ext_data.is_empty() {
            let ext_type = read_u16(&mut ext_data)?;
            let ext_len = read_u16(&mut ext_data)? as usize;
            let mut ext_payload = read_slice(&mut ext_data, ext_len)?;

            if !is_grease(ext_type) {
                total_ext_count += 1;

                if ext_type == 0x0000 {
                    has_sni = true;
                } else if ext_type == 0x0010 {
                    // Parse ALPN extension
                    if ext_payload.len() >= 2 {
                        let alpn_list_len = read_u16(&mut ext_payload)? as usize;
                        if ext_payload.len() >= alpn_list_len && alpn_list_len > 0 {
                            let mut alpn_payload = &ext_payload[..alpn_list_len];
                            if !alpn_payload.is_empty() {
                                let first_alpn_len = read_u8(&mut alpn_payload)? as usize;
                                if alpn_payload.len() >= first_alpn_len && first_alpn_len > 0 {
                                    let first_alpn = &alpn_payload[..first_alpn_len];
                                    let first_byte = first_alpn[0];
                                    let last_byte = first_alpn[first_alpn_len - 1];

                                    if first_byte.is_ascii_alphanumeric() && last_byte.is_ascii_alphanumeric() {
                                        // Standard case: extract first and last alphanumeric characters
                                        let mut first_char = 0;
                                        let mut last_char = 0;
                                        let mut char_count = 0;
                                        for &b in first_alpn {
                                            if b.is_ascii_alphanumeric() {
                                                char_count += 1;
                                                if char_count == 1 {
                                                    first_char = b;
                                                }
                                                last_char = b;
                                            }
                                        }
                                        if char_count > 0 {
                                            if char_count == 1 {
                                                alpn[0] = first_char.to_ascii_lowercase();
                                                alpn[1] = b'0';
                                            } else {
                                                alpn[0] = first_char.to_ascii_lowercase();
                                                alpn[1] = last_char.to_ascii_lowercase();
                                            }
                                        }
                                    } else {
                                        // Hex fallback case for non-alphanumeric ALPN bytes
                                        const HEX_CHARS: &[u8; 16] = b"0123456789abcdef";
                                        
                                        let f_char = if first_byte.is_ascii_alphanumeric() {
                                            first_byte.to_ascii_lowercase()
                                        } else {
                                            HEX_CHARS[((first_byte >> 4) & 0xF) as usize]
                                        };
                                        
                                        let l_char = if last_byte.is_ascii_alphanumeric() {
                                            last_byte.to_ascii_lowercase()
                                        } else {
                                            HEX_CHARS[(last_byte & 0xF) as usize]
                                        };
                                        
                                        alpn[0] = f_char;
                                        alpn[1] = l_char;
                                    }
                                }
                            }
                        }
                    }
                } else if ext_type == 0x000d {
                    // Parse Signature Algorithms extension
                    if ext_payload.len() >= 2 {
                        let sig_list_len = read_u16(&mut ext_payload)? as usize;
                        if ext_payload.len() >= sig_list_len && sig_list_len > 0 {
                            let mut sig_payload = &ext_payload[..sig_list_len];
                            while !sig_payload.is_empty() && sig_algs_count < 128 {
                                let sig = read_u16(&mut sig_payload)?;
                                sig_algs[sig_algs_count] = sig;
                                sig_algs_count += 1;
                            }
                        }
                    }
                } else if ext_type == 0x002b {
                    // Parse Supported Versions extension
                    if !ext_payload.is_empty() {
                        let ver_list_len = read_u8(&mut ext_payload)? as usize;
                        if ext_payload.len() >= ver_list_len && ver_list_len > 0 {
                            let mut ver_payload = &ext_payload[..ver_list_len];
                            while !ver_payload.is_empty() {
                                let ver = read_u16(&mut ver_payload)?;
                                if !is_grease(ver) {
                                    match highest_supported_version {
                                        None => highest_supported_version = Some(ver),
                                        Some(highest) if ver > highest => highest_supported_version = Some(ver),
                                        _ => {}
                                    }
                                }
                            }
                        }
                    }
                }

                if ext_type != 0x0000 && ext_type != 0x0010 && extensions_count < 128 {
                    extensions[extensions_count] = ext_type;
                    extensions_count += 1;
                }
            }
        }
    }

    // Sort ciphers
    let ciphers_slice = &mut ciphers[..ciphers_count];
    ciphers_slice.sort_unstable();

    // Sort extensions
    let extensions_slice = &mut extensions[..extensions_count];
    extensions_slice.sort_unstable();

    let protocol = if is_quic { b'q' } else { b't' };

    // Determine the TLS version string for JA4
    let chosen_version = highest_supported_version.unwrap_or(client_version);
    let version_bytes = match chosen_version {
        0x0304 => b"13",
        0x0303 => b"12",
        0x0302 => b"11",
        0x0301 => b"10",
        0x0300 => b"s3",
        0x0200 => b"s2",
        0x0100 => b"s1",
        0x0002 => b"s2",
        _ => b"00",
    };

    let sni = if has_sni { b'd' } else { b'i' };

    let mut fp = [0u8; 36];

    // Part a: 10 chars (Protocol, TLS version, SNI, Cipher count, Extension count, ALPN)
    fp[0] = protocol;
    fp[1] = version_bytes[0];
    fp[2] = version_bytes[1];
    fp[3] = sni;

    let cc = ciphers_count.min(99);
    fp[4] = b'0' + (cc / 10) as u8;
    fp[5] = b'0' + (cc % 10) as u8;

    let ec = total_ext_count.min(99);
    fp[6] = b'0' + (ec / 10) as u8;
    fp[7] = b'0' + (ec % 10) as u8;

    fp[8] = alpn[0];
    fp[9] = alpn[1];

    fp[10] = b'_';

    // Part b: 12 chars (first 12 hex characters of SHA-256 hash of sorted ciphers list)
    if ciphers_count == 0 {
        fp[11..23].copy_from_slice(b"000000000000");
    } else {
        let mut hasher = Sha256::new();
        for (i, &c) in ciphers_slice.iter().enumerate() {
            if i > 0 {
                hasher.update(b",");
            }
            let mut hex = [0u8; 4];
            write_u16_hex(c, &mut hex);
            hasher.update(&hex);
        }
        let hash = hasher.finalize();
        let hex_chars = b"0123456789abcdef";
        for i in 0..6 {
            let b = hash[i];
            fp[11 + i * 2] = hex_chars[(b >> 4) as usize];
            fp[11 + i * 2 + 1] = hex_chars[(b & 0x0F) as usize];
        }
    }

    fp[23] = b'_';

    // Part c: 12 chars (first 12 hex characters of SHA-256 hash of sorted extensions + sorted signature algorithms)
    if extensions_count == 0 && sig_algs_count == 0 {
        fp[24..36].copy_from_slice(b"000000000000");
    } else {
        let mut hasher = Sha256::new();
        if extensions_count > 0 {
            for (i, &e) in extensions_slice.iter().enumerate() {
                if i > 0 {
                    hasher.update(b",");
                }
                let mut hex = [0u8; 4];
                write_u16_hex(e, &mut hex);
                hasher.update(&hex);
            }
        }
        if extensions_count > 0 && sig_algs_count > 0 {
            hasher.update(b"_");
        }
        if sig_algs_count > 0 {
            for (i, &s) in sig_algs[..sig_algs_count].iter().enumerate() {
                if i > 0 {
                    hasher.update(b",");
                }
                let mut hex = [0u8; 4];
                write_u16_hex(s, &mut hex);
                hasher.update(&hex);
            }
        }
        let hash = hasher.finalize();

        let hex_chars = b"0123456789abcdef";
        for i in 0..6 {
            let b = hash[i];
            fp[24 + i * 2] = hex_chars[(b >> 4) as usize];
            fp[24 + i * 2 + 1] = hex_chars[(b & 0x0F) as usize];
        }
    }

    Some(Ja4Result { fingerprint: fp })
}

#[cfg(test)]
mod tests {
    extern crate std;
    use std::prelude::v1::*;
    use super::*;

    #[test]
    fn test_is_grease() {
        assert!(is_grease(0x0A0A));
        assert!(is_grease(0x1A1A));
        assert!(is_grease(0x3A3A));
        assert!(is_grease(0xFAFA));
        assert!(!is_grease(0x0A0B));
        assert!(!is_grease(0x1111));
    }

    #[test]
    fn test_write_u16_hex() {
        let mut buf = [0u8; 4];
        write_u16_hex(0x1a2f, &mut buf);
        assert_eq!(&buf, b"1a2f");

        write_u16_hex(0x0000, &mut buf);
        assert_eq!(&buf, b"0000");

        write_u16_hex(0xffff, &mut buf);
        assert_eq!(&buf, b"ffff");
    }

    #[test]
    fn test_empty_or_too_short_packet() {
        assert!(parse_ja4(&[], false).is_none());
        assert!(parse_ja4(&[0x16], false).is_none());
        assert!(parse_ja4(&[0x16, 0x03, 0x01, 0x00], false).is_none());
    }

    #[test]
    fn test_minimal_valid_handshake() {
        // Construct a synthetic minimal TCP ClientHello packet
        let mut packet = vec![
            0x16, 0x03, 0x01, 0x00, 0x2f, // Record header (Handshake, TLS 1.0, 47 bytes)
            0x01, 0x00, 0x00, 0x2b,       // Handshake header (ClientHello, 43 bytes)
            0x03, 0x03,                   // version TLS 1.2 (0x0303)
        ];
        // 32 bytes of random
        packet.extend_from_slice(&[0u8; 32]);
        // Session ID length (0)
        packet.push(0x00);
        // Cipher suites length (2 bytes, 1 cipher suite: TLS_AES_128_GCM_SHA256 = 0x1301)
        packet.extend_from_slice(&[0x00, 0x02, 0x13, 0x01]);
        // Compression methods length (1 byte, 1 method: null = 0x00)
        packet.extend_from_slice(&[0x01, 0x00]);
        // Extensions length (0)
        packet.extend_from_slice(&[0x00, 0x00]);

        let res = parse_ja4(&packet, false).expect("Parsing should succeed");
        let fp_str = res.as_str();

        // Protocol: t
        // Version: 12 (0x0303)
        // SNI: i (no SNI extension)
        // Cipher suites count: 01
        // Extensions count: 00
        // ALPN: 00
        // Expected part 'a': t12i010000
        assert!(fp_str.starts_with("t12i010000_"));
        assert_eq!(fp_str.len(), 36);
        assert_eq!(res.to_string(), fp_str);
    }

    #[test]
    fn test_quic_handshake() {
        // Construct a synthetic minimal QUIC ClientHello packet (no record header)
        let mut packet = vec![
            0x01, 0x00, 0x00, 0x2b,       // Handshake header (ClientHello, 43 bytes)
            0x03, 0x03,                   // version TLS 1.2 (0x0303)
        ];
        // 32 bytes of random
        packet.extend_from_slice(&[0u8; 32]);
        // Session ID length (0)
        packet.push(0x00);
        // Cipher suites length (2 bytes, 1 cipher suite: TLS_AES_128_GCM_SHA256 = 0x1301)
        packet.extend_from_slice(&[0x00, 0x02, 0x13, 0x01]);
        // Compression methods length (1 byte, 1 method: null = 0x00)
        packet.extend_from_slice(&[0x01, 0x00]);
        // Extensions length (0)
        packet.extend_from_slice(&[0x00, 0x00]);

        let res = parse_ja4(&packet, true).expect("Parsing QUIC should succeed");
        let fp_str = res.as_str();

        // Protocol: q
        // Version: 12 (0x0303)
        // SNI: i
        // Cipher count: 01
        // Extension count: 00
        // ALPN: 00
        assert!(fp_str.starts_with("q12i010000_"));
    }

    #[test]
    fn test_handshake_with_extensions() {
        // Build a synthetic ClientHello packet with extensions (SNI, ALPN, Signature Algorithms, Supported Versions)
        let mut handshake = vec![
            0x03, 0x03,                   // version TLS 1.2
        ];
        // 32 bytes random
        handshake.extend_from_slice(&[0u8; 32]);
        // Session ID length (0)
        handshake.push(0x00);
        // Cipher suites length (2 bytes, 1 cipher suite: TLS_AES_128_GCM_SHA256 = 0x1301)
        handshake.extend_from_slice(&[0x00, 0x02, 0x13, 0x01]);
        // Compression methods length (1 byte, 1 method: null = 0x00)
        handshake.extend_from_slice(&[0x01, 0x00]);

        // Extensions payload
        let mut extensions_payload = Vec::new();

        // 1. SNI Extension (type 0x0000)
        // len is 0 for our minimal mock parsing, since parse_ja4 checks presence by type
        extensions_payload.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]);

        // 2. ALPN Extension (type 0x0010)
        // format: extension_type (2 bytes), extension_len (2 bytes), alpn_list_len (2 bytes), alpn_len (1 byte), "h2" (2 bytes)
        // extension_len is 2 + 1 + 2 = 5
        extensions_payload.extend_from_slice(&[0x00, 0x10,  0x00, 0x05,  0x00, 0x03,  0x02, b'h', b'2']);

        // 3. Signature Algorithms Extension (type 0x000d)
        // format: extension_type (2 bytes), extension_len (2 bytes), sig_list_len (2 bytes), sig1 (2 bytes), sig2 (2 bytes)
        // extension_len is 2 + 4 = 6
        extensions_payload.extend_from_slice(&[0x00, 0x0d,  0x00, 0x06,  0x00, 0x04,  0x04, 0x03,  0x08, 0x04]);

        // 4. Supported Versions Extension (type 0x002b)
        // format: extension_type (2 bytes), extension_len (2 bytes), ver_list_len (1 byte), ver1 (2 bytes)
        // extension_len is 1 + 2 = 3
        // ver1 is TLS 1.3 (0x0304)
        extensions_payload.extend_from_slice(&[0x00, 0x2b,  0x00, 0x03,  0x02,  0x03, 0x04]);

        let ext_len = extensions_payload.len();
        handshake.extend_from_slice(&(ext_len as u16).to_be_bytes());
        handshake.extend_from_slice(&extensions_payload);

        // Prepend handshake header
        let mut packet = vec![
            0x01, // ClientHello
            ((handshake.len() >> 16) & 0xFF) as u8,
            ((handshake.len() >> 8) & 0xFF) as u8,
            (handshake.len() & 0xFF) as u8,
        ];
        packet.extend_from_slice(&handshake);

        let res = parse_ja4(&packet, true).expect("Parsing with extensions should succeed");
        let fp_str = res.as_str();

        // Protocol: q
        // Version: 13 (derived from Supported Versions extension: 0x0304)
        // SNI: d (present)
        // Cipher count: 01
        // Extension count: 04 (SNI, ALPN, SigAlgs, SupportedVersions)
        // ALPN: h2
        // Part a: q13d0104h2
        assert!(fp_str.starts_with("q13d0104h2_"));
    }

    #[test]
    fn test_alpn_non_alphanumeric_hex_fallback() {
        let make_packet_with_alpn = |alpn_bytes: &[u8]| -> Vec<u8> {
            let mut handshake = vec![
                0x03, 0x03, // version
            ];
            handshake.extend_from_slice(&[0u8; 32]); // random
            handshake.push(0x00); // session id len
            handshake.extend_from_slice(&[0x00, 0x02, 0x13, 0x01]); // ciphers
            handshake.extend_from_slice(&[0x01, 0x00]); // compression methods

            let mut ext_payload = Vec::new();
            // ALPN Extension (type 0x0010)
            // list_len is 1 + alpn_bytes.len()
            let list_len = 1 + alpn_bytes.len();
            let ext_len = 2 + list_len;
            ext_payload.extend_from_slice(&[0x00, 0x10]); // type
            ext_payload.extend_from_slice(&(ext_len as u16).to_be_bytes());
            ext_payload.extend_from_slice(&(list_len as u16).to_be_bytes());
            ext_payload.push(alpn_bytes.len() as u8);
            ext_payload.extend_from_slice(alpn_bytes);

            handshake.extend_from_slice(&(ext_payload.len() as u16).to_be_bytes());
            handshake.extend_from_slice(&ext_payload);

            let mut packet = vec![
                0x01,
                ((handshake.len() >> 16) & 0xFF) as u8,
                ((handshake.len() >> 8) & 0xFF) as u8,
                (handshake.len() & 0xFF) as u8,
            ];
            packet.extend_from_slice(&handshake);
            packet
        };

        // 1. Single non-alphanumeric byte: 0xAB
        // Hex: "ab". First char of hex: 'a', last (second) char of hex: 'b'.
        // Expected ALPN part in fingerprint: "ab"
        let p1 = make_packet_with_alpn(&[0xab]);
        let res1 = parse_ja4(&p1, true).unwrap();
        assert_eq!(&res1.as_str()[8..10], "ab");

        // 2. Single non-alphanumeric space character: 0x20
        // Hex: "20". First char: '2', last: '0'.
        // Expected ALPN part: "20"
        let p2 = make_packet_with_alpn(&[0x20]);
        let res2 = parse_ja4(&p2, true).unwrap();
        assert_eq!(&res2.as_str()[8..10], "20");

        // 3. Two non-alphanumeric bytes: 0xAB, 0xCD
        // First byte 0xAB (hex "ab" -> 'a'), last byte 0xCD (hex "cd" -> second char is 'd')
        // Expected ALPN part: "ad"
        let p3 = make_packet_with_alpn(&[0xab, 0xcd]);
        let res3 = parse_ja4(&p3, true).unwrap();
        assert_eq!(&res3.as_str()[8..10], "ad");

        // 4. Mix: non-alphanumeric 0x20 (space) and alphanumeric 0x61 ('a')
        // First byte 0x20 (not alphanumeric -> hex "20" -> '2')
        // Last byte 0x61 (alphanumeric -> ASCII -> 'a')
        // Expected ALPN part: "2a"
        let p4 = make_packet_with_alpn(&[0x20, 0x61]);
        let res4 = parse_ja4(&p4, true).unwrap();
        assert_eq!(&res4.as_str()[8..10], "2a");
    }

    #[test]
    fn test_full_fingerprint_hash_verification() {
        // Construct a synthetic ClientHello packet with known values
        let mut handshake = vec![
            0x03, 0x03, // version TLS 1.2
        ];
        // 32 bytes random
        handshake.extend_from_slice(&[0u8; 32]);
        // Session ID length (0)
        handshake.push(0x00);
        
        // Cipher suites length: 4 bytes (2 ciphers = 0x1302 and 0x1301)
        // Note: we place them in reverse/unsorted order to verify the sorting logic works correctly.
        handshake.extend_from_slice(&[0x00, 0x04, 0x13, 0x02, 0x13, 0x01]);
        
        // Compression methods length: 1 byte, 1 method: null = 0x00
        handshake.extend_from_slice(&[0x01, 0x00]);

        // Extensions payload
        let mut extensions_payload = Vec::new();

        // 1. Supported Versions Extension (type 0x002b)
        // format: extension_type (2 bytes), extension_len (2 bytes), ver_list_len (1 byte), ver1 (2 bytes)
        // extension_len is 1 + 2 = 3.
        // ver1 is TLS 1.3 (0x0304).
        // Note: We place this extension first (0x002b) to test that extension sorting works,
        // since Signature Algorithms is 0x000d.
        extensions_payload.extend_from_slice(&[0x00, 0x2b,  0x00, 0x03,  0x02,  0x03, 0x04]);

        // 2. Signature Algorithms Extension (type 0x000d)
        // format: extension_type (2 bytes), extension_len (2 bytes), sig_list_len (2 bytes), sig1 (2 bytes), sig2 (2 bytes)
        // extension_len is 2 + 4 = 6.
        // We write sigs in the order they should appear: 0x0403, 0x0804.
        extensions_payload.extend_from_slice(&[0x00, 0x0d,  0x00, 0x06,  0x00, 0x04,  0x04, 0x03,  0x08, 0x04]);

        let ext_len = extensions_payload.len();
        handshake.extend_from_slice(&(ext_len as u16).to_be_bytes());
        handshake.extend_from_slice(&extensions_payload);

        // Prepend handshake header
        let mut handshake_packet = vec![
            0x01, // ClientHello
            ((handshake.len() >> 16) & 0xFF) as u8,
            ((handshake.len() >> 8) & 0xFF) as u8,
            (handshake.len() & 0xFF) as u8,
        ];
        handshake_packet.extend_from_slice(&handshake);

        // Prepend TLS Record header (type = 0x16, version = 0x0301, length = handshake_packet.len())
        let mut packet = vec![
            0x16, // Handshake Record
            0x03, 0x01, // TLS 1.0
        ];
        packet.extend_from_slice(&(handshake_packet.len() as u16).to_be_bytes());
        packet.extend_from_slice(&handshake_packet);

        // Parse TCP-based TLS packet
        let res = parse_ja4(&packet, false).expect("Parsing full handshake should succeed");
        let fp_str = res.as_str();

        // Expected fingerprint:
        // - Protocol: t (TCP)
        // - Version: 13 (TLS 1.3 negotiated via Supported Versions)
        // - SNI: i (no SNI present)
        // - Cipher count: 02 (ciphers 1301 and 1302 after filtering GREASE)
        // - Extension count: 02 (Signature Algorithms + Supported Versions)
        // - ALPN: 00 (no ALPN present)
        // - Part a: t13i020200
        // - Part b: 62ed6f6ca7ad (SHA-256 of "1301,1302")
        // - Part c: ef5f37ab036a (SHA-256 of sorted extensions "000d,002b" + "_" + sorted/original order sigs "0403,0804" = "000d,002b_0403,0804")
        assert_eq!(fp_str, "t13i020200_62ed6f6ca7ad_ef5f37ab036a");
    }

    #[test]
    fn test_overflow_limits() {
        let mut handshake = vec![
            0x03, 0x03, // version
        ];
        handshake.extend_from_slice(&[0u8; 32]); // random
        handshake.push(0x00); // session id len
        
        // 130 ciphers (260 bytes)
        handshake.extend_from_slice(&[0x01, 0x04]); // 260
        for i in 0..130u16 {
            handshake.extend_from_slice(&i.to_be_bytes());
        }
        
        handshake.extend_from_slice(&[0x01, 0x00]); // compression methods
        
        // 130 extensions (each 4 bytes = 520 bytes)
        handshake.extend_from_slice(&[0x02, 0x08]); // 520
        for i in 0..130u16 {
            // Ignore GREASE to ensure they are counted
            let ext_type = if is_grease(i) { 0x0001 } else { i };
            handshake.extend_from_slice(&ext_type.to_be_bytes());
            handshake.extend_from_slice(&[0x00, 0x00]); // length 0
        }

        let mut packet = vec![
            0x01,
            ((handshake.len() >> 16) & 0xFF) as u8,
            ((handshake.len() >> 8) & 0xFF) as u8,
            (handshake.len() & 0xFF) as u8,
        ];
        packet.extend_from_slice(&handshake);
        
        let res = parse_ja4(&packet, true).unwrap();
        let fp = res.as_str();
        println!("Fingerprint: {}", fp);
        // Since ciphers count caps at 99 in JA4 fingerprint representation
        // And extensions count caps at 99.
        assert!(fp.starts_with("q12d999900_"));
    }

    #[test]
    fn test_truncated_packet() {
        let mut packet = vec![
            0x16, 0x03, 0x01, 0x00, 0x2f, 
            0x01, 0x00, 0x00, 0x2b,       
            0x03, 0x03,                   
        ];
        packet.extend_from_slice(&[0u8; 32]);
        packet.push(0x00);
        packet.extend_from_slice(&[0x00, 0x02, 0x13, 0x01]);
        packet.extend_from_slice(&[0x01, 0x00]);
        packet.extend_from_slice(&[0x00, 0x04, 0x00, 0x00, 0x00, 0x00]);
        
        // Truncate halfway through
        for i in 1..packet.len() {
            assert!(parse_ja4(&packet[..i], false).is_none());
        }
    }
}