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
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
// Copyright 2019 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0
//! Utility module
//!
//! This module mostly contains helper elements meant to act as either wrappers around FFI-level
//! structs or builders for them, along with other convenience elements.
//! The naming structure usually takes the names inherited from the TSS spec and applies Rust
//! guidelines to them. Structures that are meant to act as builders have `Builder` appended to
//! type name. Unions are converted to Rust `enum`s by dropping the `TPMU` qualifier and appending
//! `Union`.
use crate::constants::algorithm::{Cipher, EllipticCurve, HashingAlgorithm};
use crate::constants::tss::*;
use crate::structures::{Digest, PcrSlot};
use crate::tss2_esys::*;
use crate::{Error, Result, WrapperErrorKind};
use bitfield::bitfield;
use enumflags2::BitFlags;
use log::error;
use zeroize::Zeroize;

use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap};
use std::convert::{TryFrom, TryInto};
/// Helper for building `TPM2B_PUBLIC` values out of its subcomponents.
///
/// Currently the implementation is incomplete, focusing on creating objects of RSA type.
// Most of the field types are from bindgen which does not implement Debug on them.
#[allow(missing_debug_implementations)]
pub struct Tpm2BPublicBuilder {
    type_: Option<TPMI_ALG_PUBLIC>,
    name_alg: TPMI_ALG_HASH,
    object_attributes: ObjectAttributes,
    auth_policy: TPM2B_DIGEST,
    parameters: Option<PublicParmsUnion>,
    unique: Option<PublicIdUnion>,
}

impl Tpm2BPublicBuilder {
    /// Create a new builder with default (i.e. empty or null) placeholder values.
    pub fn new() -> Self {
        Tpm2BPublicBuilder {
            type_: None,
            name_alg: TPM2_ALG_NULL,
            object_attributes: ObjectAttributes(0),
            auth_policy: Default::default(),
            parameters: None,
            unique: None,
        }
    }

    /// Set the type of the object to be built.
    pub fn with_type(mut self, type_: TPMI_ALG_PUBLIC) -> Self {
        self.type_ = Some(type_);
        self
    }

    /// Set the algorithm used to derive the object name.
    pub fn with_name_alg(mut self, name_alg: TPMI_ALG_HASH) -> Self {
        self.name_alg = name_alg;
        self
    }

    /// Set the object attributes.
    pub fn with_object_attributes(mut self, obj_attr: ObjectAttributes) -> Self {
        self.object_attributes = obj_attr;
        self
    }

    /// Set the authentication policy hash for the object.
    pub fn with_auth_policy(mut self, size: u16, buffer: [u8; 64]) -> Self {
        self.auth_policy = TPM2B_DIGEST { size, buffer };
        self
    }

    /// Set the public parameters of the object.
    pub fn with_parms(mut self, parameters: PublicParmsUnion) -> Self {
        self.parameters = Some(parameters);
        self
    }

    /// Set the unique value for the object.
    pub fn with_unique(mut self, unique: PublicIdUnion) -> Self {
        self.unique = Some(unique);
        self
    }

    /// Build an object with the previously provided parameters.
    ///
    /// The paramters are checked for consistency based on the TSS specifications for the
    /// `TPM2B_PUBLIC` structure and for the structures nested within it.
    ///
    /// Currently only objects of type `TPM2_ALG_RSA` are supported.
    ///
    /// # Errors
    /// * if no public parameters are provided, `ParamsMissing` wrapper error is returned
    /// * if a public parameter type or public ID type is provided that is incosistent with the
    /// object type provided, `InconsistentParams` wrapper error is returned
    ///
    /// # Panics
    /// * will panic on unsupported platforms (i.e. on 8 bit processors)
    pub fn build(self) -> Result<TPM2B_PUBLIC> {
        match self.type_ {
            Some(TPM2_ALG_RSA) => {
                // RSA key
                let parameters;
                let unique;
                if let Some(PublicParmsUnion::RsaDetail(parms)) = self.parameters {
                    parameters = TPMU_PUBLIC_PARMS { rsaDetail: parms };
                } else if self.parameters.is_none() {
                    return Err(Error::local_error(WrapperErrorKind::ParamsMissing));
                } else {
                    return Err(Error::local_error(WrapperErrorKind::InconsistentParams));
                }

                if let Some(PublicIdUnion::Rsa(rsa_unique)) = self.unique {
                    unique = TPMU_PUBLIC_ID { rsa: *rsa_unique };
                } else if self.unique.is_none() {
                    unique = Default::default();
                } else {
                    return Err(Error::local_error(WrapperErrorKind::InconsistentParams));
                }

                Ok(TPM2B_PUBLIC {
                    size: std::mem::size_of::<TPMT_PUBLIC>()
                        .try_into()
                        .expect("Failed to convert usize to u16"), // should not fail on valid targets
                    publicArea: TPMT_PUBLIC {
                        type_: self.type_.unwrap(), // cannot fail given that this is inside a match on `type_`
                        nameAlg: self.name_alg,
                        objectAttributes: self.object_attributes.0,
                        authPolicy: self.auth_policy,
                        parameters,
                        unique,
                    },
                })
            }
            Some(TPM2_ALG_ECC) => {
                // ECC key
                let parameters;
                let unique;
                if let Some(PublicParmsUnion::EccDetail(parms)) = self.parameters {
                    parameters = TPMU_PUBLIC_PARMS { eccDetail: parms };
                } else if self.parameters.is_none() {
                    return Err(Error::local_error(WrapperErrorKind::ParamsMissing));
                } else {
                    return Err(Error::local_error(WrapperErrorKind::InconsistentParams));
                }

                if let Some(PublicIdUnion::Ecc(rsa_unique)) = self.unique {
                    unique = TPMU_PUBLIC_ID { ecc: *rsa_unique };
                } else if self.unique.is_none() {
                    unique = Default::default();
                } else {
                    return Err(Error::local_error(WrapperErrorKind::InconsistentParams));
                }

                Ok(TPM2B_PUBLIC {
                    size: std::mem::size_of::<TPMT_PUBLIC>()
                        .try_into()
                        .expect("Failed to convert usize to u16"), // should not fail on valid targets
                    publicArea: TPMT_PUBLIC {
                        type_: self.type_.unwrap(), // cannot fail given that this is inside a match on `type_`
                        nameAlg: self.name_alg,
                        objectAttributes: self.object_attributes.0,
                        authPolicy: self.auth_policy,
                        parameters,
                        unique,
                    },
                })
            }
            _ => Err(Error::local_error(WrapperErrorKind::UnsupportedParam)),
        }
    }
}

impl Default for Tpm2BPublicBuilder {
    fn default() -> Self {
        Tpm2BPublicBuilder::new()
    }
}

/// Builder for `TPMS_RSA_PARMS` values.
// Most of the field types are from bindgen which does not implement Debug on them.
#[allow(missing_debug_implementations)]
#[derive(Copy, Clone, Default)]
pub struct TpmsRsaParmsBuilder {
    /// Symmetric cipher to be used in conjuction with the key
    pub symmetric: Option<TPMT_SYM_DEF_OBJECT>,
    /// Asymmetric scheme to be used for key operations
    pub scheme: Option<AsymSchemeUnion>,
    /// Size of key, in bits
    pub key_bits: TPMI_RSA_KEY_BITS,
    /// Public exponent of the key. A value of 0 defaults to 2 ^ 16 + 1
    pub exponent: u32,
    /// Flag indicating whether the key shall be used for signing
    pub for_signing: bool,
    /// Flag indicating whether the key shall be used for decryption
    pub for_decryption: bool,
    /// Flag indicating whether the key is restricted
    pub restricted: bool,
}

impl TpmsRsaParmsBuilder {
    /// Create parameters for a restricted decryption key
    pub fn new_restricted_decryption_key(
        symmetric: TPMT_SYM_DEF_OBJECT,
        key_bits: TPMI_RSA_KEY_BITS,
        exponent: u32,
    ) -> Self {
        TpmsRsaParmsBuilder {
            symmetric: Some(symmetric),
            scheme: Some(AsymSchemeUnion::AnySig(None)),
            key_bits,
            exponent,
            for_signing: false,
            for_decryption: true,
            restricted: true,
        }
    }

    /// Create parameters for an unrestricted signing key
    pub fn new_unrestricted_signing_key(
        scheme: AsymSchemeUnion,
        key_bits: TPMI_RSA_KEY_BITS,
        exponent: u32,
    ) -> Self {
        TpmsRsaParmsBuilder {
            symmetric: None,
            scheme: Some(scheme),
            key_bits,
            exponent,
            for_signing: true,
            for_decryption: false,
            restricted: false,
        }
    }

    /// Build an object given the previously provded parameters.
    ///
    /// The only mandatory parameter is the asymmetric scheme.
    ///
    /// # Errors
    /// * if no asymmetric scheme is set, `ParamsMissing` wrapper error is returned.
    /// * if the `for_signing`, `for_decryption` and `restricted` parameters are
    /// inconsistent with the rest of the parameters, `InconsistentParams` wrapper
    /// error is returned
    pub fn build(self) -> Result<TPMS_RSA_PARMS> {
        if self.restricted && self.for_decryption {
            if self.symmetric.is_none() {
                return Err(Error::local_error(WrapperErrorKind::ParamsMissing));
            }
        } else if self.symmetric.is_some() {
            return Err(Error::local_error(WrapperErrorKind::InconsistentParams));
        }
        let symmetric = self.symmetric.unwrap_or_else(|| {
            let mut def: TPMT_SYM_DEF_OBJECT = Default::default();
            def.algorithm = TPM2_ALG_NULL;

            def
        });

        let scheme = self
            .scheme
            .ok_or_else(|| Error::local_error(WrapperErrorKind::ParamsMissing))?
            .get_rsa_scheme_struct();
        if self.restricted {
            if self.for_signing
                && scheme.scheme != TPM2_ALG_RSAPSS
                && scheme.scheme != TPM2_ALG_RSASSA
            {
                return Err(Error::local_error(WrapperErrorKind::InconsistentParams));
            }

            if self.for_decryption && scheme.scheme != TPM2_ALG_NULL {
                return Err(Error::local_error(WrapperErrorKind::InconsistentParams));
            }
        } else {
            if self.for_decryption && self.for_signing && scheme.scheme != TPM2_ALG_NULL {
                return Err(Error::local_error(WrapperErrorKind::InconsistentParams));
            }
            if self.for_signing
                && scheme.scheme != TPM2_ALG_RSAPSS
                && scheme.scheme != TPM2_ALG_RSASSA
                && scheme.scheme != TPM2_ALG_NULL
            {
                return Err(Error::local_error(WrapperErrorKind::InconsistentParams));
            }

            if self.for_decryption
                && scheme.scheme != TPM2_ALG_RSAES
                && scheme.scheme != TPM2_ALG_OAEP
                && scheme.scheme != TPM2_ALG_NULL
            {
                return Err(Error::local_error(WrapperErrorKind::InconsistentParams));
            }
        }
        Ok(TPMS_RSA_PARMS {
            symmetric,
            scheme,
            keyBits: self.key_bits,
            exponent: self.exponent,
        })
    }
}

/// Supported sizes for RSA key modulus
pub const RSA_KEY_SIZES: [u16; 4] = [1024, 2048, 3072, 4096];

/// Builder for `TPMS_ECC_PARMS` values.
#[derive(Copy, Clone, Debug)]
pub struct TpmsEccParmsBuilder {
    /// Symmetric cipher to be used in conjuction with the key
    pub symmetric: Option<Cipher>,
    /// Asymmetric scheme to be used for key operations
    pub scheme: AsymSchemeUnion,
    /// Curve to be used with the key
    pub curve: EllipticCurve,
    /// Flag indicating whether the key shall be used for signing
    pub for_signing: bool,
    /// Flag indicating whether the key shall be used for decryption
    pub for_decryption: bool,
    /// Flag indicating whether the key is restricted
    pub restricted: bool,
}

impl TpmsEccParmsBuilder {
    /// Create parameters for a restricted decryption key (i.e. a storage key)
    pub fn new_restricted_decryption_key(symmetric: Cipher, curve: EllipticCurve) -> Self {
        TpmsEccParmsBuilder {
            symmetric: Some(symmetric),
            scheme: AsymSchemeUnion::AnySig(None),
            curve,
            for_signing: false,
            for_decryption: true,
            restricted: true,
        }
    }

    /// Create parameters for an unrestricted signing key
    pub fn new_unrestricted_signing_key(scheme: AsymSchemeUnion, curve: EllipticCurve) -> Self {
        TpmsEccParmsBuilder {
            symmetric: None,
            scheme,
            curve,
            for_signing: true,
            for_decryption: false,
            restricted: false,
        }
    }

    /// Build an object given the previously provded parameters.
    ///
    /// The only mandatory parameters are the asymmetric scheme and the elliptic curve.
    ///
    /// # Errors
    /// * if no asymmetric scheme is set, `ParamsMissing` wrapper error is returned.
    /// * if the `for_signing`, `for_decryption` and `restricted` parameters are
    /// inconsistent with the rest of the parameters, `InconsistentParams` wrapper
    /// error is returned
    pub fn build(self) -> Result<TPMS_ECC_PARMS> {
        if self.restricted && self.for_decryption {
            if self.symmetric.is_none() {
                return Err(Error::local_error(WrapperErrorKind::ParamsMissing));
            }
        } else if self.symmetric.is_some() {
            return Err(Error::local_error(WrapperErrorKind::InconsistentParams));
        }
        if self.for_decryption && self.for_signing {
            return Err(Error::local_error(WrapperErrorKind::InconsistentParams));
        }

        let scheme = self.scheme.get_ecc_scheme_struct();
        if self.for_signing
            && scheme.scheme != TPM2_ALG_ECDSA
            && scheme.scheme != TPM2_ALG_ECDAA
            && scheme.scheme != TPM2_ALG_SM2
            && scheme.scheme != TPM2_ALG_ECSCHNORR
        {
            return Err(Error::local_error(WrapperErrorKind::InconsistentParams));
        }

        if self.for_decryption
            && scheme.scheme != TPM2_ALG_SM2
            && scheme.scheme != TPM2_ALG_ECDH
            && scheme.scheme != TPM2_ALG_ECMQV
            && scheme.scheme != TPM2_ALG_NULL
        {
            return Err(Error::local_error(WrapperErrorKind::InconsistentParams));
        }

        if (self.curve == EllipticCurve::BnP256 || self.curve == EllipticCurve::BnP638)
            && scheme.scheme != TPM2_ALG_ECDAA
        {
            return Err(Error::local_error(WrapperErrorKind::InconsistentParams));
        }

        let symmetric = match self.symmetric {
            Some(symmetric) => symmetric.into(),
            None => {
                let mut def: TPMT_SYM_DEF_OBJECT = Default::default();
                def.algorithm = TPM2_ALG_NULL;
                def
            }
        };

        Ok(TPMS_ECC_PARMS {
            symmetric,
            scheme,
            curveID: self.curve.into(),
            kdf: TPMT_KDF_SCHEME {
                scheme: TPM2_ALG_NULL,
                details: Default::default(),
            },
        })
    }
}

/// Builder for `TPMT_SYM_DEF` objects.
#[derive(Copy, Clone, Debug)]
pub struct TpmtSymDefBuilder {
    algorithm: Option<TPM2_ALG_ID>,
    key_bits: u16,
    mode: TPM2_ALG_ID,
}

impl TpmtSymDefBuilder {
    /// Create a new builder with default (i.e. empty or null) placeholder values.
    pub fn new() -> Self {
        TpmtSymDefBuilder {
            algorithm: None,
            key_bits: 0,
            mode: TPM2_ALG_NULL,
        }
    }

    /// Set the symmetric algorithm.
    pub fn with_algorithm(mut self, algorithm: TPM2_ALG_ID) -> Self {
        self.algorithm = Some(algorithm);
        self
    }

    /// Set the key length.
    pub fn with_key_bits(mut self, key_bits: TPM2_KEY_BITS) -> Self {
        self.key_bits = key_bits;
        self
    }

    /// Set the hash algorithm (applies when the symmetric algorithm is XOR).
    pub fn with_hash(mut self, hash: TPM2_ALG_ID) -> Self {
        self.key_bits = hash;
        self
    }

    /// Set the mode of the symmetric algorithm.
    pub fn with_mode(mut self, mode: TPM2_ALG_ID) -> Self {
        self.mode = mode;
        self
    }

    /// Build a TPMT_SYM_DEF given the previously provided parameters.
    ///
    /// # Errors
    /// * if an unrecognized symmetric algorithm type was set, `UnsupportedParam` wrapper error
    /// is returned.
    /// * if an algorithm is not explicitly set, `ParamsMissing` is returned
    pub fn build(self) -> Result<TPMT_SYM_DEF> {
        let (key_bits, mode) = self.bits_and_mode()?;

        Ok(TPMT_SYM_DEF {
            algorithm: self.algorithm.unwrap(), // bits_and_mode would return an Err if algorithm was missing
            keyBits: key_bits,
            mode,
        })
    }

    /// Build a TPMT_SYM_DEF_OBJECT given the previously provided parameters.
    ///
    /// # Errors
    /// * if an unrecognized symmetric algorithm type was set, `UnsupportedParam` wrapper error
    /// is returned.
    /// * if an algorithm is not explicitly set, `ParamsMissing` is returned
    pub fn build_object(self) -> Result<TPMT_SYM_DEF_OBJECT> {
        let (key_bits, mode) = self.bits_and_mode()?;

        Ok(TPMT_SYM_DEF_OBJECT {
            algorithm: self.algorithm.unwrap(), // bits_and_mode would return an Err if algorithm was missing
            keyBits: key_bits,
            mode,
        })
    }

    fn bits_and_mode(self) -> Result<(TPMU_SYM_KEY_BITS, TPMU_SYM_MODE)> {
        let key_bits;
        let mode;
        match self.algorithm {
            Some(TPM2_ALG_XOR) => {
                // Exclusive OR
                key_bits = TPMU_SYM_KEY_BITS {
                    exclusiveOr: self.key_bits,
                };
                mode = Default::default(); // NULL
            }
            Some(TPM2_ALG_AES) => {
                // AES
                key_bits = TPMU_SYM_KEY_BITS { aes: self.key_bits };
                mode = TPMU_SYM_MODE { aes: self.mode };
            }
            Some(TPM2_ALG_SM4) => {
                // SM4
                key_bits = TPMU_SYM_KEY_BITS { sm4: self.key_bits };
                mode = TPMU_SYM_MODE { sm4: self.mode };
            }
            Some(TPM2_ALG_CAMELLIA) => {
                // CAMELLIA
                key_bits = TPMU_SYM_KEY_BITS {
                    camellia: self.key_bits,
                };
                mode = TPMU_SYM_MODE {
                    camellia: self.mode,
                };
            }
            Some(TPM2_ALG_NULL) => {
                // NULL
                key_bits = Default::default();
                mode = Default::default();
            }
            None => return Err(Error::local_error(WrapperErrorKind::ParamsMissing)),
            _ => return Err(Error::local_error(WrapperErrorKind::UnsupportedParam)),
        }

        Ok((key_bits, mode))
    }
}

impl Default for TpmtSymDefBuilder {
    fn default() -> Self {
        TpmtSymDefBuilder::new()
    }
}

bitfield! {
    pub struct ObjectAttributes(TPMA_OBJECT);
    impl Debug;
    // Object attribute flags
    pub fixed_tpm, set_fixed_tpm: 1;
    pub st_clear, set_st_clear: 2;
    pub fixed_parent, set_fixed_parent: 4;
    pub sensitive_data_origin, set_sensitive_data_origin: 5;
    pub user_with_auth, set_user_with_auth: 6;
    pub admin_with_policy, set_admin_with_policy: 7;
    pub no_da, set_no_da: 10;
    pub encrypted_duplication, set_encrypted_duplication: 11;
    pub restricted, set_restricted: 16;
    pub decrypt, set_decrypt: 17;
    pub sign_encrypt, set_sign_encrypt: 18;
}

impl ObjectAttributes {
    pub fn new_fixed_parent_key() -> Self {
        let mut attrs = ObjectAttributes(0);
        attrs.set_fixed_tpm(true);
        attrs.set_fixed_parent(true);
        attrs.set_sensitive_data_origin(true);
        attrs.set_user_with_auth(true);
        attrs.set_decrypt(true);
        attrs.set_restricted(true);
        attrs
    }

    pub fn new_fixed_signing_key() -> Self {
        let mut attrs = ObjectAttributes(0);
        attrs.set_fixed_tpm(true);
        attrs.set_fixed_parent(true);
        attrs.set_sensitive_data_origin(true);
        attrs.set_user_with_auth(true);
        attrs.set_sign_encrypt(true);

        attrs
    }
}

/// Rust enum representation of `TPMU_PUBLIC_ID`.
// Most of the field types are from bindgen which does not implement Debug on them.
#[allow(missing_debug_implementations)]
pub enum PublicIdUnion {
    KeyedHash(TPM2B_DIGEST),
    Sym(TPM2B_DIGEST),
    Rsa(Box<TPM2B_PUBLIC_KEY_RSA>),
    Ecc(Box<TPMS_ECC_POINT>),
}

impl PublicIdUnion {
    /// Extract a `PublicIdUnion` from a `TPM2B_PUBLIC` object.
    ///
    /// # Constraints
    /// * the value of `public.publicArea.type_` *MUST* be consistent with the union field used in
    /// `public.publicArea.unique`.
    ///
    /// # Safety
    ///
    /// Check "Notes on code safety" section in the crate-level documentation.
    pub unsafe fn from_public(public: &TPM2B_PUBLIC) -> Result<Self> {
        match public.publicArea.type_ {
            TPM2_ALG_RSA => Ok(PublicIdUnion::Rsa(Box::from(public.publicArea.unique.rsa))),
            TPM2_ALG_ECC => Ok(PublicIdUnion::Ecc(Box::from(public.publicArea.unique.ecc))),
            TPM2_ALG_SYMCIPHER => Err(Error::local_error(WrapperErrorKind::UnsupportedParam)),
            TPM2_ALG_KEYEDHASH => Err(Error::local_error(WrapperErrorKind::UnsupportedParam)),
            _ => Err(Error::local_error(WrapperErrorKind::UnsupportedParam)),
        }
    }
}

/// Rust enum representation of `TPMU_PUBLIC_PARMS`.
// Most of the field types are from bindgen which does not implement Debug on them.
#[allow(missing_debug_implementations)]
#[allow(clippy::pub_enum_variant_names)]
#[derive(Copy, Clone)]
pub enum PublicParmsUnion {
    KeyedHashDetail(TPMS_KEYEDHASH_PARMS),
    SymDetail(Cipher),
    RsaDetail(TPMS_RSA_PARMS),
    EccDetail(TPMS_ECC_PARMS),
    AsymDetail(TPMS_ASYM_PARMS),
}

impl PublicParmsUnion {
    /// Get the object type corresponding to the value's variant.
    pub fn object_type(&self) -> TPMI_ALG_PUBLIC {
        match self {
            PublicParmsUnion::AsymDetail(..) => TPM2_ALG_NULL,
            PublicParmsUnion::EccDetail(..) => TPM2_ALG_ECC,
            PublicParmsUnion::RsaDetail(..) => TPM2_ALG_RSA,
            PublicParmsUnion::SymDetail(..) => TPM2_ALG_SYMCIPHER,
            PublicParmsUnion::KeyedHashDetail(..) => TPM2_ALG_KEYEDHASH,
        }
    }
}

impl From<PublicParmsUnion> for TPMU_PUBLIC_PARMS {
    fn from(parms: PublicParmsUnion) -> Self {
        match parms {
            PublicParmsUnion::AsymDetail(tss_parms) => TPMU_PUBLIC_PARMS {
                asymDetail: tss_parms,
            },
            PublicParmsUnion::EccDetail(tss_parms) => TPMU_PUBLIC_PARMS {
                eccDetail: tss_parms,
            },
            PublicParmsUnion::RsaDetail(tss_parms) => TPMU_PUBLIC_PARMS {
                rsaDetail: tss_parms,
            },
            PublicParmsUnion::SymDetail(cipher) => TPMU_PUBLIC_PARMS {
                symDetail: cipher.into(),
            },
            PublicParmsUnion::KeyedHashDetail(tss_parms) => TPMU_PUBLIC_PARMS {
                keyedHashDetail: tss_parms,
            },
        }
    }
}

/// Rust enum representation of `TPMU_ASYM_SCHEME`.
#[derive(Copy, Clone, Debug)]
pub enum AsymSchemeUnion {
    ECDH(HashingAlgorithm),
    ECMQV(HashingAlgorithm),
    RSASSA(HashingAlgorithm),
    RSAPSS(HashingAlgorithm),
    ECDSA(HashingAlgorithm),
    ECDAA(HashingAlgorithm, u16),
    SM2(HashingAlgorithm),
    ECSchnorr(HashingAlgorithm),
    RSAES,
    RSAOAEP(HashingAlgorithm),
    AnySig(Option<HashingAlgorithm>),
}

impl AsymSchemeUnion {
    /// Get scheme ID.
    pub fn scheme_id(self) -> TPM2_ALG_ID {
        match self {
            AsymSchemeUnion::ECDH(_) => TPM2_ALG_ECDH,
            AsymSchemeUnion::ECMQV(_) => TPM2_ALG_ECMQV,
            AsymSchemeUnion::RSASSA(_) => TPM2_ALG_RSASSA,
            AsymSchemeUnion::RSAPSS(_) => TPM2_ALG_RSAPSS,
            AsymSchemeUnion::ECDSA(_) => TPM2_ALG_ECDSA,
            AsymSchemeUnion::ECDAA(_, _) => TPM2_ALG_ECDAA,
            AsymSchemeUnion::SM2(_) => TPM2_ALG_SM2,
            AsymSchemeUnion::ECSchnorr(_) => TPM2_ALG_ECSCHNORR,
            AsymSchemeUnion::RSAES => TPM2_ALG_RSAES,
            AsymSchemeUnion::RSAOAEP(_) => TPM2_ALG_OAEP,
            AsymSchemeUnion::AnySig(_) => TPM2_ALG_NULL,
        }
    }

    fn get_details(self) -> TPMU_ASYM_SCHEME {
        match self {
            AsymSchemeUnion::ECDH(hash_alg) => TPMU_ASYM_SCHEME {
                ecdh: TPMS_SCHEME_HASH {
                    hashAlg: hash_alg.into(),
                },
            },
            AsymSchemeUnion::ECMQV(hash_alg) => TPMU_ASYM_SCHEME {
                ecmqv: TPMS_SCHEME_HASH {
                    hashAlg: hash_alg.into(),
                },
            },
            AsymSchemeUnion::RSASSA(hash_alg) => TPMU_ASYM_SCHEME {
                rsassa: TPMS_SCHEME_HASH {
                    hashAlg: hash_alg.into(),
                },
            },
            AsymSchemeUnion::RSAPSS(hash_alg) => TPMU_ASYM_SCHEME {
                rsapss: TPMS_SCHEME_HASH {
                    hashAlg: hash_alg.into(),
                },
            },
            AsymSchemeUnion::ECDSA(hash_alg) => TPMU_ASYM_SCHEME {
                ecdsa: TPMS_SCHEME_HASH {
                    hashAlg: hash_alg.into(),
                },
            },
            AsymSchemeUnion::ECDAA(hash_alg, count) => TPMU_ASYM_SCHEME {
                ecdaa: TPMS_SCHEME_ECDAA {
                    hashAlg: hash_alg.into(),
                    count,
                },
            },
            AsymSchemeUnion::SM2(hash_alg) => TPMU_ASYM_SCHEME {
                sm2: TPMS_SCHEME_HASH {
                    hashAlg: hash_alg.into(),
                },
            },
            AsymSchemeUnion::ECSchnorr(hash_alg) => TPMU_ASYM_SCHEME {
                ecschnorr: TPMS_SCHEME_HASH {
                    hashAlg: hash_alg.into(),
                },
            },
            AsymSchemeUnion::RSAES => TPMU_ASYM_SCHEME {
                rsaes: Default::default(),
            },
            AsymSchemeUnion::RSAOAEP(hash_alg) => TPMU_ASYM_SCHEME {
                oaep: TPMS_SCHEME_HASH {
                    hashAlg: hash_alg.into(),
                },
            },
            AsymSchemeUnion::AnySig(hash_alg) => TPMU_ASYM_SCHEME {
                anySig: TPMS_SCHEME_HASH {
                    hashAlg: hash_alg.map(u16::from).or(Some(TPM2_ALG_NULL)).unwrap(),
                },
            },
        }
    }

    /// Convert scheme object to `TPMT_RSA_SCHEME`.
    fn get_rsa_scheme_struct(self) -> TPMT_RSA_SCHEME {
        let scheme = self.scheme_id();
        let details = self.get_details();

        TPMT_RSA_SCHEME { scheme, details }
    }

    /// Convert scheme object to `TPMT_RSA_DECRYPT`.
    pub fn get_rsa_decrypt_struct(self) -> TPMT_RSA_DECRYPT {
        let scheme = self.scheme_id();
        let details = self.get_details();

        TPMT_RSA_DECRYPT { scheme, details }
    }

    /// Convert scheme object to `TPMT_ECC_SCHEME`.
    fn get_ecc_scheme_struct(self) -> TPMT_ECC_SCHEME {
        let scheme = self.scheme_id();
        let details = self.get_details();

        TPMT_ECC_SCHEME { scheme, details }
    }

    pub fn is_signing(self) -> bool {
        match self {
            AsymSchemeUnion::ECDH(_)
            | AsymSchemeUnion::ECMQV(_)
            | AsymSchemeUnion::RSAOAEP(_)
            | AsymSchemeUnion::RSAES => false,
            AsymSchemeUnion::RSASSA(_)
            | AsymSchemeUnion::RSAPSS(_)
            | AsymSchemeUnion::ECDSA(_)
            | AsymSchemeUnion::ECDAA(_, _)
            | AsymSchemeUnion::SM2(_)
            | AsymSchemeUnion::ECSchnorr(_)
            | AsymSchemeUnion::AnySig(_) => true,
        }
    }

    pub fn is_decryption(self) -> bool {
        match self {
            AsymSchemeUnion::ECDH(_)
            | AsymSchemeUnion::ECMQV(_)
            | AsymSchemeUnion::RSAOAEP(_)
            | AsymSchemeUnion::RSAES => true,
            AsymSchemeUnion::RSASSA(_)
            | AsymSchemeUnion::RSAPSS(_)
            | AsymSchemeUnion::ECDSA(_)
            | AsymSchemeUnion::ECDAA(_, _)
            | AsymSchemeUnion::SM2(_)
            | AsymSchemeUnion::ECSchnorr(_)
            | AsymSchemeUnion::AnySig(_) => false,
        }
    }

    pub fn is_rsa(self) -> bool {
        match self {
            AsymSchemeUnion::RSASSA(_)
            | AsymSchemeUnion::RSAOAEP(_)
            | AsymSchemeUnion::RSAPSS(_)
            | AsymSchemeUnion::AnySig(_)
            | AsymSchemeUnion::RSAES => true,
            AsymSchemeUnion::ECDH(_)
            | AsymSchemeUnion::ECMQV(_)
            | AsymSchemeUnion::ECDSA(_)
            | AsymSchemeUnion::ECDAA(_, _)
            | AsymSchemeUnion::SM2(_)
            | AsymSchemeUnion::ECSchnorr(_) => false,
        }
    }

    pub fn is_ecc(self) -> bool {
        match self {
            AsymSchemeUnion::RSASSA(_)
            | AsymSchemeUnion::RSAOAEP(_)
            | AsymSchemeUnion::RSAPSS(_)
            | AsymSchemeUnion::AnySig(_)
            | AsymSchemeUnion::RSAES => false,
            AsymSchemeUnion::ECDH(_)
            | AsymSchemeUnion::ECMQV(_)
            | AsymSchemeUnion::ECDSA(_)
            | AsymSchemeUnion::ECDAA(_, _)
            | AsymSchemeUnion::SM2(_)
            | AsymSchemeUnion::ECSchnorr(_) => true,
        }
    }
}

/// Rust native representation of an asymmetric signature.
///
/// The structure contains the signature as a byte vector and the scheme with which the signature
/// was created.
#[derive(Debug)]
pub struct Signature {
    pub scheme: AsymSchemeUnion,
    pub signature: SignatureData,
}

#[derive(Debug, PartialEq, Zeroize)]
#[zeroize(drop)]
pub enum SignatureData {
    RsaSignature(Vec<u8>),
    EcdsaSignature { r: Vec<u8>, s: Vec<u8> },
}

impl Signature {
    /// Attempt to parse a signature from a `TPMT_SIGNATURE` object.
    ///
    /// # Constraints
    /// * the value of `tss_signature.sigAlg` *MUST* be consistent with the union field used in
    /// `tss_signature.signature`
    ///
    /// # Safety
    ///
    /// Check "Notes on code safety" section in the crate-level documentation.
    pub unsafe fn try_from(tss_signature: TPMT_SIGNATURE) -> Result<Self> {
        match tss_signature.sigAlg {
            TPM2_ALG_RSASSA => {
                let hash_alg = tss_signature.signature.rsassa.hash;
                let scheme = AsymSchemeUnion::RSASSA(hash_alg.try_into()?);
                let signature_buf = tss_signature.signature.rsassa.sig;
                let mut signature = signature_buf.buffer.to_vec();
                let buf_size = signature_buf.size.into();
                if buf_size > signature.len() {
                    return Err(Error::local_error(WrapperErrorKind::InconsistentParams));
                }
                signature.truncate(buf_size);

                Ok(Signature {
                    scheme,
                    signature: SignatureData::RsaSignature(signature),
                })
            }
            TPM2_ALG_RSAPSS => {
                let hash_alg = tss_signature.signature.rsapss.hash;
                let scheme = AsymSchemeUnion::RSAPSS(hash_alg.try_into()?);
                let signature_buf = tss_signature.signature.rsassa.sig;
                let mut signature = signature_buf.buffer.to_vec();
                let buf_size = signature_buf.size.into();
                if buf_size > signature.len() {
                    return Err(Error::local_error(WrapperErrorKind::InconsistentParams));
                }
                signature.truncate(buf_size);

                Ok(Signature {
                    scheme,
                    signature: SignatureData::RsaSignature(signature),
                })
            }
            TPM2_ALG_ECDSA => {
                let hash_alg = tss_signature.signature.ecdsa.hash;
                let scheme = AsymSchemeUnion::ECDSA(hash_alg.try_into()?);
                let buf = tss_signature.signature.ecdsa.signatureR;
                let mut r = buf.buffer.to_vec();
                let buf_size = buf.size.into();
                if buf_size > r.len() {
                    return Err(Error::local_error(WrapperErrorKind::InconsistentParams));
                }
                r.truncate(buf_size);

                let buf = tss_signature.signature.ecdsa.signatureS;
                let mut s = buf.buffer.to_vec();
                let buf_size = buf.size.into();
                if buf_size > s.len() {
                    return Err(Error::local_error(WrapperErrorKind::InconsistentParams));
                }
                s.truncate(buf_size);

                Ok(Signature {
                    scheme,
                    signature: SignatureData::EcdsaSignature { r, s },
                })
            }
            TPM2_ALG_SM2 | TPM2_ALG_ECSCHNORR | TPM2_ALG_ECDAA => {
                Err(Error::local_error(WrapperErrorKind::UnsupportedParam))
            }
            _ => Err(Error::local_error(WrapperErrorKind::InconsistentParams)),
        }
    }
}

impl TryFrom<Signature> for TPMT_SIGNATURE {
    type Error = Error;
    fn try_from(sig: Signature) -> Result<Self> {
        if sig.scheme.is_decryption() {
            return Err(Error::local_error(WrapperErrorKind::InconsistentParams));
        }
        match sig.scheme {
            AsymSchemeUnion::RSASSA(hash_alg) => {
                let signature = match sig.signature {
                    SignatureData::RsaSignature(signature) => signature,
                    SignatureData::EcdsaSignature { .. } => {
                        return Err(Error::local_error(WrapperErrorKind::InconsistentParams))
                    }
                };

                let len = signature.len();
                if len > 512 {
                    return Err(Error::local_error(WrapperErrorKind::WrongParamSize));
                }

                let mut buffer = [0_u8; 512];
                buffer[..len].clone_from_slice(&signature[..len]);
                Ok(TPMT_SIGNATURE {
                    sigAlg: TPM2_ALG_RSASSA,
                    signature: TPMU_SIGNATURE {
                        rsassa: TPMS_SIGNATURE_RSA {
                            hash: hash_alg.into(),
                            sig: TPM2B_PUBLIC_KEY_RSA {
                                size: len.try_into().expect("Failed to convert length to u16"), // Should never panic as per the check above
                                buffer,
                            },
                        },
                    },
                })
            }
            AsymSchemeUnion::RSAPSS(hash_alg) => {
                let signature = match sig.signature {
                    SignatureData::RsaSignature(signature) => signature,
                    SignatureData::EcdsaSignature { .. } => {
                        return Err(Error::local_error(WrapperErrorKind::InconsistentParams))
                    }
                };

                let len = signature.len();
                if len > 512 {
                    return Err(Error::local_error(WrapperErrorKind::WrongParamSize));
                }

                let mut buffer = [0_u8; 512];
                buffer[..len].clone_from_slice(&signature[..len]);
                Ok(TPMT_SIGNATURE {
                    sigAlg: TPM2_ALG_RSAPSS,
                    signature: TPMU_SIGNATURE {
                        rsapss: TPMS_SIGNATURE_RSA {
                            hash: hash_alg.into(),
                            sig: TPM2B_PUBLIC_KEY_RSA {
                                size: len.try_into().expect("Failed to convert length to u16"), // Should never panic as per the check above
                                buffer,
                            },
                        },
                    },
                })
            }
            AsymSchemeUnion::ECDSA(hash_alg) => {
                let signature = match sig.signature {
                    SignatureData::EcdsaSignature { r, s } => (r, s),
                    SignatureData::RsaSignature(_) => {
                        return Err(Error::local_error(WrapperErrorKind::InconsistentParams))
                    }
                };

                let r_len = signature.0.len();
                if r_len > 128 {
                    return Err(Error::local_error(WrapperErrorKind::WrongParamSize));
                }

                let mut r_buffer = [0_u8; 128];
                r_buffer[..r_len].clone_from_slice(&signature.0[..r_len]);

                let s_len = signature.1.len();
                if s_len > 128 {
                    return Err(Error::local_error(WrapperErrorKind::WrongParamSize));
                }

                let mut s_buffer = [0_u8; 128];
                s_buffer[..s_len].clone_from_slice(&signature.1[..s_len]);

                Ok(TPMT_SIGNATURE {
                    sigAlg: TPM2_ALG_ECDSA,
                    signature: TPMU_SIGNATURE {
                        ecdsa: TPMS_SIGNATURE_ECDSA {
                            hash: hash_alg.into(),
                            signatureR: TPM2B_ECC_PARAMETER {
                                size: r_len.try_into().expect("Failed to convert length to u16"), // Should never panic as per the check above
                                buffer: r_buffer,
                            },
                            signatureS: TPM2B_ECC_PARAMETER {
                                size: s_len.try_into().expect("Failed to convert length to u16"), // Should never panic as per the check above
                                buffer: s_buffer,
                            },
                        },
                    },
                })
            }
            _ => Err(Error::local_error(WrapperErrorKind::UnsupportedParam)),
        }
    }
}

/// Rust native wrapper for session attributes objects.
#[derive(Copy, Clone, Debug, Default)]
pub struct TpmaSession {
    flags: TPMA_SESSION,
    mask: TPMA_SESSION,
}

impl TpmaSession {
    // Clones the TpmaSession but adds a new mask.
    pub fn clone_with_new_mask(self, new_mask: TPMA_SESSION) -> TpmaSession {
        TpmaSession {
            flags: self.flags,
            mask: new_mask,
        }
    }

    /// Function to retrieve the masks
    /// that have been set.
    pub fn mask(self) -> TPMA_SESSION {
        self.mask
    }

    /// Function to retrive the flags that
    /// gave been set.
    pub fn flags(self) -> TPMA_SESSION {
        self.flags
    }
}

/// A builder for TpmaSession.
///
/// If no mask have been added then the mask
/// will be set till all flags.
#[derive(Copy, Clone, Debug, Default)]
pub struct TpmaSessionBuilder {
    flags: TPMA_SESSION,
    mask: Option<TPMA_SESSION>,
}

impl TpmaSessionBuilder {
    pub fn new() -> TpmaSessionBuilder {
        TpmaSessionBuilder {
            flags: 0,
            mask: None,
        }
    }

    /// Function used to add flags.
    pub fn with_flag(mut self, flag: TPMA_SESSION) -> Self {
        self.flags |= flag;
        self
    }

    /// Function used to add masks.
    pub fn with_mask(mut self, mask: TPMA_SESSION) -> Self {
        self.mask = Some(self.mask.unwrap_or(0) | mask);
        self
    }

    /// Function used to build a TpmaSession
    /// from the parameters that have been
    /// added.
    pub fn build(self) -> TpmaSession {
        TpmaSession {
            flags: self.flags,
            mask: self.mask.unwrap_or(self.flags),
        }
    }
}

/// Rust native wrapper for `TPMS_CONTEXT` objects.
///
/// This structure is intended to help with persisting object contexts. As the main reason for
/// saving the context of an object is to be able to re-use it later, on demand, a serializable
/// structure is most commonly needed. `TpmsContext` implements the `Serialize` and `Deserialize`
/// defined by `serde`.
#[derive(Debug, Serialize, Deserialize, Clone, Zeroize)]
#[zeroize(drop)]
pub struct TpmsContext {
    sequence: u64,
    saved_handle: TPMI_DH_CONTEXT,
    hierarchy: TPMI_RH_HIERARCHY,
    context_blob: Vec<u8>,
}

// TODO: Replace with `From`
impl TryFrom<TPMS_CONTEXT> for TpmsContext {
    type Error = Error;

    fn try_from(tss2_context: TPMS_CONTEXT) -> Result<Self> {
        let mut context = TpmsContext {
            sequence: tss2_context.sequence,
            saved_handle: tss2_context.savedHandle,
            hierarchy: tss2_context.hierarchy,
            context_blob: tss2_context.contextBlob.buffer.to_vec(),
        };
        context.context_blob.truncate(
            tss2_context
                .contextBlob
                .size
                .try_into()
                .map_err(|_| Error::local_error(WrapperErrorKind::WrongParamSize))?,
        );
        Ok(context)
    }
}

#[allow(clippy::needless_update)]
impl TryFrom<TpmsContext> for TPMS_CONTEXT {
    type Error = Error;

    fn try_from(context: TpmsContext) -> Result<Self> {
        let buffer_size = context.context_blob.len();
        if buffer_size > 5188 {
            return Err(Error::local_error(WrapperErrorKind::WrongParamSize));
        }
        let mut buffer = [0_u8; 5188];
        for (i, val) in context.context_blob.iter().enumerate() {
            buffer[i] = *val;
        }
        Ok(TPMS_CONTEXT {
            sequence: context.sequence,
            savedHandle: context.saved_handle,
            hierarchy: context.hierarchy,
            contextBlob: TPM2B_CONTEXT_DATA {
                size: buffer_size.try_into().unwrap(), // should not panic given the check above
                buffer,
            },
            ..Default::default()
        })
    }
}

/// Enum describing the object hierarchies in a TPM 2.0.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Hierarchy {
    Null,
    Owner,
    Platform,
    Endorsement,
}

impl Hierarchy {
    /// Get the ESYS resource handle for the hierarchy.
    pub fn esys_rh(self) -> TPMI_RH_HIERARCHY {
        match self {
            Hierarchy::Null => ESYS_TR_RH_NULL,
            Hierarchy::Owner => ESYS_TR_RH_OWNER,
            Hierarchy::Platform => ESYS_TR_RH_PLATFORM,
            Hierarchy::Endorsement => ESYS_TR_RH_ENDORSEMENT,
        }
    }

    /// Get the TPM resource handle for the hierarchy.
    pub fn rh(self) -> TPM2_RH {
        match self {
            Hierarchy::Null => TPM2_RH_NULL,
            Hierarchy::Owner => TPM2_RH_OWNER,
            Hierarchy::Platform => TPM2_RH_PLATFORM,
            Hierarchy::Endorsement => TPM2_RH_ENDORSEMENT,
        }
    }
}

impl TryFrom<TPM2_HANDLE> for Hierarchy {
    type Error = Error;

    fn try_from(handle: TPM2_HANDLE) -> Result<Self> {
        match handle {
            TPM2_RH_NULL | ESYS_TR_RH_NULL => Ok(Hierarchy::Null),
            TPM2_RH_OWNER | ESYS_TR_RH_OWNER => Ok(Hierarchy::Owner),
            TPM2_RH_PLATFORM | ESYS_TR_RH_PLATFORM => Ok(Hierarchy::Platform),
            TPM2_RH_ENDORSEMENT | ESYS_TR_RH_ENDORSEMENT => Ok(Hierarchy::Endorsement),
            _ => Err(Error::local_error(WrapperErrorKind::InconsistentParams)),
        }
    }
}

/// Create the TPM2B_PUBLIC structure for a restricted decryption key.
///
/// * `symmetric` - Cipher to be used for decrypting children of the key
/// * `key_bits` - Size in bits of the decryption key
/// * `pub_exponent` - Public exponent of the RSA key. A value of 0 defaults to 2^16 + 1
pub fn create_restricted_decryption_rsa_public(
    symmetric: Cipher,
    key_bits: u16,
    pub_exponent: u32,
) -> Result<TPM2B_PUBLIC> {
    let rsa_parms = TpmsRsaParmsBuilder::new_restricted_decryption_key(
        symmetric.into(),
        key_bits,
        pub_exponent,
    )
    .build()?;
    let mut object_attributes = ObjectAttributes(0);
    object_attributes.set_fixed_tpm(true);
    object_attributes.set_fixed_parent(true);
    object_attributes.set_sensitive_data_origin(true);
    object_attributes.set_user_with_auth(true);
    object_attributes.set_decrypt(true);
    object_attributes.set_sign_encrypt(false);
    object_attributes.set_restricted(true);

    Tpm2BPublicBuilder::new()
        .with_type(TPM2_ALG_RSA)
        .with_name_alg(TPM2_ALG_SHA256)
        .with_object_attributes(object_attributes)
        .with_parms(PublicParmsUnion::RsaDetail(rsa_parms))
        .build()
}

/// Create the TPM2B_PUBLIC structure for an unrestricted encryption/decryption key.
///
/// * `symmetric` - Cipher to be used for decrypting children of the key
/// * `key_bits` - Size in bits of the decryption key
/// * `pub_exponent` - Public exponent of the RSA key. A value of 0 defaults to 2^16 + 1
pub fn create_unrestricted_encryption_decryption_rsa_public(
    key_bits: u16,
    pub_exponent: u32,
) -> Result<TPM2B_PUBLIC> {
    let rsa_parms = TpmsRsaParmsBuilder {
        symmetric: None,
        scheme: Some(AsymSchemeUnion::AnySig(None)),
        key_bits,
        exponent: pub_exponent,
        for_signing: true,
        for_decryption: true,
        restricted: false,
    }
    .build()
    .unwrap();
    let mut object_attributes = ObjectAttributes(0);
    object_attributes.set_fixed_tpm(true);
    object_attributes.set_fixed_parent(true);
    object_attributes.set_sensitive_data_origin(true);
    object_attributes.set_user_with_auth(true);
    object_attributes.set_decrypt(true);
    object_attributes.set_sign_encrypt(true);
    object_attributes.set_restricted(false);

    Tpm2BPublicBuilder::new()
        .with_type(TPM2_ALG_RSA)
        .with_name_alg(TPM2_ALG_SHA256)
        .with_object_attributes(object_attributes)
        .with_parms(PublicParmsUnion::RsaDetail(rsa_parms))
        .build()
}

/// Create the TPM2B_PUBLIC structure for an RSA unrestricted signing key.
///
/// * `scheme` - Asymmetric scheme to be used for signing
/// * `key_bits` - Size in bits of the decryption key
/// * `pub_exponent` - Public exponent of the RSA key. A value of 0 defaults to 2^16 + 1
pub fn create_unrestricted_signing_rsa_public(
    scheme: AsymSchemeUnion,
    key_bits: u16,
    pub_exponent: u32,
) -> Result<TPM2B_PUBLIC> {
    let rsa_parms =
        TpmsRsaParmsBuilder::new_unrestricted_signing_key(scheme, key_bits, pub_exponent)
            .build()?;
    let mut object_attributes = ObjectAttributes(0);
    object_attributes.set_fixed_tpm(true);
    object_attributes.set_fixed_parent(true);
    object_attributes.set_sensitive_data_origin(true);
    object_attributes.set_user_with_auth(true);
    object_attributes.set_decrypt(false);
    object_attributes.set_sign_encrypt(true);
    object_attributes.set_restricted(false);

    Tpm2BPublicBuilder::new()
        .with_type(TPM2_ALG_RSA)
        .with_name_alg(TPM2_ALG_SHA256)
        .with_object_attributes(object_attributes)
        .with_parms(PublicParmsUnion::RsaDetail(rsa_parms))
        .build()
}

/// Create the TPM2B_PUBLIC structure for an ECC unrestricted signing key.
///
/// * `scheme` - Asymmetric scheme to be used for signing; *must* be an RSA signing scheme
/// * `curve` - identifier of the precise curve to be used with the key
pub fn create_unrestricted_signing_ecc_public(
    scheme: AsymSchemeUnion,
    curve: EllipticCurve,
) -> Result<TPM2B_PUBLIC> {
    let ecc_parms = TpmsEccParmsBuilder::new_unrestricted_signing_key(scheme, curve).build()?;
    let mut object_attributes = ObjectAttributes(0);
    object_attributes.set_fixed_tpm(true);
    object_attributes.set_fixed_parent(true);
    object_attributes.set_sensitive_data_origin(true);
    object_attributes.set_user_with_auth(true);
    object_attributes.set_decrypt(false);
    object_attributes.set_sign_encrypt(true);
    object_attributes.set_restricted(false);

    Tpm2BPublicBuilder::new()
        .with_type(TPM2_ALG_ECC)
        .with_name_alg(TPM2_ALG_SHA256)
        .with_object_attributes(object_attributes)
        .with_parms(PublicParmsUnion::EccDetail(ecc_parms))
        .build()
}

#[derive(Debug, Clone)]
pub enum PublicKey {
    Rsa(Vec<u8>),
    Ecc { x: Vec<u8>, y: Vec<u8> },
}

type PcrValue = Digest;

/// Struct for holding PcrSlots and their
/// corresponding values.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct PcrBank {
    bank: BTreeMap<PcrSlot, PcrValue>,
}

impl PcrBank {
    /// Function for retrieving a pcr value corresponding to a pcr slot.
    pub fn pcr_value(&self, pcr_slot: PcrSlot) -> Option<&PcrValue> {
        self.bank.get(&pcr_slot)
    }

    /// Function for retrieiving the number of pcr slot values in the bank.
    pub fn len(&self) -> usize {
        self.bank.len()
    }

    /// Returns true if there are no pcr slot values in the bank.
    pub fn is_empty(&self) -> bool {
        self.bank.is_empty()
    }
}

impl<'a> IntoIterator for &'a PcrBank {
    type Item = (&'a PcrSlot, &'a PcrValue);
    type IntoIter = ::std::collections::btree_map::Iter<'a, PcrSlot, PcrValue>;

    fn into_iter(self) -> Self::IntoIter {
        self.bank.iter()
    }
}

/// Struct holding pcr banks and their associated
/// hashing algorithm
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PcrData {
    data: HashMap<HashingAlgorithm, PcrBank>,
}

impl PcrData {
    /// Contrustctor that creates a PcrData from
    /// tss types.
    pub fn new(
        tpml_pcr_selections: &TPML_PCR_SELECTION,
        tpml_digests: &TPML_DIGEST,
    ) -> Result<Self> {
        // Check digests
        let digests_count = tpml_digests.count as usize;
        if digests_count > 8 {
            error!("Error: Invalid TPML_DIGEST count(> 8)");
            return Err(Error::local_error(WrapperErrorKind::InvalidParam));
        }
        let digests = &tpml_digests.digests[..digests_count];
        // Check selections
        let selections_count = tpml_pcr_selections.count as usize;
        if selections_count > 16 {
            error!("Error: Invalid TPML_SELECTIONS count(> 16)");
            return Err(Error::local_error(WrapperErrorKind::InvalidParam));
        }
        let pcr_selections = &tpml_pcr_selections.pcrSelections[..selections_count];

        let mut digest_iter = digests.iter();
        let mut parsed_pcr_data = PcrData {
            data: Default::default(),
        };
        for &pcr_selection in pcr_selections {
            // Parse hash algorithm from selection
            let parsed_hash_algorithm =
                HashingAlgorithm::try_from(pcr_selection.hash).map_err(|e| {
                    error!("Error converting hash to a HashingAlgorithm: {}.", e);
                    Error::local_error(WrapperErrorKind::InvalidParam)
                })?;
            // Parse pcr slots from selection
            let parsed_pcr_slots: BitFlags<PcrSlot> =
                BitFlags::<PcrSlot>::try_from(u32::from_le_bytes(pcr_selection.pcrSelect))
                    .map_err(|e| {
                        error!("Error parsing pcrSelect to a BitFlags<PcrSlot>: {}.", e);
                        Error::local_error(WrapperErrorKind::UnsupportedParam)
                    })?;
            // Create PCR bank by mapping the pcr slots to the pcr values
            let mut parsed_pcr_bank = PcrBank {
                bank: Default::default(),
            };
            for pcr_slot in parsed_pcr_slots.iter() {
                // Make sure there are still data
                let digest = match digest_iter.next() {
                    Some(val) => val,
                    None => {
                        error!("Error number of items in selection does not match number of items in data.");
                        return Err(Error::local_error(WrapperErrorKind::InconsistentParams));
                    }
                };
                // Add the value corresponding to the pcr slot.
                if parsed_pcr_bank
                    .bank
                    .insert(pcr_slot, PcrValue::try_from(*digest)?)
                    .is_some()
                {
                    error!("Error trying to insert data into PcrSlot where data have already been inserted.");
                    return Err(Error::local_error(WrapperErrorKind::InconsistentParams));
                }
            }
            // Add the parsed pcr bank for the parsed hashing algorithm.
            if parsed_pcr_data
                .data
                .insert(parsed_hash_algorithm, parsed_pcr_bank)
                .is_some()
            {
                error!("Error trying to insert data into a PcrBank where data have already been inserted.");
                return Err(Error::local_error(WrapperErrorKind::InconsistentParams));
            }
        }
        // Make sure all values in the digest have been read.
        if digest_iter.next().is_some() {
            error!("Error not all values in the digest have been handled.");
            return Err(Error::local_error(WrapperErrorKind::InconsistentParams));
        }

        Ok(parsed_pcr_data)
    }
    /// Function for retriving a bank associated with the hashing_algorithm.
    pub fn pcr_bank(&self, hashing_algorithm: HashingAlgorithm) -> Option<&PcrBank> {
        self.data.get(&hashing_algorithm)
    }

    /// Function for retrieving the number of banks in the data.
    pub fn len(&self) -> usize {
        self.data.len()
    }

    /// Returns true if there are no banks in the data.
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }
}

impl<'a> IntoIterator for &'a PcrData {
    type Item = (&'a HashingAlgorithm, &'a PcrBank);
    type IntoIter = ::std::collections::hash_map::Iter<'a, HashingAlgorithm, PcrBank>;

    fn into_iter(self) -> Self::IntoIter {
        self.data.iter()
    }
}

impl From<PcrData> for TPML_DIGEST {
    fn from(pcr_data: PcrData) -> Self {
        let mut tpml_digest: TPML_DIGEST = Default::default();

        for (_hash_algo, pcr_bank) in pcr_data.into_iter() {
            for (_pcr_slot, pcr_value) in pcr_bank.into_iter() {
                let i = tpml_digest.count as usize;
                let size = pcr_value.value().len() as u16;
                tpml_digest.digests[i].size = size;
                tpml_digest.digests[i].buffer[..size as usize].copy_from_slice(pcr_value.value());
                tpml_digest.count += 1;
            }
        }
        tpml_digest
    }
}