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
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
// SPDX-FileCopyrightText: 2021-2023 Heiko Schaefer <heiko@schaefer.name>
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Client library for
//! [OpenPGP card](https://en.wikipedia.org/wiki/OpenPGP_card)
//! devices (such as Gnuk, Nitrokey, YubiKey, or Java smartcards running an
//! OpenPGP card application).
//!
//! This library aims to offer
//! - access to all features in the OpenPGP
//! [card specification](https://gnupg.org/ftp/specs/OpenPGP-smart-card-application-3.4.1.pdf),
//! - without relying on a particular
//! [OpenPGP implementation](https://www.openpgp.org/software/developer/).
//!
//! The [openpgp-card-sequoia](https://crates.io/crates/openpgp-card-sequoia)
//! crate offers a higher level wrapper based on the [Sequoia PGP](https://sequoia-pgp.org/)
//! implementation.
//!
//! Note that this library can't directly access cards by itself.
//! Instead, users need to supply a backend that implements the
//! [`CardBackend`] and [`CardTransaction`] traits.
//! For example [card-backend-pcsc](https://crates.io/crates/card-backend-pcsc)
//! offers a backend implementation that uses [PC/SC](https://en.wikipedia.org/wiki/PC/SC) to
//! communicate with Smart Cards.
//!
//! See the [architecture diagram](https://gitlab.com/openpgp-card/openpgp-card#architecture)
//! for an overview of the ecosystem around this crate.

extern crate core;

pub mod algorithm;
mod apdu;
pub mod card_do;
mod commands;
pub mod crypto_data;
mod errors;
mod keys;
mod oid;
mod tags;
mod tlv;

use std::convert::{TryFrom, TryInto};

use card_backend::{CardBackend, CardCaps, CardTransaction, PinType, SmartcardError};
use tags::{ShortTag, Tags};

use crate::algorithm::{AlgorithmAttributes, AlgorithmInformation};
use crate::apdu::command::Command;
use crate::apdu::response::RawResponse;
use crate::card_do::{
    ApplicationIdentifier, ApplicationRelatedData, CardholderRelatedData, ExtendedCapabilities,
    ExtendedLengthInfo, Fingerprint, HistoricalBytes, KdfDo, KeyGenerationTime, Lang,
    PWStatusBytes, SecuritySupportTemplate, Sex, UserInteractionFlag,
};
use crate::crypto_data::{CardUploadableKey, Cryptogram, Hash, PublicKeyMaterial};
pub use crate::errors::{Error, StatusBytes};
use crate::tlv::tag::Tag;
use crate::tlv::value::Value;
use crate::tlv::Tlv;

const OPENPGP_APPLICATION: &[u8] = &[0xD2, 0x76, 0x00, 0x01, 0x24, 0x01];

/// Identify a Key slot on an OpenPGP card
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
#[non_exhaustive]
pub enum KeyType {
    Signing,
    Decryption,
    Authentication,

    /// Attestation is a Yubico proprietary key slot
    Attestation,
}

impl KeyType {
    /// Get C1/C2/C3/DA values for this KeyTypes, to use as Tag
    fn algorithm_tag(&self) -> ShortTag {
        match self {
            Self::Signing => Tags::AlgorithmAttributesSignature,
            Self::Decryption => Tags::AlgorithmAttributesDecryption,
            Self::Authentication => Tags::AlgorithmAttributesAuthentication,
            Self::Attestation => Tags::AlgorithmAttributesAttestation,
        }
        .into()
    }

    /// Get C7/C8/C9/DB values for this KeyTypes, to use as Tag.
    ///
    /// (NOTE: these Tags are only used for "PUT DO", but GETting
    /// fingerprint information from the card uses the combined Tag C5)
    fn fingerprint_put_tag(&self) -> ShortTag {
        match self {
            Self::Signing => Tags::FingerprintSignature,
            Self::Decryption => Tags::FingerprintDecryption,
            Self::Authentication => Tags::FingerprintAuthentication,
            Self::Attestation => Tags::FingerprintAttestation,
        }
        .into()
    }

    /// Get CE/CF/D0/DD values for this KeyTypes, to use as Tag.
    ///
    /// (NOTE: these Tags are only used for "PUT DO", but GETting
    /// timestamp information from the card uses the combined Tag CD)
    fn timestamp_put_tag(&self) -> ShortTag {
        match self {
            Self::Signing => Tags::GenerationTimeSignature,
            Self::Decryption => Tags::GenerationTimeDecryption,
            Self::Authentication => Tags::GenerationTimeAuthentication,
            Self::Attestation => Tags::GenerationTimeAttestation,
        }
        .into()
    }
}

/// A struct to cache immutable information of a card.
/// Some of the data is stored during [`Card::new`].
/// Other information can optionally be cached later (e.g. `ai`)
#[derive(Debug)]
struct CardImmutable {
    aid: ApplicationIdentifier,
    ec: ExtendedCapabilities,
    hb: Option<HistoricalBytes>,     // new in v2.0
    eli: Option<ExtendedLengthInfo>, // new in v3.0

    // First `Option` layer encodes if this cache field has been initialized,
    // if `Some`, then the second `Option` layer encodes if the field exists on the card.
    ai: Option<Option<AlgorithmInformation>>, // new in v3.4
}

/// An OpenPGP card object (backed by a CardBackend implementation).
///
/// Most users will probably want to use the `PcscCard` backend from the `card-backend-pcsc` crate.
///
/// Users of this crate can keep a long lived [`Card`] object, including in long running programs.
/// All operations must be performed on a [`Transaction`] (which must be short lived).
pub struct Card {
    /// A connection to the smart card
    card: Box<dyn CardBackend + Send + Sync>,

    /// Capabilites of the card, determined from hints by the Backend,
    /// as well as the Application Related Data
    card_caps: Option<CardCaps>,

    /// A cache data structure for information that is immutable on OpenPGP cards.
    /// Some of the information gets initialized when connecting to the card.
    /// Other information my be cached on first read.
    immutable: Option<CardImmutable>,
}

impl Card {
    /// Turn a [`CardBackend`] into a [`Card`] object:
    ///
    /// The OpenPGP application is `SELECT`ed, and the card capabilities
    /// of the card are retrieved from the "Application Related Data".
    pub fn new<B>(backend: B) -> Result<Self, Error>
    where
        B: Into<Box<dyn CardBackend + Send + Sync>>,
    {
        let card: Box<dyn CardBackend + Send + Sync> = backend.into();

        let mut op = Self {
            card,
            card_caps: None,
            immutable: None,
        };

        let (caps, imm) = {
            let mut tx = op.transaction()?;
            tx.select()?;

            // Init card_caps
            let ard = tx.application_related_data()?;

            // Determine chaining/extended length support from card
            // metadata and cache this information in the CardTransaction
            // implementation (as a CardCaps)
            let mut ext_support = false;
            let mut chaining_support = false;

            if let Ok(hist) = ard.historical_bytes() {
                if let Some(cc) = hist.card_capabilities() {
                    chaining_support = cc.command_chaining();
                    ext_support = cc.extended_lc_le();
                }
            }

            let ext_cap = ard.extended_capabilities()?;

            // Get max command/response byte sizes from card
            let (max_cmd_bytes, max_rsp_bytes) = if let Ok(Some(eli)) =
                ard.extended_length_information()
            {
                // In card 3.x, max lengths come from ExtendedLengthInfo
                (eli.max_command_bytes(), eli.max_response_bytes())
            } else if let (Some(cmd), Some(rsp)) = (ext_cap.max_cmd_len(), ext_cap.max_resp_len()) {
                // In card 2.x, max lengths come from ExtendedCapabilities
                (cmd, rsp)
            } else {
                // Fallback: use 255 if we have no information from the card
                (255, 255)
            };

            let pw_status = ard.pw_status_bytes()?;
            let pw1_max = pw_status.pw1_max_len();
            let pw3_max = pw_status.pw3_max_len();

            let caps = CardCaps::new(
                ext_support,
                chaining_support,
                max_cmd_bytes,
                max_rsp_bytes,
                pw1_max,
                pw3_max,
            );

            let imm = CardImmutable {
                aid: ard.application_id()?,
                ec: ard.extended_capabilities()?,
                hb: Some(ard.historical_bytes()?),
                eli: ard.extended_length_information()?,
                ai: None, // FIXME: initialize elsewhere?
            };

            drop(tx);

            // General mechanism to ask the backend for amendments to
            // the CardCaps (e.g. to change support for "extended length")
            //
            // Also see https://blog.apdu.fr/posts/2011/05/extended-apdu-status-per-reader/
            let caps = op.card.limit_card_caps(caps);

            (caps, imm)
        };

        log::trace!("set card_caps to: {:x?}", caps);
        op.card_caps = Some(caps);

        log::trace!("set immutable card state to: {:x?}", imm);
        op.immutable = Some(imm);

        Ok(op)
    }

    /// Get the internal `CardBackend`.
    ///
    /// This is useful to perform operations on the card with a different crate,
    /// e.g. `yubikey-management`.
    pub fn into_card(self) -> Box<dyn CardBackend + Send + Sync> {
        self.card
    }

    /// Start a transaction on the underlying CardBackend.
    /// The resulting [Transaction] object allows performing commands on the card.
    ///
    /// Note: Transactions on the Card cannot be long running.
    /// They may be reset by the smart card subsystem within seconds, when idle.
    pub fn transaction(&mut self) -> Result<Transaction, Error> {
        let card_caps = &mut self.card_caps;
        let immutable = &mut self.immutable; // FIXME: unwrap

        let tx = self.card.transaction(Some(OPENPGP_APPLICATION))?;

        if tx.was_reset() {
            // FIXME: Signal state invalidation to the library user?
            // (E.g.: PIN verifications may have been lost.)
        }

        Ok(Transaction {
            tx,
            card_caps,
            immutable,
        })
    }
}

/// To perform commands on a [`Card`], a [`Transaction`] must be started.
/// This struct offers low-level access to OpenPGP card functionality.
///
/// On backends that support transactions, operations are grouped together in transaction, while
/// an object of this type lives.
///
/// A [`Transaction`] on typical underlying card subsystems must be short lived.
/// (Typically, smart cards can't be kept open for longer than a few seconds,
/// before they are automatically closed.)
pub struct Transaction<'a> {
    tx: Box<dyn CardTransaction + Send + Sync + 'a>,
    card_caps: &'a Option<CardCaps>,
    immutable: &'a mut Option<CardImmutable>,
}

impl<'a> Transaction<'a> {
    pub(crate) fn tx(&mut self) -> &mut dyn CardTransaction {
        self.tx.as_mut()
    }

    pub(crate) fn send_command(
        &mut self,
        cmd: Command,
        expect_reply: bool,
    ) -> Result<RawResponse, Error> {
        apdu::send_command(&mut *self.tx, cmd, *self.card_caps, expect_reply)
    }

    // SELECT

    /// Select the OpenPGP card application
    pub fn select(&mut self) -> Result<Vec<u8>, Error> {
        log::info!("OpenPgpTransaction: select");

        self.send_command(commands::select_openpgp(), false)?
            .try_into()
    }

    // TERMINATE DF

    /// 7.2.16 TERMINATE DF
    pub fn terminate_df(&mut self) -> Result<(), Error> {
        log::info!("OpenPgpTransaction: terminate_df");

        self.send_command(commands::terminate_df(), false)?;
        Ok(())
    }

    // ACTIVATE FILE

    /// 7.2.17 ACTIVATE FILE
    pub fn activate_file(&mut self) -> Result<(), Error> {
        log::info!("OpenPgpTransaction: activate_file");

        self.send_command(commands::activate_file(), false)?;
        Ok(())
    }

    // --- pinpad ---

    /// Does the reader support FEATURE_VERIFY_PIN_DIRECT?
    pub fn feature_pinpad_verify(&self) -> bool {
        self.tx.feature_pinpad_verify()
    }

    /// Does the reader support FEATURE_MODIFY_PIN_DIRECT?
    pub fn feature_pinpad_modify(&self) -> bool {
        self.tx.feature_pinpad_modify()
    }

    // --- get data ---

    /// Get the "application related data" from the card.
    ///
    /// (This data should probably be cached in a higher layer. Some parts of
    /// it are needed regularly, and it does not usually change during
    /// normal use of a card.)
    pub fn application_related_data(&mut self) -> Result<ApplicationRelatedData, Error> {
        log::info!("OpenPgpTransaction: application_related_data");

        let resp = self.send_command(commands::application_related_data(), true)?;
        let value = Value::from(resp.data()?, true)?;

        log::trace!(" ARD value: {:02x?}", value);

        Ok(ApplicationRelatedData(Tlv::new(
            Tags::ApplicationRelatedData,
            value,
        )))
    }

    // -- cached card data --

    /// Get read access to cached immutable card information
    fn card_immutable(&self) -> Result<&CardImmutable, Error> {
        if let Some(imm) = &self.immutable {
            Ok(imm)
        } else {
            // We expect that self.immutable has been initialized here
            Err(Error::InternalError(
                "Unexpected state of immutable cache".to_string(),
            ))
        }
    }

    /// Application Identifier.
    ///
    /// This function returns data that is cached during initialization.
    /// Calling it doesn't require sending a command to the card.
    pub fn application_identifier(&self) -> Result<ApplicationIdentifier, Error> {
        Ok(self.card_immutable()?.aid)
    }

    /// Extended capabilities.
    ///
    /// This function returns data that is cached during initialization.
    /// Calling it doesn't require sending a command to the card.
    pub fn extended_capabilities(&self) -> Result<ExtendedCapabilities, Error> {
        Ok(self.card_immutable()?.ec)
    }

    /// Historical Bytes (if available).
    ///
    /// This function returns data that is cached during initialization.
    /// Calling it doesn't require sending a command to the card.
    pub fn historical_bytes(&self) -> Result<Option<HistoricalBytes>, Error> {
        Ok(self.card_immutable()?.hb)
    }

    /// Extended length info (if available).
    ///
    /// This function returns data that is cached during initialization.
    /// Calling it doesn't require sending a command to the card.
    pub fn extended_length_info(&self) -> Result<Option<ExtendedLengthInfo>, Error> {
        Ok(self.card_immutable()?.eli)
    }

    #[allow(dead_code)]
    fn algorithm_information_cached(&mut self) -> Result<Option<AlgorithmInformation>, Error> {
        // FIXME: merge this fn with the regular/public `algorithm_information()` fn?

        if self.immutable.is_none() {
            // We expect that self.immutable has been initialized here
            return Err(Error::InternalError(
                "Unexpected state of immutable cache".to_string(),
            ));
        }

        if self.immutable.as_ref().unwrap().ai.is_none() {
            // Cached ai is unset, initialize it now!

            let ai = self.algorithm_information()?;
            self.immutable.as_mut().unwrap().ai = Some(ai);
        }

        Ok(self.immutable.as_ref().unwrap().ai.clone().unwrap())
    }

    // --- login data (5e) ---

    /// Get URL (5f50)
    pub fn url(&mut self) -> Result<Vec<u8>, Error> {
        log::info!("OpenPgpTransaction: url");

        self.send_command(commands::url(), true)?.try_into()
    }

    /// Get Login Data (5e)
    pub fn login_data(&mut self) -> Result<Vec<u8>, Error> {
        log::info!("OpenPgpTransaction: login_data");

        self.send_command(commands::login_data(), true)?.try_into()
    }

    /// Get cardholder related data (65)
    pub fn cardholder_related_data(&mut self) -> Result<CardholderRelatedData, Error> {
        log::info!("OpenPgpTransaction: cardholder_related_data");

        let resp = self.send_command(commands::cardholder_related_data(), true)?;

        resp.data()?.try_into()
    }

    /// Get security support template (7a)
    pub fn security_support_template(&mut self) -> Result<SecuritySupportTemplate, Error> {
        log::info!("OpenPgpTransaction: security_support_template");

        let resp = self.send_command(commands::security_support_template(), true)?;

        let tlv = Tlv::try_from(resp.data()?)?;

        let dst = tlv.find(Tags::DigitalSignatureCounter).ok_or_else(|| {
            Error::NotFound("Couldn't get DigitalSignatureCounter DO".to_string())
        })?;

        if let Value::S(data) = dst {
            let mut data = data.to_vec();
            if data.len() != 3 {
                return Err(Error::ParseError(format!(
                    "Unexpected length {} for DigitalSignatureCounter DO",
                    data.len()
                )));
            }

            data.insert(0, 0); // prepend a zero
            let data: [u8; 4] = data.try_into().unwrap();

            let dsc: u32 = u32::from_be_bytes(data);
            Ok(SecuritySupportTemplate { dsc })
        } else {
            Err(Error::NotFound(
                "Failed to process SecuritySupportTemplate".to_string(),
            ))
        }
    }

    /// Get cardholder certificate (each for AUT, DEC and SIG).
    ///
    /// Call select_data() before calling this fn to select a particular
    /// certificate (if the card supports multiple certificates).
    ///
    /// According to the OpenPGP card specification:
    ///
    /// The cardholder certificate DOs are designed to store a certificate (e. g. X.509)
    /// for the keys in the card. They can be used to identify the card in a client-server
    /// authentication, where specific non-OpenPGP-certificates are needed, for S-MIME and
    /// other x.509 related functions.
    ///
    /// (See <https://support.nitrokey.com/t/nitrokey-pro-and-pkcs-11-support-on-linux/160/4>
    /// for some discussion of the `cardholder certificate` OpenPGP card feature)
    #[allow(dead_code)]
    pub fn cardholder_certificate(&mut self) -> Result<Vec<u8>, Error> {
        log::info!("OpenPgpTransaction: cardholder_certificate");

        self.send_command(commands::cardholder_certificate(), true)?
            .try_into()
    }

    /// Call "GET NEXT DATA" for the DO cardholder certificate.
    ///
    /// Cardholder certificate data for multiple slots can be read from the card by first calling
    /// cardholder_certificate(), followed by up to two calls to  next_cardholder_certificate().
    pub fn next_cardholder_certificate(&mut self) -> Result<Vec<u8>, Error> {
        log::info!("OpenPgpTransaction: next_cardholder_certificate");

        self.send_command(commands::get_next_cardholder_certificate(), true)?
            .try_into()
    }

    /// Get "KDF-DO" (announced in Extended Capabilities)
    pub fn kdf_do(&mut self) -> Result<KdfDo, Error> {
        log::info!("OpenPgpTransaction: kdf_do");

        let kdf_do = self
            .send_command(commands::kdf_do(), true)?
            .data()?
            .try_into()?;

        log::trace!(" KDF DO value: {:02x?}", kdf_do);

        Ok(kdf_do)
    }

    /// Get "Algorithm Information"
    pub fn algorithm_information(&mut self) -> Result<Option<AlgorithmInformation>, Error> {
        log::info!("OpenPgpTransaction: algorithm_information");

        let resp = self.send_command(commands::algo_info(), true)?;

        let ai = resp.data()?.try_into()?;
        Ok(Some(ai))
    }

    /// Get "Attestation Certificate (Yubico)"
    pub fn attestation_certificate(&mut self) -> Result<Vec<u8>, Error> {
        log::info!("OpenPgpTransaction: attestation_certificate");

        self.send_command(commands::attestation_certificate(), true)?
            .try_into()
    }

    /// Firmware Version (YubiKey specific (?))
    pub fn firmware_version(&mut self) -> Result<Vec<u8>, Error> {
        log::info!("OpenPgpTransaction: firmware_version");

        self.send_command(commands::firmware_version(), true)?
            .try_into()
    }

    /// Set identity (Nitrokey Start specific (?)).
    /// [see:
    /// <https://docs.nitrokey.com/start/linux/multiple-identities.html>
    /// <https://github.com/Nitrokey/nitrokey-start-firmware/pull/33/>]
    pub fn set_identity(&mut self, id: u8) -> Result<Vec<u8>, Error> {
        log::info!("OpenPgpTransaction: set_identity");

        let resp = self.send_command(commands::set_identity(id), false);

        // Apparently it's normal to get "NotTransacted" from pcsclite when
        // the identity switch was successful.
        if let Err(Error::Smartcard(SmartcardError::NotTransacted)) = resp {
            Ok(vec![])
        } else {
            resp?.try_into()
        }
    }

    /// SELECT DATA ("select a DO in the current template").
    ///
    /// This command currently only applies to
    /// [`cardholder_certificate`](Transaction::cardholder_certificate) and
    /// [`set_cardholder_certificate`](Transaction::set_cardholder_certificate)
    /// in OpenPGP card.

    /// (This library leaves it up to consumers to decide on a strategy for dealing with this
    /// issue. Possible strategies include:
    /// - asking the card for its [`Transaction::firmware_version`]
    ///   and using the workaround if version <=5.4.3
    /// - trying this command first without the workaround, then with workaround if the card
    ///   returns [`StatusBytes::IncorrectParametersCommandDataField`]
    /// - for read operations: using [`Transaction::next_cardholder_certificate`]
    ///   instead of SELECT DATA)
    pub fn select_data(&mut self, num: u8, tag: &[u8]) -> Result<(), Error> {
        log::info!("OpenPgpTransaction: select_data");

        let tlv = Tlv::new(
            Tags::GeneralReference,
            Value::C(vec![Tlv::new(Tags::TagList, Value::S(tag.to_vec()))]),
        );

        let mut data = tlv.serialize();

        // YubiKey 5 up to (and including) firmware version 5.4.3 need a workaround
        // for this command.
        //
        // When sending the SELECT DATA command as defined in the card spec, without enabling the
        // workaround, bad YubiKey firmware versions (<= 5.4.3) return
        // `StatusBytes::IncorrectParametersCommandDataField`
        //
        // FIXME: caching for `firmware_version`?
        if let Ok(version) = self.firmware_version() {
            if version.len() == 3
                && version[0] == 5
                && (version[1] < 4 || (version[1] == 4 && version[2] <= 3))
            {
                // Workaround for YubiKey 5.
                // This hack is needed <= 5.4.3 according to ykman sources
                // (see _select_certificate() in ykman/openpgp.py).

                assert!(data.len() <= 255); // catch blatant misuse: tags are 1-2 bytes long

                data.insert(0, data.len() as u8);
            }
        }

        let cmd = commands::select_data(num, data);

        // Possible response data (Control Parameter = CP) don't need to be evaluated by the
        // application (See "7.2.5 SELECT DATA")
        self.send_command(cmd, true)?.check_ok()?;

        Ok(())
    }

    // --- optional private DOs (0101 - 0104) ---

    /// Get data from "private use" DO.
    ///
    /// `num` must be between 1 and 4.
    pub fn private_use_do(&mut self, num: u8) -> Result<Vec<u8>, Error> {
        log::info!("OpenPgpTransaction: private_use_do");

        if !(1..=4).contains(&num) {
            return Err(Error::UnsupportedFeature(format!(
                "Illegal Private Use DO num '{}'",
                num,
            )));
        }

        let cmd = commands::private_use_do(num);
        self.send_command(cmd, true)?.try_into()
    }

    // ----------

    /// Reset all state on this OpenPGP card.
    ///
    /// Note: the "factory reset" operation is not directly offered by the
    /// card spec. It is implemented as a series of OpenPGP card commands:
    /// - send 4 bad requests to verify pw1,
    /// - send 4 bad requests to verify pw3,
    /// - terminate_df,
    /// - activate_file.
    ///
    /// With most cards, this sequence of operations causes the card
    /// to revert to a "blank" state.
    ///
    /// (However, e.g. vanilla Gnuk doesn't support this functionality.
    /// Gnuk needs to be built with the `--enable-factory-reset`
    /// option to the `configure` script to enable this functionality).
    pub fn factory_reset(&mut self) -> Result<(), Error> {
        log::info!("OpenPgpTransaction: factory_reset");

        // send 4 bad requests to verify pw1
        for _ in 0..4 {
            let resp = self.verify_pw1_sign(&[0x40; 8]);

            if !(matches!(
                resp,
                Err(Error::CardStatus(StatusBytes::SecurityStatusNotSatisfied))
                    | Err(Error::CardStatus(StatusBytes::AuthenticationMethodBlocked))
                    | Err(Error::CardStatus(
                        StatusBytes::ExecutionErrorNonVolatileMemoryUnchanged
                    ))
                    | Err(Error::CardStatus(StatusBytes::PasswordNotChecked(_)))
                    | Err(Error::CardStatus(StatusBytes::ConditionOfUseNotSatisfied))
            )) {
                return Err(Error::InternalError(
                    "Unexpected status for reset, at pw1.".into(),
                ));
            }
        }

        // send 4 bad requests to verify pw3
        for _ in 0..4 {
            let resp = self.verify_pw3(&[0x40; 8]);

            if !(matches!(
                resp,
                Err(Error::CardStatus(StatusBytes::SecurityStatusNotSatisfied))
                    | Err(Error::CardStatus(StatusBytes::AuthenticationMethodBlocked))
                    | Err(Error::CardStatus(
                        StatusBytes::ExecutionErrorNonVolatileMemoryUnchanged
                    ))
                    | Err(Error::CardStatus(StatusBytes::PasswordNotChecked(_)))
                    | Err(Error::CardStatus(StatusBytes::ConditionOfUseNotSatisfied))
            )) {
                return Err(Error::InternalError(
                    "Unexpected status for reset, at pw3.".into(),
                ));
            }
        }

        self.terminate_df()?;
        self.activate_file()?;

        Ok(())
    }

    // --- verify/modify ---

    /// Verify pw1 (user) for signing operation (mode 81).
    ///
    /// Depending on the PW1 status byte (see Extended Capabilities) this
    /// access condition is only valid for one PSO:CDS command or remains
    /// valid for several attempts.
    pub fn verify_pw1_sign(&mut self, pin: &[u8]) -> Result<(), Error> {
        log::info!("OpenPgpTransaction: verify_pw1_sign");

        let cmd = commands::verify_pw1_81(pin.to_vec());

        self.send_command(cmd, false)?.try_into()
    }

    /// Verify pw1 (user) for signing operation (mode 81) using a
    /// pinpad on the card reader. If no usable pinpad is found, an error
    /// is returned.
    ///
    /// Depending on the PW1 status byte (see Extended Capabilities) this
    /// access condition is only valid for one PSO:CDS command or remains
    /// valid for several attempts.
    pub fn verify_pw1_sign_pinpad(&mut self) -> Result<(), Error> {
        log::info!("OpenPgpTransaction: verify_pw1_sign_pinpad");

        let cc = *self.card_caps;

        let res = self.tx().pinpad_verify(PinType::Sign, &cc)?;
        RawResponse::try_from(res)?.try_into()
    }

    /// Check the current access of PW1 for signing (mode 81).
    ///
    /// If verification is not required, an empty Ok Response is returned.
    ///
    /// (Note:
    /// - some cards don't correctly implement this feature, e.g. YubiKey 5
    /// - some cards that don't support this instruction may decrease the pin's error count,
    ///   eventually requiring the user to reset the pin)
    pub fn check_pw1_sign(&mut self) -> Result<(), Error> {
        log::info!("OpenPgpTransaction: check_pw1_sign");

        let verify = commands::verify_pw1_81(vec![]);
        self.send_command(verify, false)?.try_into()
    }

    /// Verify PW1 (user).
    /// (For operations except signing, mode 82).
    pub fn verify_pw1_user(&mut self, pin: &[u8]) -> Result<(), Error> {
        log::info!("OpenPgpTransaction: verify_pw1_user");

        let verify = commands::verify_pw1_82(pin.to_vec());
        self.send_command(verify, false)?.try_into()
    }

    /// Verify PW1 (user) for operations except signing (mode 82),
    /// using a pinpad on the card reader. If no usable pinpad is found,
    /// an error is returned.

    pub fn verify_pw1_user_pinpad(&mut self) -> Result<(), Error> {
        log::info!("OpenPgpTransaction: verify_pw1_user_pinpad");

        let cc = *self.card_caps;

        let res = self.tx().pinpad_verify(PinType::User, &cc)?;
        RawResponse::try_from(res)?.try_into()
    }

    /// Check the current access of PW1.
    /// (For operations except signing, mode 82).
    ///
    /// If verification is not required, an empty Ok Response is returned.
    ///
    /// (Note:
    /// - some cards don't correctly implement this feature, e.g. YubiKey 5
    /// - some cards that don't support this instruction may decrease the pin's error count,
    ///   eventually requiring the user to reset the pin)
    pub fn check_pw1_user(&mut self) -> Result<(), Error> {
        log::info!("OpenPgpTransaction: check_pw1_user");

        let verify = commands::verify_pw1_82(vec![]);
        self.send_command(verify, false)?.try_into()
    }

    /// Verify PW3 (admin).
    pub fn verify_pw3(&mut self, pin: &[u8]) -> Result<(), Error> {
        log::info!("OpenPgpTransaction: verify_pw3");

        let verify = commands::verify_pw3(pin.to_vec());
        self.send_command(verify, false)?.try_into()
    }

    /// Verify PW3 (admin) using a pinpad on the card reader. If no usable
    /// pinpad is found, an error is returned.
    pub fn verify_pw3_pinpad(&mut self) -> Result<(), Error> {
        log::info!("OpenPgpTransaction: verify_pw3_pinpad");

        let cc = *self.card_caps;

        let res = self.tx().pinpad_verify(PinType::Admin, &cc)?;
        RawResponse::try_from(res)?.try_into()
    }

    /// Check the current access of PW3 (admin).
    ///
    /// If verification is not required, an empty Ok Response is returned.
    ///
    /// (Note:
    /// - some cards don't correctly implement this feature, e.g. YubiKey 5
    /// - some cards that don't support this instruction may decrease the pin's error count,
    ///   eventually requiring the user to factory reset the card)
    pub fn check_pw3(&mut self) -> Result<(), Error> {
        log::info!("OpenPgpTransaction: check_pw3");

        let verify = commands::verify_pw3(vec![]);
        self.send_command(verify, false)?.try_into()
    }

    /// Change the value of PW1 (user password).
    ///
    /// The current value of PW1 must be presented in `old` for authorization.
    pub fn change_pw1(&mut self, old: &[u8], new: &[u8]) -> Result<(), Error> {
        log::info!("OpenPgpTransaction: change_pw1");

        let mut data = vec![];
        data.extend(old);
        data.extend(new);

        let change = commands::change_pw1(data);
        self.send_command(change, false)?.try_into()
    }

    /// Change the value of PW1 (0x81) using a pinpad on the
    /// card reader. If no usable pinpad is found, an error is returned.
    pub fn change_pw1_pinpad(&mut self) -> Result<(), Error> {
        log::info!("OpenPgpTransaction: change_pw1_pinpad");

        let cc = *self.card_caps;

        // Note: for change PW, only 0x81 and 0x83 are used!
        // 0x82 is implicitly the same as 0x81.
        let res = self.tx().pinpad_modify(PinType::Sign, &cc)?;
        RawResponse::try_from(res)?.try_into()
    }

    /// Change the value of PW3 (admin password).
    ///
    /// The current value of PW3 must be presented in `old` for authorization.
    pub fn change_pw3(&mut self, old: &[u8], new: &[u8]) -> Result<(), Error> {
        log::info!("OpenPgpTransaction: change_pw3");

        let mut data = vec![];
        data.extend(old);
        data.extend(new);

        let change = commands::change_pw3(data);
        self.send_command(change, false)?.try_into()
    }

    /// Change the value of PW3 (admin password) using a pinpad on the
    /// card reader. If no usable pinpad is found, an error is returned.
    pub fn change_pw3_pinpad(&mut self) -> Result<(), Error> {
        log::info!("OpenPgpTransaction: change_pw3_pinpad");

        let cc = *self.card_caps;

        let res = self.tx().pinpad_modify(PinType::Admin, &cc)?;
        RawResponse::try_from(res)?.try_into()
    }

    /// Reset the error counter for PW1 (user password) and set a new value
    /// for PW1.
    ///
    /// For authorization, either:
    /// - PW3 must have been verified previously,
    /// - secure messaging must be currently used,
    /// - the resetting_code must be presented.
    pub fn reset_retry_counter_pw1(
        &mut self,
        new_pw1: &[u8],
        resetting_code: Option<&[u8]>,
    ) -> Result<(), Error> {
        log::info!("OpenPgpTransaction: reset_retry_counter_pw1");

        let cmd = commands::reset_retry_counter_pw1(resetting_code, new_pw1);
        self.send_command(cmd, false)?.try_into()
    }

    // --- decrypt ---

    /// Decrypt the ciphertext in `dm`, on the card.
    ///
    /// (This is a wrapper around the low-level pso_decipher
    /// operation, it builds the required `data` field from `dm`)
    pub fn decipher(&mut self, dm: Cryptogram) -> Result<Vec<u8>, Error> {
        match dm {
            Cryptogram::RSA(message) => {
                // "Padding indicator byte (00) for RSA" (pg. 69)
                let mut data = vec![0x0];
                data.extend_from_slice(message);

                // Call the card to decrypt `data`
                self.pso_decipher(data)
            }
            Cryptogram::ECDH(eph) => {
                // "In case of ECDH the card supports a partial decrypt
                // only. The input is a cipher DO with the following data:"
                // A6 xx Cipher DO
                //  -> 7F49 xx Public Key DO
                //    -> 86 xx External Public Key

                // External Public Key
                let epk = Tlv::new(Tags::ExternalPublicKey, Value::S(eph.to_vec()));

                // Public Key DO
                let pkdo = Tlv::new(Tags::PublicKey, Value::C(vec![epk]));

                // Cipher DO
                let cdo = Tlv::new(Tags::Cipher, Value::C(vec![pkdo]));

                self.pso_decipher(cdo.serialize())
            }
        }
    }

    /// Run decryption operation on the smartcard (low level operation)
    /// (7.2.11 PSO: DECIPHER)
    ///
    /// (consider using the [`Self::decipher`] method if you don't want to create
    /// the data field manually)
    pub fn pso_decipher(&mut self, data: Vec<u8>) -> Result<Vec<u8>, Error> {
        log::info!("OpenPgpTransaction: pso_decipher");

        // The OpenPGP card is already connected and PW1 82 has been verified
        let dec_cmd = commands::decryption(data);
        let resp = self.send_command(dec_cmd, true)?;

        Ok(resp.data()?.to_vec())
    }

    /// Set the key to be used for the pso_decipher and the internal_authenticate commands.
    ///
    /// Valid until next reset of of the card or the next call to `select`
    /// The only keys that can be configured by this command are the `Decryption` and `Authentication` keys.
    ///
    /// The following first sets the *Authentication* key to be used for [`Self::pso_decipher`]
    /// and then sets the *Decryption* key to be used for [`Self::internal_authenticate`].
    ///
    /// ```no_run
    /// # use openpgp_card::{KeyType, Transaction};
    /// # let mut tx: Transaction<'static> = panic!();
    /// tx.manage_security_environment(KeyType::Decryption, KeyType::Authentication)?;
    /// tx.manage_security_environment(KeyType::Authentication, KeyType::Decryption)?;
    /// # Result::<(), openpgp_card::Error>::Ok(())
    /// ```
    pub fn manage_security_environment(
        &mut self,
        for_operation: KeyType,
        key_ref: KeyType,
    ) -> Result<(), Error> {
        log::info!("OpenPgpTransaction: manage_security_environment");

        if !matches!(for_operation, KeyType::Authentication | KeyType::Decryption)
            || !matches!(key_ref, KeyType::Authentication | KeyType::Decryption)
        {
            return Err(Error::UnsupportedAlgo("Only Decryption and Authentication keys can be manipulated by manage_security_environment".to_string()));
        }

        let cmd = commands::manage_security_environment(for_operation, key_ref);
        let resp = self.send_command(cmd, false)?;
        resp.check_ok()?;
        Ok(())
    }

    // --- sign ---

    /// Sign `hash`, on the card.
    ///
    /// This is a wrapper around the low-level
    /// pso_compute_digital_signature operation.
    /// It builds the required `data` field from `hash`.
    ///
    /// For RSA, this means a "DigestInfo" data structure is generated.
    /// (see 7.2.10.2 DigestInfo for RSA).
    ///
    /// With ECC the hash data is processed as is, using
    /// [`Self::pso_compute_digital_signature`].
    pub fn signature_for_hash(&mut self, hash: Hash) -> Result<Vec<u8>, Error> {
        self.pso_compute_digital_signature(digestinfo(hash))
    }

    /// Run signing operation on the smartcard (low level operation)
    /// (7.2.10 PSO: COMPUTE DIGITAL SIGNATURE)
    ///
    /// (consider using the [`Self::signature_for_hash`] method if you don't
    /// want to create the data field manually)
    pub fn pso_compute_digital_signature(&mut self, data: Vec<u8>) -> Result<Vec<u8>, Error> {
        log::info!("OpenPgpTransaction: pso_compute_digital_signature");

        let cds_cmd = commands::signature(data);

        let resp = self.send_command(cds_cmd, true)?;

        Ok(resp.data().map(|d| d.to_vec())?)
    }

    // --- internal authenticate ---

    /// Auth-sign `hash`, on the card.
    ///
    /// This is a wrapper around the low-level
    /// internal_authenticate operation.
    /// It builds the required `data` field from `hash`.
    ///
    /// For RSA, this means a "DigestInfo" data structure is generated.
    /// (see 7.2.10.2 DigestInfo for RSA).
    ///
    /// With ECC the hash data is processed as is.
    pub fn authenticate_for_hash(&mut self, hash: Hash) -> Result<Vec<u8>, Error> {
        self.internal_authenticate(digestinfo(hash))
    }

    /// Run signing operation on the smartcard (low level operation)
    /// (7.2.13 INTERNAL AUTHENTICATE)
    ///
    /// (consider using the `authenticate_for_hash()` method if you don't
    /// want to create the data field manually)
    pub fn internal_authenticate(&mut self, data: Vec<u8>) -> Result<Vec<u8>, Error> {
        log::info!("OpenPgpTransaction: internal_authenticate");

        let ia_cmd = commands::internal_authenticate(data);
        let resp = self.send_command(ia_cmd, true)?;

        Ok(resp.data().map(|d| d.to_vec())?)
    }

    // --- PUT DO ---

    /// Set data of "private use" DO.
    ///
    /// `num` must be between 1 and 4.
    ///
    /// Access condition:
    /// - 1/3 need PW1 (82)
    /// - 2/4 need PW3
    pub fn set_private_use_do(&mut self, num: u8, data: Vec<u8>) -> Result<(), Error> {
        log::info!("OpenPgpTransaction: set_private_use_do");

        if !(1..=4).contains(&num) {
            return Err(Error::UnsupportedFeature(format!(
                "Illegal Private Use DO num '{}'",
                num,
            )));
        }

        let cmd = commands::put_private_use_do(num, data);
        self.send_command(cmd, true)?.try_into()
    }

    pub fn set_login(&mut self, login: &[u8]) -> Result<(), Error> {
        log::info!("OpenPgpTransaction: set_login");

        let cmd = commands::put_login_data(login.to_vec());
        self.send_command(cmd, false)?.try_into()
    }

    pub fn set_name(&mut self, name: &[u8]) -> Result<(), Error> {
        log::info!("OpenPgpTransaction: set_name");

        let cmd = commands::put_name(name.to_vec());
        self.send_command(cmd, false)?.try_into()
    }

    pub fn set_lang(&mut self, lang: &[Lang]) -> Result<(), Error> {
        log::info!("OpenPgpTransaction: set_lang");

        let bytes: Vec<_> = lang.iter().flat_map(|&l| Vec::<u8>::from(l)).collect();

        let cmd = commands::put_lang(bytes);
        self.send_command(cmd, false)?.try_into()
    }

    pub fn set_sex(&mut self, sex: Sex) -> Result<(), Error> {
        log::info!("OpenPgpTransaction: set_sex");

        let cmd = commands::put_sex((&sex).into());
        self.send_command(cmd, false)?.try_into()
    }

    pub fn set_url(&mut self, url: &[u8]) -> Result<(), Error> {
        log::info!("OpenPgpTransaction: set_url");

        let cmd = commands::put_url(url.to_vec());
        self.send_command(cmd, false)?.try_into()
    }

    /// Set cardholder certificate (for AUT, DEC or SIG).
    ///
    /// Call select_data() before calling this fn to select a particular
    /// certificate (if the card supports multiple certificates).
    pub fn set_cardholder_certificate(&mut self, data: Vec<u8>) -> Result<(), Error> {
        log::info!("OpenPgpTransaction: set_cardholder_certificate");

        let cmd = commands::put_cardholder_certificate(data);
        self.send_command(cmd, false)?.try_into()
    }

    /// Set algorithm attributes for a key slot (4.4.3.9 Algorithm Attributes)
    ///
    /// Note: `algorithm_attributes` needs to precisely specify the
    /// RSA bit-size of e (if applicable), and import format, with values
    /// that the current card supports.
    pub fn set_algorithm_attributes(
        &mut self,
        key_type: KeyType,
        algorithm_attributes: &AlgorithmAttributes,
    ) -> Result<(), Error> {
        log::info!("OpenPgpTransaction: set_algorithm_attributes");

        // Don't set algorithm if the feature is not available?
        let ecap = self.extended_capabilities()?;
        if !ecap.algo_attrs_changeable() {
            // Don't change the algorithm attributes, if the card doesn't support change
            // FIXME: Compare current and requested setting and return an error, if they differ?

            return Ok(());
        }

        // Command to PUT the algorithm attributes
        let cmd = commands::put_data(
            key_type.algorithm_tag(),
            algorithm_attributes.to_data_object()?,
        );

        self.send_command(cmd, false)?.try_into()
    }

    /// Set PW Status Bytes.
    ///
    /// If `long` is false, send 1 byte to the card, otherwise 4.
    /// According to the spec, length information should not be changed.
    ///
    /// So, effectively, with 'long == false' the setting `pw1_cds_multi`
    /// can be changed.
    /// With 'long == true', the settings `pw1_pin_block` and `pw3_pin_block`
    /// can also be changed.
    ///
    /// (See OpenPGP card spec, pg. 28)
    pub fn set_pw_status_bytes(
        &mut self,
        pw_status: &PWStatusBytes,
        long: bool,
    ) -> Result<(), Error> {
        log::info!("OpenPgpTransaction: set_pw_status_bytes");

        let data = pw_status.serialize_for_put(long);

        let cmd = commands::put_pw_status(data);
        self.send_command(cmd, false)?.try_into()
    }

    pub fn set_fingerprint(&mut self, fp: Fingerprint, key_type: KeyType) -> Result<(), Error> {
        log::info!("OpenPgpTransaction: set_fingerprint");

        let cmd = commands::put_data(key_type.fingerprint_put_tag(), fp.as_bytes().to_vec());

        self.send_command(cmd, false)?.try_into()
    }

    pub fn set_ca_fingerprint_1(&mut self, fp: Fingerprint) -> Result<(), Error> {
        log::info!("OpenPgpTransaction: set_ca_fingerprint_1");

        let cmd = commands::put_data(Tags::CaFingerprint1, fp.as_bytes().to_vec());
        self.send_command(cmd, false)?.try_into()
    }

    pub fn set_ca_fingerprint_2(&mut self, fp: Fingerprint) -> Result<(), Error> {
        log::info!("OpenPgpTransaction: set_ca_fingerprint_2");

        let cmd = commands::put_data(Tags::CaFingerprint2, fp.as_bytes().to_vec());
        self.send_command(cmd, false)?.try_into()
    }

    pub fn set_ca_fingerprint_3(&mut self, fp: Fingerprint) -> Result<(), Error> {
        log::info!("OpenPgpTransaction: set_ca_fingerprint_3");

        let cmd = commands::put_data(Tags::CaFingerprint3, fp.as_bytes().to_vec());
        self.send_command(cmd, false)?.try_into()
    }

    pub fn set_creation_time(
        &mut self,
        time: KeyGenerationTime,
        key_type: KeyType,
    ) -> Result<(), Error> {
        log::info!("OpenPgpTransaction: set_creation_time");

        // Timestamp update
        let time_value: Vec<u8> = time.get().to_be_bytes().to_vec();

        let cmd = commands::put_data(key_type.timestamp_put_tag(), time_value);

        self.send_command(cmd, false)?.try_into()
    }

    // FIXME: optional DO SM-Key-ENC

    // FIXME: optional DO SM-Key-MAC

    /// Set resetting code
    /// (4.3.4 Resetting Code)
    pub fn set_resetting_code(&mut self, resetting_code: &[u8]) -> Result<(), Error> {
        log::info!("OpenPgpTransaction: set_resetting_code");

        let cmd = commands::put_data(Tags::ResettingCode, resetting_code.to_vec());
        self.send_command(cmd, false)?.try_into()
    }

    /// Set AES key for symmetric decryption/encryption operations.
    ///
    /// Optional DO (announced in Extended Capabilities) for
    /// PSO:ENC/DEC with AES (32 bytes dec. in case of
    /// AES256, 16 bytes dec. in case of AES128).
    pub fn set_pso_enc_dec_key(&mut self, key: &[u8]) -> Result<(), Error> {
        log::info!("OpenPgpTransaction: set_pso_enc_dec_key");

        let cmd = commands::put_data(Tags::PsoEncDecKey, key.to_vec());
        self.send_command(cmd, false)?.try_into()
    }

    /// Set UIF for PSO:CDS
    pub fn set_uif_pso_cds(&mut self, uif: &UserInteractionFlag) -> Result<(), Error> {
        log::info!("OpenPgpTransaction: set_uif_pso_cds");

        let cmd = commands::put_data(Tags::UifSig, uif.as_bytes().to_vec());
        self.send_command(cmd, false)?.try_into()
    }

    /// Set UIF for PSO:DEC
    pub fn set_uif_pso_dec(&mut self, uif: &UserInteractionFlag) -> Result<(), Error> {
        log::info!("OpenPgpTransaction: set_uif_pso_dec");

        let cmd = commands::put_data(Tags::UifDec, uif.as_bytes().to_vec());
        self.send_command(cmd, false)?.try_into()
    }

    /// Set UIF for PSO:AUT
    pub fn set_uif_pso_aut(&mut self, uif: &UserInteractionFlag) -> Result<(), Error> {
        log::info!("OpenPgpTransaction: set_uif_pso_aut");

        let cmd = commands::put_data(Tags::UifAuth, uif.as_bytes().to_vec());
        self.send_command(cmd, false)?.try_into()
    }

    /// Set UIF for Attestation key
    pub fn set_uif_attestation(&mut self, uif: &UserInteractionFlag) -> Result<(), Error> {
        log::info!("OpenPgpTransaction: set_uif_attestation");

        let cmd = commands::put_data(Tags::UifAttestation, uif.as_bytes().to_vec());
        self.send_command(cmd, false)?.try_into()
    }

    /// Generate Attestation (Yubico)
    pub fn generate_attestation(&mut self, key_type: KeyType) -> Result<(), Error> {
        log::info!("OpenPgpTransaction: generate_attestation");

        let key = match key_type {
            KeyType::Signing => 0x01,
            KeyType::Decryption => 0x02,
            KeyType::Authentication => 0x03,
            _ => return Err(Error::InternalError("Unexpected KeyType".to_string())),
        };

        let cmd = commands::generate_attestation(key);
        self.send_command(cmd, false)?.try_into()
    }

    // FIXME: Attestation key algo attr, FP, CA-FP, creation time

    // FIXME: SM keys (ENC and MAC) with Tags D1 and D2

    // FIXME: KDF DO

    // FIXME: certificate used with secure messaging

    // FIXME: Attestation Certificate (Yubico)

    // -----------------

    /// Import an existing private key to the card.
    /// (This implicitly sets the algorithm attributes, fingerprint and timestamp)
    pub fn key_import(
        &mut self,
        key: Box<dyn CardUploadableKey>,
        key_type: KeyType,
    ) -> Result<(), Error> {
        keys::key_import(self, key, key_type)
    }

    /// Generate a key on the card.
    /// (7.2.14 GENERATE ASYMMETRIC KEY PAIR)
    pub fn generate_key(
        &mut self,
        fp_from_pub: fn(
            &PublicKeyMaterial,
            KeyGenerationTime,
            KeyType,
        ) -> Result<Fingerprint, Error>,
        key_type: KeyType,
    ) -> Result<(PublicKeyMaterial, KeyGenerationTime), Error> {
        // get current (possibly updated) state of algorithm_attributes
        let ard = self.application_related_data()?; // no caching, here!
        let cur_algo = ard.algorithm_attributes(key_type)?;

        keys::gen_key_set_metadata(self, fp_from_pub, &cur_algo, key_type)
    }

    /// Get public key material from the card.
    ///
    /// Note: this fn returns a set of raw public key data (not an
    /// OpenPGP data structure).
    ///
    /// Note also that the information from the card is insufficient to
    /// reconstruct a pre-existing OpenPGP public key that corresponds to
    /// the private key on the card.
    pub fn public_key(&mut self, key_type: KeyType) -> Result<PublicKeyMaterial, Error> {
        keys::public_key(self, key_type)
    }
}

fn digestinfo(hash: Hash) -> Vec<u8> {
    match hash {
        Hash::SHA256(_) | Hash::SHA384(_) | Hash::SHA512(_) => {
            let tlv = Tlv::new(
                Tags::Sequence,
                Value::C(vec![
                    Tlv::new(
                        Tags::Sequence,
                        Value::C(vec![
                            Tlv::new(
                                Tags::ObjectIdentifier,
                                // unwrapping is ok, for SHA*
                                Value::S(hash.oid().unwrap().to_vec()),
                            ),
                            Tlv::new(Tags::Null, Value::S(vec![])),
                        ]),
                    ),
                    Tlv::new(Tags::OctetString, Value::S(hash.digest().to_vec())),
                ]),
            );

            tlv.serialize()
        }
        Hash::EdDSA(d) => d.to_vec(),
        Hash::ECDSA(d) => d.to_vec(),
    }
}