yubikit 1.0.0-beta.0

YubiKey management library
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
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
// Copyright 2026 Yubico AB
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! YubiHSM Auth application for symmetric key storage and derivation.
//!
//! This module manages credentials on the YubiHSM Auth applet, which stores
//! symmetric keys used for establishing secure sessions with a YubiHSM 2.
//! The main entry point is [`HsmAuthSession`](crate::hsmauth::HsmAuthSession), which wraps a
//! [`SmartCardConnection`](crate::smartcard::SmartCardConnection).
//!
//! # Example
//!
//! ```no_run
//! use yubikit::platform::device::list_devices;
//! use yubikit::management::UsbInterface;
//! use yubikit::hsmauth::HsmAuthSession;
//!
//! let devices = list_devices(UsbInterface::CCID)?;
//! let dev = devices.first().expect("no YubiKey found");
//! let conn = dev.open_smartcard()?;
//! let mut session = HsmAuthSession::new(conn).map_err(|(e, _)| e)?;
//!
//! for cred in session.list_credentials()? {
//!     println!("{}: {:?}", cred.label, cred.algorithm);
//! }
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use std::fmt;

use thiserror::Error;
use zeroize::{Zeroize, Zeroizing};

use crate::__internal::tlv::{parse_tlv_list, tlv_append, tlv_encode};
use crate::core::Version;
use crate::core::patch_version;
use crate::smartcard::{Aid, SmartCardConnection, SmartCardError, SmartCardProtocol};

// ---------------------------------------------------------------------------
// TLV tags
// ---------------------------------------------------------------------------

const TAG_LABEL: u32 = 0x71;
const TAG_LABEL_LIST: u32 = 0x72;
const TAG_CREDENTIAL_PASSWORD: u32 = 0x73;
const TAG_ALGORITHM: u32 = 0x74;
const TAG_KEY_ENC: u32 = 0x75;
const TAG_KEY_MAC: u32 = 0x76;
const TAG_CONTEXT: u32 = 0x77;
const TAG_RESPONSE: u32 = 0x78;
const TAG_VERSION: u32 = 0x79;
const TAG_TOUCH: u32 = 0x7A;
const TAG_MANAGEMENT_KEY: u32 = 0x7B;
const TAG_PUBLIC_KEY: u32 = 0x7C;
const TAG_PRIVATE_KEY: u32 = 0x7D;

// ---------------------------------------------------------------------------
// Instruction bytes
// ---------------------------------------------------------------------------

const INS_PUT: u8 = 0x01;
const INS_DELETE: u8 = 0x02;
const INS_CALCULATE: u8 = 0x03;
const INS_GET_CHALLENGE: u8 = 0x04;
const INS_LIST: u8 = 0x05;
const INS_RESET: u8 = 0x06;
#[allow(dead_code)]
const INS_GET_VERSION: u8 = 0x07;
const INS_PUT_MANAGEMENT_KEY: u8 = 0x08;
const INS_GET_MANAGEMENT_KEY_RETRIES: u8 = 0x09;
const INS_GET_PUBLIC_KEY: u8 = 0x0A;
const INS_CHANGE_CREDENTIAL_PASSWORD: u8 = 0x0B;

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

/// Length of the management key in bytes.
const MANAGEMENT_KEY_LEN: usize = 16;
/// Length of the credential password in bytes.
const CREDENTIAL_PASSWORD_LEN: usize = 16;
/// Minimum length of a credential label in bytes.
const MIN_LABEL_LEN: usize = 1;
/// Maximum length of a credential label in bytes.
const MAX_LABEL_LEN: usize = 64;

/// The default management key (all zeros).
pub const DEFAULT_MANAGEMENT_KEY: &[u8; MANAGEMENT_KEY_LEN] = &[0u8; MANAGEMENT_KEY_LEN];
/// The initial retry counter value for new credentials.
const INITIAL_RETRY_COUNTER: u32 = 8;

// ---------------------------------------------------------------------------
// Secret newtypes
// ---------------------------------------------------------------------------

/// A 16-byte management key for the YubiHSM Auth application.
///
/// The key is automatically zeroized when dropped.
///
/// # Examples
///
/// ```
/// use yubikit::hsmauth::{HsmAuthManagementKey, DEFAULT_MANAGEMENT_KEY};
///
/// let key = HsmAuthManagementKey::new(DEFAULT_MANAGEMENT_KEY).unwrap();
/// ```
#[derive(Clone)]
pub struct HsmAuthManagementKey(crate::__internal::SecretValue<[u8; MANAGEMENT_KEY_LEN]>);

impl HsmAuthManagementKey {
    /// Create a new management key from a 16-byte slice.
    ///
    /// Returns an error if the slice is not exactly 16 bytes.
    pub fn new(key: &[u8]) -> Result<Self, HsmAuthError> {
        let arr: [u8; MANAGEMENT_KEY_LEN] = key.try_into().map_err(|_| {
            HsmAuthError::InvalidData(format!(
                "Management key must be {MANAGEMENT_KEY_LEN} bytes long"
            ))
        })?;
        Ok(Self(crate::__internal::SecretValue::new(arr)))
    }

    /// Access the raw key bytes.
    pub fn expose_secret(&self) -> &[u8] {
        self.0.expose_secret()
    }
}

impl fmt::Debug for HsmAuthManagementKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("HsmAuthManagementKey([REDACTED])")
    }
}

/// A 16-byte credential password for the YubiHSM Auth application.
///
/// The password is automatically zeroized when dropped.
///
/// # Examples
///
/// ```
/// use yubikit::hsmauth::CredentialPassword;
///
/// let pw = CredentialPassword::new(&[0u8; 16]).unwrap();
/// let pw_from_str = CredentialPassword::from_password("my-password").unwrap();
/// ```
#[derive(Clone)]
pub struct CredentialPassword(crate::__internal::SecretValue<[u8; CREDENTIAL_PASSWORD_LEN]>);

impl CredentialPassword {
    /// Create a credential password from a 16-byte slice.
    ///
    /// Returns an error if the slice is not exactly 16 bytes.
    pub fn new(password: &[u8]) -> Result<Self, HsmAuthError> {
        let arr: [u8; CREDENTIAL_PASSWORD_LEN] = password.try_into().map_err(|_| {
            HsmAuthError::InvalidData(format!(
                "Credential password must be {CREDENTIAL_PASSWORD_LEN} bytes long"
            ))
        })?;
        Ok(Self(crate::__internal::SecretValue::new(arr)))
    }

    /// Create a credential password from a UTF-8 string, padding with zeros.
    ///
    /// Returns an error if the encoded password exceeds 16 bytes.
    pub fn from_password(password: &str) -> Result<Self, HsmAuthError> {
        let bytes = password.as_bytes();
        if bytes.len() > CREDENTIAL_PASSWORD_LEN {
            return Err(HsmAuthError::InvalidData(format!(
                "Credential password must be at most {CREDENTIAL_PASSWORD_LEN} UTF-8 bytes"
            )));
        }
        let mut pw = [0u8; CREDENTIAL_PASSWORD_LEN];
        pw[..bytes.len()].copy_from_slice(bytes);
        Ok(Self(crate::__internal::SecretValue::new(pw)))
    }

    /// Access the raw password bytes.
    pub(crate) fn expose_secret(&self) -> &[u8] {
        self.0.expose_secret()
    }
}

impl fmt::Debug for CredentialPassword {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("CredentialPassword([REDACTED])")
    }
}

// ---------------------------------------------------------------------------
// Algorithm
// ---------------------------------------------------------------------------

/// The cryptographic algorithm used by an HSM Auth credential.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
#[repr(u8)]
pub enum Algorithm {
    /// AES-128 Yubico authentication.
    Aes128YubicoAuthentication = 38,
    /// EC P-256 Yubico authentication.
    EcP256YubicoAuthentication = 39,
}

impl Algorithm {
    /// Convert a raw byte value to an [`Algorithm`], returning `None` for unknown values.
    pub fn from_u8(v: u8) -> Option<Self> {
        match v {
            38 => Some(Self::Aes128YubicoAuthentication),
            39 => Some(Self::EcP256YubicoAuthentication),
            _ => None,
        }
    }

    /// Return the key length in bytes for this algorithm.
    pub fn key_len(self) -> usize {
        match self {
            Self::Aes128YubicoAuthentication => 16,
            Self::EcP256YubicoAuthentication => 32,
        }
    }
}

// ---------------------------------------------------------------------------
// Credential
// ---------------------------------------------------------------------------

/// An HSM Auth credential stored on the YubiKey.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Credential {
    /// The human-readable label identifying this credential.
    pub label: String,
    /// The algorithm used by this credential.
    pub algorithm: Algorithm,
    /// The remaining retry counter for this credential.
    pub counter: u32,
    /// Whether touch confirmation is required to use this credential.
    pub touch_required: bool,
}

// ---------------------------------------------------------------------------
// SessionKeys
// ---------------------------------------------------------------------------

/// A set of SCP03 session keys derived from an HSM Auth calculation.
#[derive(Clone, PartialEq, Eq)]
pub struct SessionKeys {
    /// The session encryption key (S-ENC).
    pub key_senc: [u8; 16],
    /// The session MAC key (S-MAC).
    pub key_smac: [u8; 16],
    /// The session response MAC key (S-RMAC).
    pub key_srmac: [u8; 16],
}

impl Drop for SessionKeys {
    fn drop(&mut self) {
        self.key_senc.zeroize();
        self.key_smac.zeroize();
        self.key_srmac.zeroize();
    }
}

impl fmt::Debug for SessionKeys {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SessionKeys")
            .field("key_senc", &"<redacted>")
            .field("key_smac", &"<redacted>")
            .field("key_srmac", &"<redacted>")
            .finish()
    }
}

impl SessionKeys {
    /// Parse session keys from a raw APDU response.
    pub fn parse(response: &[u8]) -> Result<Self, HsmAuthError> {
        if response.len() < 48 {
            return Err(HsmAuthError::InvalidData(
                "Session key response too short".into(),
            ));
        }
        Ok(Self {
            key_senc: response[..16].try_into().unwrap(),
            key_smac: response[16..32].try_into().unwrap(),
            key_srmac: response[32..48].try_into().unwrap(),
        })
    }
}

// ---------------------------------------------------------------------------
// Errors
// ---------------------------------------------------------------------------

/// Errors that can occur during HSM Auth operations.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum HsmAuthError {
    /// The requested feature is not supported by the device.
    #[error("Not supported: {0}")]
    NotSupported(String),
    /// The provided data is invalid or malformed.
    #[error("Invalid data: {0}")]
    InvalidData(String),
    /// The PIN was incorrect; the inner value is the number of remaining attempts.
    #[error("Invalid PIN, {0} attempts remaining")]
    InvalidPin(u32),
    /// A communication error occurred with the smart card.
    #[error("Connection error: {0}")]
    Connection(SmartCardError),
}

impl From<SmartCardError> for HsmAuthError {
    fn from(e: SmartCardError) -> Self {
        match e {
            SmartCardError::NotSupported(msg) => HsmAuthError::NotSupported(msg),
            SmartCardError::InvalidData(msg) => HsmAuthError::InvalidData(msg),
            other => HsmAuthError::Connection(other),
        }
    }
}

impl From<crate::__internal::tlv::TlvError> for HsmAuthError {
    fn from(e: crate::__internal::tlv::TlvError) -> Self {
        HsmAuthError::InvalidData(e.to_string())
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn parse_label(label: &str) -> Result<Vec<u8>, HsmAuthError> {
    let bytes = label.as_bytes();
    if bytes.len() < MIN_LABEL_LEN || bytes.len() > MAX_LABEL_LEN {
        return Err(HsmAuthError::InvalidData(format!(
            "Label must be between {MIN_LABEL_LEN} and {MAX_LABEL_LEN} bytes long"
        )));
    }
    Ok(bytes.to_vec())
}

fn password_to_key(password: &str) -> ([u8; 16], [u8; 16]) {
    let mut key = Zeroizing::new([0u8; 32]);
    pbkdf2::pbkdf2_hmac::<sha2_legacy::Sha256>(password.as_bytes(), b"Yubico", 10000, &mut *key);
    let key_enc: [u8; 16] = key[..16].try_into().unwrap();
    let key_mac: [u8; 16] = key[16..].try_into().unwrap();
    (key_enc, key_mac)
}

fn retries_from_sw(sw: u16) -> Option<u32> {
    if sw & 0xFFF0 == 0x63C0 {
        Some((sw & !0xFFF0) as u32)
    } else {
        None
    }
}

fn require_version(version: Version, required: Version, feature: &str) -> Result<(), HsmAuthError> {
    crate::core::require_version(version, required, feature).map_err(HsmAuthError::NotSupported)
}

/// Map APDU errors to InvalidPin where applicable, otherwise propagate.
fn map_pin_error(e: SmartCardError) -> HsmAuthError {
    if let Some(sw) = e.sw()
        && let Some(retries) = retries_from_sw(sw)
    {
        return HsmAuthError::InvalidPin(retries);
    }
    HsmAuthError::Connection(e)
}

// ---------------------------------------------------------------------------
// HsmAuthSession
// ---------------------------------------------------------------------------

/// A session for interacting with the YubiHSM Auth application on a YubiKey.
pub struct HsmAuthSession<C: SmartCardConnection> {
    protocol: SmartCardProtocol<C>,
    version: Version,
}

impl<C: SmartCardConnection> HsmAuthSession<C> {
    /// Open an HSM Auth session on the given connection.
    ///
    /// On error, returns the connection so the caller can recover it.
    pub fn new(connection: C) -> Result<Self, (HsmAuthError, C)> {
        let mut protocol = SmartCardProtocol::new(connection);
        let select_response = match protocol.select(Aid::HSMAUTH) {
            Ok(v) => v,
            Err(e) => return Err((e.into(), protocol.into_connection())),
        };
        Self::init(protocol, &select_response)
    }

    /// Open an HSM Auth session with SCP (Secure Channel Protocol).
    ///
    /// On error, returns the connection so the caller can recover it.
    pub fn new_with_scp(
        connection: C,
        scp_key_params: &crate::smartcard::ScpKeyParams,
    ) -> Result<Self, (HsmAuthError, C)> {
        let mut protocol = SmartCardProtocol::new(connection);
        let select_response = match protocol.select(Aid::HSMAUTH) {
            Ok(v) => v,
            Err(e) => return Err((e.into(), protocol.into_connection())),
        };
        if let Err(e) = protocol.init_scp(scp_key_params) {
            return Err((e.into(), protocol.into_connection()));
        }
        Self::init(protocol, &select_response)
    }

    fn init(
        mut protocol: SmartCardProtocol<C>,
        select_response: &[u8],
    ) -> Result<Self, (HsmAuthError, C)> {
        log::debug!("Opening HsmAuthSession");
        // Parse version from TAG_VERSION in select response
        let entries = match parse_tlv_list(select_response) {
            Ok(v) => v,
            Err(e) => return Err((e.into(), protocol.into_connection())),
        };
        let version_data = match entries
            .iter()
            .find(|(tag, _)| *tag == TAG_VERSION)
            .map(|(_, v)| v.as_slice())
        {
            Some(v) => v,
            None => {
                return Err((
                    HsmAuthError::InvalidData("Missing version tag in SELECT response".into()),
                    protocol.into_connection(),
                ));
            }
        };
        let version = patch_version(Version::from_bytes(version_data));
        protocol.configure(version);

        Ok(Self { protocol, version })
    }

    /// Return the firmware version of the YubiKey.
    pub fn version(&self) -> Version {
        self.version
    }

    /// Get a mutable reference to the underlying protocol.
    pub fn protocol_mut(&mut self) -> &mut SmartCardProtocol<C> {
        &mut self.protocol
    }

    /// Consume the session, returning the underlying connection.
    pub fn into_connection(self) -> C {
        self.protocol.into_connection()
    }

    /// Reset the HSM Auth application to its factory state.
    pub fn reset(&mut self) -> Result<(), HsmAuthError> {
        log::debug!("Resetting YubiHSM Auth");
        self.protocol.send_apdu(0, INS_RESET, 0xDE, 0xAD, &[])?;
        log::info!("YubiHSM Auth reset");
        Ok(())
    }

    /// List all credentials stored on the YubiKey.
    pub fn list_credentials(&mut self) -> Result<Vec<Credential>, HsmAuthError> {
        log::debug!("Listing YubiHSM Auth credentials");
        let response = self.protocol.send_apdu(0, INS_LIST, 0, 0, &[])?;
        let entries = parse_tlv_list(&response)?;

        let mut creds = Vec::new();
        for (tag, value) in &entries {
            if *tag != TAG_LABEL_LIST {
                continue;
            }
            if value.len() < 3 {
                return Err(HsmAuthError::InvalidData(
                    "Credential entry too short".into(),
                ));
            }
            let algorithm = Algorithm::from_u8(value[0]).ok_or_else(|| {
                HsmAuthError::InvalidData(format!("Unknown algorithm: {}", value[0]))
            })?;
            let touch_required = value[1] != 0;
            // Label is bytes [2..len-1], counter is last byte
            let label_bytes = &value[2..value.len() - 1];
            let counter = *value.last().unwrap() as u32;
            let label = String::from_utf8(label_bytes.to_vec())
                .map_err(|e| HsmAuthError::InvalidData(e.to_string()))?;
            creds.push(Credential {
                label,
                algorithm,
                counter,
                touch_required,
            });
        }
        Ok(creds)
    }

    fn put_credential(
        &mut self,
        management_key: &HsmAuthManagementKey,
        label: &str,
        key: &[u8],
        algorithm: Algorithm,
        credential_password: &CredentialPassword,
        touch_required: bool,
    ) -> Result<Credential, HsmAuthError> {
        let parsed_label = parse_label(label)?;

        let mut data = Zeroizing::new(Vec::new());
        tlv_append(
            &mut data,
            TAG_MANAGEMENT_KEY,
            management_key.expose_secret(),
        );
        tlv_append(&mut data, TAG_LABEL, &parsed_label);
        tlv_append(&mut data, TAG_ALGORITHM, &[algorithm as u8]);

        match algorithm {
            Algorithm::Aes128YubicoAuthentication => {
                tlv_append(&mut data, TAG_KEY_ENC, &key[..16]);
                tlv_append(&mut data, TAG_KEY_MAC, &key[16..]);
            }
            Algorithm::EcP256YubicoAuthentication => {
                tlv_append(&mut data, TAG_PRIVATE_KEY, key);
            }
        }

        tlv_append(
            &mut data,
            TAG_CREDENTIAL_PASSWORD,
            credential_password.expose_secret(),
        );
        tlv_append(&mut data, TAG_TOUCH, &[if touch_required { 1 } else { 0 }]);

        self.protocol
            .send_apdu(0, INS_PUT, 0, 0, &data)
            .map_err(map_pin_error)?;

        Ok(Credential {
            label: label.to_string(),
            algorithm,
            counter: INITIAL_RETRY_COUNTER,
            touch_required,
        })
    }

    /// Store an AES-128 symmetric credential with explicit encryption and MAC keys.
    pub fn put_credential_symmetric(
        &mut self,
        management_key: &HsmAuthManagementKey,
        label: &str,
        key_enc: &[u8],
        key_mac: &[u8],
        credential_password: &CredentialPassword,
        touch_required: bool,
    ) -> Result<Credential, HsmAuthError> {
        log::debug!("Storing symmetric credential");
        let aes_key_len = Algorithm::Aes128YubicoAuthentication.key_len();
        if key_enc.len() != aes_key_len || key_mac.len() != aes_key_len {
            return Err(HsmAuthError::InvalidData(format!(
                "Encryption and MAC key must be {aes_key_len} bytes long"
            )));
        }

        let mut key = Zeroizing::new(Vec::with_capacity(32));
        key.extend_from_slice(key_enc);
        key.extend_from_slice(key_mac);

        let result = self.put_credential(
            management_key,
            label,
            &key,
            Algorithm::Aes128YubicoAuthentication,
            credential_password,
            touch_required,
        )?;
        log::info!("Symmetric credential stored");
        Ok(result)
    }

    /// Store an AES-128 symmetric credential with keys derived from a password.
    pub fn put_credential_derived(
        &mut self,
        management_key: &HsmAuthManagementKey,
        label: &str,
        derivation_password: &str,
        credential_password: &CredentialPassword,
        touch_required: bool,
    ) -> Result<Credential, HsmAuthError> {
        log::debug!("Storing derived credential");
        let (mut key_enc, mut key_mac) = password_to_key(derivation_password);
        let result = self.put_credential_symmetric(
            management_key,
            label,
            &key_enc,
            &key_mac,
            credential_password,
            touch_required,
        );
        key_enc.zeroize();
        key_mac.zeroize();
        let credential = result?;
        log::info!("Derived credential stored");
        Ok(credential)
    }

    /// Store an EC P-256 asymmetric credential from an existing private key.
    ///
    /// Requires firmware version 5.6.0 or later.
    pub fn put_credential_asymmetric(
        &mut self,
        management_key: &HsmAuthManagementKey,
        label: &str,
        private_key: &p256::SecretKey,
        credential_password: &CredentialPassword,
        touch_required: bool,
    ) -> Result<Credential, HsmAuthError> {
        log::debug!("Storing asymmetric credential");
        require_version(self.version, Version(5, 6, 0), "put_credential_asymmetric")?;
        let key_bytes = private_key.to_bytes();
        let result = self.put_credential(
            management_key,
            label,
            key_bytes.as_slice(),
            Algorithm::EcP256YubicoAuthentication,
            credential_password,
            touch_required,
        )?;
        log::info!("Asymmetric credential stored");
        Ok(result)
    }

    /// Generate an EC P-256 asymmetric credential on the device.
    ///
    /// The private key is generated on-device and never leaves the YubiKey.
    /// Requires firmware version 5.6.0 or later.
    pub fn generate_credential_asymmetric(
        &mut self,
        management_key: &HsmAuthManagementKey,
        label: &str,
        credential_password: &CredentialPassword,
        touch_required: bool,
    ) -> Result<Credential, HsmAuthError> {
        log::debug!("Generating asymmetric credential");
        require_version(
            self.version,
            Version(5, 6, 0),
            "generate_credential_asymmetric",
        )?;
        let result = self.put_credential(
            management_key,
            label,
            &[], // Empty key triggers on-device generation
            Algorithm::EcP256YubicoAuthentication,
            credential_password,
            touch_required,
        )?;
        log::info!("Asymmetric credential generated");
        Ok(result)
    }

    /// Retrieve the public key associated with an asymmetric credential.
    ///
    /// Requires firmware version 5.6.0 or later.
    pub fn get_public_key(&mut self, label: &str) -> Result<p256::PublicKey, HsmAuthError> {
        log::debug!("Reading public key");
        require_version(self.version, Version(5, 6, 0), "get_public_key")?;
        let data = tlv_encode(TAG_LABEL, &parse_label(label)?);
        let response = self
            .protocol
            .send_apdu(0, INS_GET_PUBLIC_KEY, 0, 0, &data)?;

        parse_p256_public_key(&response)
    }

    /// Delete a credential from the YubiKey.
    pub fn delete_credential(
        &mut self,
        management_key: &HsmAuthManagementKey,
        label: &str,
    ) -> Result<(), HsmAuthError> {
        log::debug!("Deleting credential");
        let parsed_label = parse_label(label)?;
        let mut data = Zeroizing::new(Vec::new());
        tlv_append(
            &mut data,
            TAG_MANAGEMENT_KEY,
            management_key.expose_secret(),
        );
        tlv_append(&mut data, TAG_LABEL, &parsed_label);

        self.protocol
            .send_apdu(0, INS_DELETE, 0, 0, &data)
            .map_err(map_pin_error)?;
        log::info!("Credential deleted");
        Ok(())
    }

    fn change_credential_password_inner(
        &mut self,
        data: &[u8],
        use_management_key: bool,
    ) -> Result<(), HsmAuthError> {
        require_version(self.version, Version(5, 8, 0), "change_credential_password")?;
        let p1 = if use_management_key { 1 } else { 0 };
        self.protocol
            .send_apdu(0, INS_CHANGE_CREDENTIAL_PASSWORD, p1, 0, data)
            .map_err(map_pin_error)?;
        Ok(())
    }

    /// Change the password protecting a credential, authenticating with the current password.
    ///
    /// Requires firmware version 5.8.0 or later.
    pub fn change_credential_password(
        &mut self,
        label: &str,
        credential_password: &CredentialPassword,
        new_credential_password: &CredentialPassword,
    ) -> Result<(), HsmAuthError> {
        log::debug!("Changing credential password");

        let parsed_label = parse_label(label)?;
        let mut data = Zeroizing::new(Vec::new());
        tlv_append(&mut data, TAG_LABEL, &parsed_label);
        tlv_append(
            &mut data,
            TAG_CREDENTIAL_PASSWORD,
            credential_password.expose_secret(),
        );
        tlv_append(
            &mut data,
            TAG_CREDENTIAL_PASSWORD,
            new_credential_password.expose_secret(),
        );

        self.change_credential_password_inner(&data, false)?;
        log::info!("Credential password changed");
        Ok(())
    }

    /// Change the password protecting a credential, authenticating with the management key.
    ///
    /// Requires firmware version 5.8.0 or later.
    pub fn change_credential_password_admin(
        &mut self,
        management_key: &HsmAuthManagementKey,
        label: &str,
        new_credential_password: &CredentialPassword,
    ) -> Result<(), HsmAuthError> {
        log::debug!("Changing credential password (admin)");

        let parsed_label = parse_label(label)?;
        let mut data = Zeroizing::new(Vec::new());
        tlv_append(&mut data, TAG_LABEL, &parsed_label);
        tlv_append(
            &mut data,
            TAG_MANAGEMENT_KEY,
            management_key.expose_secret(),
        );
        tlv_append(
            &mut data,
            TAG_CREDENTIAL_PASSWORD,
            new_credential_password.expose_secret(),
        );

        self.change_credential_password_inner(&data, true)?;
        log::info!("Credential password changed");
        Ok(())
    }

    /// Replace the management key with a new one.
    pub fn put_management_key(
        &mut self,
        management_key: &HsmAuthManagementKey,
        new_management_key: &HsmAuthManagementKey,
    ) -> Result<(), HsmAuthError> {
        log::debug!("Updating management key");

        let mut data = Zeroizing::new(Vec::new());
        tlv_append(
            &mut data,
            TAG_MANAGEMENT_KEY,
            management_key.expose_secret(),
        );
        tlv_append(
            &mut data,
            TAG_MANAGEMENT_KEY,
            new_management_key.expose_secret(),
        );

        self.protocol
            .send_apdu(0, INS_PUT_MANAGEMENT_KEY, 0, 0, &data)
            .map_err(map_pin_error)?;
        log::info!("Management key updated");
        Ok(())
    }

    /// Get the number of remaining retry attempts for the management key.
    pub fn get_management_key_retries(&mut self) -> Result<u32, HsmAuthError> {
        log::debug!("Getting management key retries");
        let response = self
            .protocol
            .send_apdu(0, INS_GET_MANAGEMENT_KEY_RETRIES, 0, 0, &[])?;
        if response.is_empty() {
            return Err(HsmAuthError::InvalidData(
                "Empty response for management key retries".into(),
            ));
        }
        // Decode big-endian integer
        let mut value: u32 = 0;
        for &b in &response {
            value = (value << 8) | b as u32;
        }
        Ok(value)
    }

    fn calculate_session_keys_inner(
        &mut self,
        label: &str,
        context: &[u8],
        credential_password: &CredentialPassword,
        card_crypto: Option<&[u8]>,
        public_key: Option<&[u8]>,
    ) -> Result<Vec<u8>, HsmAuthError> {
        let parsed_label = parse_label(label)?;
        let mut data = Zeroizing::new(Vec::new());
        tlv_append(&mut data, TAG_LABEL, &parsed_label);
        tlv_append(&mut data, TAG_CONTEXT, context);

        if let Some(pk) = public_key {
            tlv_append(&mut data, TAG_PUBLIC_KEY, pk);
        }

        if let Some(cc) = card_crypto {
            tlv_append(&mut data, TAG_RESPONSE, cc);
        }

        tlv_append(
            &mut data,
            TAG_CREDENTIAL_PASSWORD,
            credential_password.expose_secret(),
        );

        let response = self
            .protocol
            .send_apdu(0, INS_CALCULATE, 0, 0, &data)
            .map_err(map_pin_error)?;
        Ok(response)
    }

    /// Calculate SCP03 session keys using a symmetric (AES-128) credential.
    pub fn calculate_session_keys_symmetric(
        &mut self,
        label: &str,
        context: &[u8],
        credential_password: &CredentialPassword,
        card_crypto: Option<&[u8]>,
    ) -> Result<SessionKeys, HsmAuthError> {
        log::debug!("Calculating symmetric session keys");
        let response = self.calculate_session_keys_inner(
            label,
            context,
            credential_password,
            card_crypto,
            None,
        )?;
        SessionKeys::parse(&response)
    }

    /// Calculate SCP03 session keys using an asymmetric (EC P-256) credential.
    ///
    /// Requires firmware version 5.6.0 or later.
    pub fn calculate_session_keys_asymmetric(
        &mut self,
        label: &str,
        context: &[u8],
        peer_public_key: &p256::PublicKey,
        credential_password: &CredentialPassword,
        card_crypto: &[u8],
    ) -> Result<SessionKeys, HsmAuthError> {
        log::debug!("Calculating asymmetric session keys");
        require_version(
            self.version,
            Version(5, 6, 0),
            "calculate_session_keys_asymmetric",
        )?;

        // Encode as SEC1 uncompressed point (0x04 || x || y)
        let encoded = p256::Sec1Point::from(peer_public_key);
        let public_key_data = encoded.as_bytes().to_vec();

        let response = self.calculate_session_keys_inner(
            label,
            context,
            credential_password,
            Some(card_crypto),
            Some(&public_key_data),
        )?;
        SessionKeys::parse(&response)
    }

    /// Get a challenge from the YubiKey for an asymmetric credential.
    ///
    /// Requires firmware version 5.6.0 or later.
    pub fn get_challenge(
        &mut self,
        label: &str,
        credential_password: Option<&CredentialPassword>,
    ) -> Result<Vec<u8>, HsmAuthError> {
        require_version(self.version, Version(5, 6, 0), "get_challenge")?;

        let parsed_label = parse_label(label)?;
        let mut data = Zeroizing::new(Vec::new());
        tlv_append(&mut data, TAG_LABEL, &parsed_label);

        if let Some(pw) = credential_password
            && (self.version >= Version(5, 7, 1) || self.version.0 == 0)
        {
            tlv_append(&mut data, TAG_CREDENTIAL_PASSWORD, pw.expose_secret());
        }

        let response = self.protocol.send_apdu(0, INS_GET_CHALLENGE, 0, 0, &data)?;
        Ok(response)
    }
}

fn parse_p256_public_key(data: &[u8]) -> Result<p256::PublicKey, HsmAuthError> {
    use elliptic_curve::sec1::FromSec1Point;

    // Try parsing as SEC1 (with 0x04 prefix) or raw 64-byte coordinates
    let encoded = if data.len() == 64 {
        let mut buf = Vec::with_capacity(65);
        buf.push(0x04);
        buf.extend_from_slice(data);
        buf
    } else {
        data.to_vec()
    };

    let point = p256::Sec1Point::from_bytes(&encoded)
        .map_err(|e| HsmAuthError::InvalidData(format!("Invalid EC point: {e}")))?;

    Option::from(p256::PublicKey::from_sec1_point(&point))
        .ok_or_else(|| HsmAuthError::InvalidData("Invalid EC public key".into()))
}

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

    #[test]
    fn test_algorithm_from_u8() {
        assert_eq!(
            Algorithm::from_u8(38),
            Some(Algorithm::Aes128YubicoAuthentication)
        );
        assert_eq!(
            Algorithm::from_u8(39),
            Some(Algorithm::EcP256YubicoAuthentication)
        );
        assert_eq!(Algorithm::from_u8(0), None);
    }

    #[test]
    fn test_algorithm_key_len() {
        assert_eq!(Algorithm::Aes128YubicoAuthentication.key_len(), 16);
        assert_eq!(Algorithm::EcP256YubicoAuthentication.key_len(), 32);
    }

    #[test]
    fn test_parse_label() {
        assert!(parse_label("").is_err());
        assert!(parse_label("a").is_ok());
        assert!(parse_label(&"a".repeat(64)).is_ok());
        assert!(parse_label(&"a".repeat(65)).is_err());
    }

    #[test]
    fn test_credential_password() {
        assert!(CredentialPassword::new(&[0u8; 16]).is_ok());
        assert!(CredentialPassword::new(&[0u8; 15]).is_err());
        assert!(CredentialPassword::new(&[0u8; 17]).is_err());
    }

    #[test]
    fn test_credential_password_from_str() {
        let pw = CredentialPassword::from_password("hello").unwrap();
        let bytes = pw.expose_secret();
        assert_eq!(bytes.len(), 16);
        assert_eq!(&bytes[..5], b"hello");
        assert_eq!(&bytes[5..], &[0u8; 11]);
    }

    #[test]
    fn test_credential_password_string_byte_limits() {
        for password in [
            "",
            "a\0b",
            "123456789012345",
            "1234567890123456",
            "\u{e9}\u{e9}\u{e9}\u{e9}\u{e9}\u{e9}\u{e9}\u{e9}",
            "\u{1f511}\u{1f511}\u{1f511}\u{1f511}",
        ] {
            let pw = CredentialPassword::from_password(password).unwrap();
            assert_eq!(&pw.expose_secret()[..password.len()], password.as_bytes());
            assert!(pw.expose_secret()[password.len()..].iter().all(|&b| b == 0));
        }
        for password in [
            "12345678901234567",
            "123456789012345\u{e9}",
            "\u{e9}\u{e9}\u{e9}\u{e9}\u{e9}\u{e9}\u{e9}\u{e9}a",
            "\u{1f511}\u{1f511}\u{1f511}\u{1f511}a",
        ] {
            assert!(matches!(
                CredentialPassword::from_password(password),
                Err(HsmAuthError::InvalidData(_))
            ));
        }
    }

    #[test]
    fn test_password_to_key() {
        let (enc, mac) = password_to_key("password");
        assert_eq!(
            enc,
            [
                0x09, 0x0b, 0x47, 0xdb, 0xed, 0x59, 0x56, 0x54, 0x90, 0x1d, 0xee, 0x1c, 0xc6, 0x55,
                0xe4, 0x20,
            ]
        );
        assert_eq!(
            mac,
            [
                0x59, 0x2f, 0xd4, 0x83, 0xf7, 0x59, 0xe2, 0x99, 0x09, 0xa0, 0x4c, 0x45, 0x05, 0xd2,
                0xce, 0x0a,
            ]
        );
    }

    #[test]
    fn test_retries_from_sw() {
        assert_eq!(retries_from_sw(0x63C5), Some(5));
        assert_eq!(retries_from_sw(0x63C0), Some(0));
        assert_eq!(retries_from_sw(0x9000), None);
    }

    #[test]
    fn test_session_keys_parse() {
        let data = vec![0u8; 48];
        let keys = SessionKeys::parse(&data).unwrap();
        assert_eq!(keys.key_senc.len(), 16);
        assert_eq!(keys.key_smac.len(), 16);
        assert_eq!(keys.key_srmac.len(), 16);

        assert!(SessionKeys::parse(&[0u8; 47]).is_err());
    }

    #[test]
    fn test_management_key() {
        assert!(HsmAuthManagementKey::new(&[0u8; 16]).is_ok());
        assert!(HsmAuthManagementKey::new(&[0u8; 15]).is_err());
    }

    #[test]
    fn test_parse_p256_public_key_sec1() {
        // Generate a key and round-trip it
        let secret = p256::SecretKey::generate();
        let public = secret.public_key();
        let encoded = p256::Sec1Point::from(public);
        let bytes = encoded.as_bytes();

        let parsed = parse_p256_public_key(bytes).unwrap();
        assert_eq!(parsed, public);
    }

    #[test]
    fn test_parse_p256_public_key_raw_64() {
        let secret = p256::SecretKey::generate();
        let public = secret.public_key();
        let encoded = p256::Sec1Point::from(public);
        // Strip the 0x04 prefix
        let raw = &encoded.as_bytes()[1..];
        assert_eq!(raw.len(), 64);

        let parsed = parse_p256_public_key(raw).unwrap();
        assert_eq!(parsed, public);
    }
}