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
// Copyright 2020 Contributors to the Parsec project.
// SPDX-License-Identifier: Apache-2.0

//! # PSA Key types

#![allow(deprecated)]
#[cfg(feature = "with-mbed-crypto")]
use crate::initialized;
#[cfg(feature = "with-mbed-crypto")]
use crate::types::algorithm::AsymmetricSignature;
use crate::types::algorithm::{Algorithm, Cipher};
#[cfg(feature = "with-mbed-crypto")]
use crate::types::status::Status;
use crate::types::status::{Error, Result};
#[cfg(feature = "with-mbed-crypto")]
use core::convert::{TryFrom, TryInto};
use log::error;
pub use psa_crypto_sys::{self, psa_key_id_t, PSA_KEY_ID_USER_MAX, PSA_KEY_ID_USER_MIN};
use serde::{Deserialize, Serialize};

/// Native definition of the attributes needed to fully describe
/// a cryptographic key.
#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Attributes {
    /// Lifetime of the key
    pub lifetime: Lifetime,
    /// Intrinsic category and type of the key
    pub key_type: Type,
    /// Size of the key in bits
    pub bits: usize,
    /// Policy restricting the permitted usage of the key
    pub policy: Policy,
}

impl Attributes {
    /// Check if a key has permission to be exported
    pub fn is_exportable(self) -> bool {
        self.policy.usage_flags.export
    }

    /// Check export in a fallible way
    ///
    /// # Example
    ///
    /// ```
    /// use psa_crypto::types::key::{Attributes, Type, Lifetime, Policy, UsageFlags};
    /// use psa_crypto::types::algorithm::{Algorithm, AsymmetricSignature, Hash};
    ///
    /// let mut attributes = Attributes {
    ///     key_type: Type::RsaKeyPair,
    ///     bits: 1024,
    ///     lifetime: Lifetime::Volatile,
    ///     policy: Policy {
    ///         usage_flags: UsageFlags {
    ///             export: false,
    ///             copy: false,
    ///             cache: false,
    ///             encrypt: false,
    ///             decrypt: false,
    ///             sign_message: false,
    ///             verify_message: false,
    ///             sign_hash: false,
    ///             verify_hash: false,
    ///             derive: false,
    ///         },
    ///         permitted_algorithms: Algorithm::AsymmetricSignature(AsymmetricSignature::RsaPkcs1v15Sign {
    ///             hash_alg: Hash::Sha256.into(),
    ///         }),
    ///     },
    /// };

    /// // Can not export because the export flag is set to false.
    /// attributes.can_export().unwrap_err();
    /// ```
    pub fn can_export(self) -> Result<()> {
        if self.is_exportable() {
            Ok(())
        } else {
            error!("Key attributes do not permit exporting key.");
            Err(Error::NotPermitted)
        }
    }

    /// Check if a key has permission to sign a message hash
    pub fn is_hash_signable(self) -> bool {
        self.policy.usage_flags.sign_hash
    }

    /// Check hash signing permission in a fallible way
    pub fn can_sign_hash(self) -> Result<()> {
        if self.is_hash_signable() {
            Ok(())
        } else {
            error!("Key attributes do not permit signing hashes.");
            Err(Error::NotPermitted)
        }
    }

    /// Check if a key has permission to verify a message hash
    pub fn is_hash_verifiable(self) -> bool {
        self.policy.usage_flags.verify_hash
    }

    /// Check hash signing permission in a fallible way
    pub fn can_verify_hash(self) -> Result<()> {
        if self.is_hash_verifiable() {
            Ok(())
        } else {
            error!("Key attributes do not permit verifying hashes.");
            Err(Error::NotPermitted)
        }
    }

    /// Check if the alg given for a cryptographic operation is permitted to be used with the key
    pub fn is_alg_permitted(self, alg: Algorithm) -> bool {
        match self.policy.permitted_algorithms {
            Algorithm::None => false,
            Algorithm::AsymmetricSignature(asymmetric_signature_alg_policy) => {
                if let Algorithm::AsymmetricSignature(asymmetric_signature_alg) = alg {
                    asymmetric_signature_alg_policy.is_alg_permitted(asymmetric_signature_alg)
                } else {
                    false
                }
            }
            // These ones can not be wildcard algorithms: it is sufficient to just check for
            // equality.
            permitted_alg => permitted_alg == alg,
        }
    }

    /// Check if alg is permitted in a fallible way
    pub fn permits_alg(self, alg: Algorithm) -> Result<()> {
        if self.is_alg_permitted(alg) {
            Ok(())
        } else {
            error!("Key attributes do not permit specified algorithm.");
            Err(Error::NotPermitted)
        }
    }

    /// Check if the alg given for a cryptographic operation is compatible with the type of the
    /// key
    ///
    /// # Example
    ///
    /// ```
    /// use psa_crypto::types::key::{Attributes, Type, Lifetime, Policy, UsageFlags};
    /// use psa_crypto::types::algorithm::{Algorithm, AsymmetricSignature, Hash};
    ///
    /// let permitted_alg = Algorithm::AsymmetricSignature(AsymmetricSignature::RsaPkcs1v15Sign {
    ///     hash_alg: Hash::Sha256.into(),
    /// });
    /// let alg = Algorithm::AsymmetricSignature(AsymmetricSignature::RsaPkcs1v15Sign {
    ///     hash_alg: Hash::Sha256.into(),
    /// });
    /// let mut attributes = Attributes {
    ///     key_type: Type::RsaKeyPair,
    ///     bits: 1024,
    ///     lifetime: Lifetime::Volatile,
    ///     policy: Policy {
    ///         usage_flags: UsageFlags {
    ///             export: false,
    ///             copy: false,
    ///             cache: false,
    ///             encrypt: false,
    ///             decrypt: false,
    ///             sign_message: false,
    ///             verify_message: false,
    ///             sign_hash: false,
    ///             verify_hash: false,
    ///             derive: false,
    ///         },
    ///         permitted_algorithms: permitted_alg,
    ///     },
    /// };

    /// assert!(attributes.is_compatible_with_alg(alg));
    /// attributes.key_type = Type::RsaPublicKey;
    /// assert!(attributes.is_compatible_with_alg(alg));
    /// ```
    pub fn is_compatible_with_alg(self, alg: Algorithm) -> bool {
        match self.key_type {
            Type::RawData => false,
            Type::Hmac => alg.is_hmac(),
            Type::Derive => {
                if let Algorithm::KeyDerivation(_) = alg {
                    true
                } else {
                    false
                }
            }
            Type::Aes | Type::Camellia => {
                if let Algorithm::Mac(mac_alg) = alg {
                    mac_alg.is_block_cipher_needed()
                } else if let Algorithm::Cipher(cipher_alg) = alg {
                    cipher_alg.is_block_cipher_mode()
                } else if let Algorithm::Aead(aead_alg) = alg {
                    aead_alg.is_aead_on_block_cipher()
                } else {
                    false
                }
            }
            Type::Des => {
                if let Algorithm::Mac(mac_alg) = alg {
                    mac_alg.is_block_cipher_needed()
                } else if let Algorithm::Cipher(cipher_alg) = alg {
                    cipher_alg.is_block_cipher_mode()
                } else {
                    false
                }
            }
            Type::Arc4 => alg == Algorithm::Cipher(Cipher::StreamCipher),
            Type::Chacha20 => {
                if alg == Algorithm::Cipher(Cipher::StreamCipher) {
                    true
                } else if let Algorithm::Aead(aead_alg) = alg {
                    aead_alg.is_chacha20_poly1305_alg()
                } else {
                    false
                }
            }
            Type::RsaPublicKey | Type::RsaKeyPair => {
                if let Algorithm::AsymmetricSignature(sign_alg) = alg {
                    sign_alg.is_rsa_alg()
                } else if let Algorithm::AsymmetricEncryption(_) = alg {
                    true
                } else {
                    false
                }
            }
            Type::EccKeyPair { .. } | Type::EccPublicKey { .. } => {
                if let Algorithm::AsymmetricSignature(sign_alg) = alg {
                    sign_alg.is_ecc_alg()
                } else {
                    false
                }
            }
            Type::DhKeyPair { .. } | Type::DhPublicKey { .. } => {
                if let Algorithm::KeyAgreement(_) = alg {
                    true
                } else {
                    false
                }
            }
        }
    }

    /// Check if alg is compatible in a fallible way
    pub fn compatible_with_alg(self, alg: Algorithm) -> Result<()> {
        if self.is_compatible_with_alg(alg) {
            Ok(())
        } else {
            error!("Key attributes are not compatible with specified algorithm.");
            Err(Error::NotPermitted)
        }
    }

    #[cfg(feature = "with-mbed-crypto")]
    pub(crate) fn reset(attributes: &mut psa_crypto_sys::psa_key_attributes_t) {
        unsafe { psa_crypto_sys::psa_reset_key_attributes(attributes) };
    }

    /// Gets the attributes for a given key ID
    ///
    /// The `Id` structure can be created with the `from_persistent_key_id` constructor on `Id`.
    ///
    /// # Example
    ///
    /// ```
    /// # use psa_crypto::operations::key_management;
    /// # use psa_crypto::types::key::{Attributes, Type, Lifetime, Policy, UsageFlags};
    /// # use psa_crypto::types::algorithm::{AsymmetricSignature, Hash};
    /// # let mut attributes = Attributes {
    /// #     key_type: Type::RsaKeyPair,
    /// #     bits: 1024,
    /// #     lifetime: Lifetime::Volatile,
    /// #     policy: Policy {
    /// #         usage_flags: UsageFlags {
    /// #             sign_hash: true,
    /// #             sign_message: true,
    /// #             verify_hash: true,
    /// #             verify_message: true,
    /// #             ..Default::default()
    /// #         },
    /// #         permitted_algorithms: AsymmetricSignature::RsaPkcs1v15Sign {
    /// #             hash_alg: Hash::Sha256.into(),
    /// #         }.into(),
    /// #     },
    /// # };
    /// psa_crypto::init().unwrap();
    /// let my_key_id = key_management::generate(attributes, None).unwrap();
    /// //...
    /// let key_attributes = Attributes::from_key_id(my_key_id);
    /// ```
    #[cfg(feature = "with-mbed-crypto")]
    pub fn from_key_id(key_id: Id) -> Result<Self> {
        initialized()?;
        let mut key_attributes = unsafe { psa_crypto_sys::psa_key_attributes_init() };
        let handle = key_id.handle()?;
        let get_attributes_res = Status::from(unsafe {
            psa_crypto_sys::psa_get_key_attributes(handle, &mut key_attributes)
        })
        .to_result();
        let attributes = Attributes::try_from(key_attributes);
        Attributes::reset(&mut key_attributes);
        key_id.close_handle(handle)?;
        get_attributes_res?;
        Ok(attributes?)
    }

    /// Sufficient size for a buffer to export the key, if supported
    #[cfg(feature = "with-mbed-crypto")]
    pub fn export_key_output_size(self) -> Result<usize> {
        Attributes::export_key_output_size_base(self.key_type, self.bits)
    }

    /// Sufficient size for a buffer to export the public key, if supported
    #[cfg(feature = "with-mbed-crypto")]
    pub fn export_public_key_output_size(self) -> Result<usize> {
        match self.key_type {
            Type::RsaKeyPair
            | Type::RsaPublicKey
            | Type::EccKeyPair { .. }
            | Type::EccPublicKey { .. }
            | Type::DhKeyPair { .. }
            | Type::DhPublicKey { .. } => {
                let pub_type = self.key_type.key_type_public_key_of_key_pair()?;
                Attributes::export_key_output_size_base(pub_type, self.bits)
            }
            _ => Err(Error::InvalidArgument),
        }
    }

    /// Sufficient size for a buffer to export the given key type, if supported
    #[cfg(feature = "with-mbed-crypto")]
    fn export_key_output_size_base(key_type: Type, bits: usize) -> Result<usize> {
        let size =
            unsafe { psa_crypto_sys::PSA_EXPORT_KEY_OUTPUT_SIZE(key_type.try_into()?, bits) };
        if size > 0 {
            Ok(size)
        } else {
            Err(Error::NotSupported)
        }
    }

    /// Sufficient buffer size for a signature using the given key, if the key is supported
    #[cfg(feature = "with-mbed-crypto")]
    pub fn sign_output_size(self, alg: AsymmetricSignature) -> Result<usize> {
        self.compatible_with_alg(Algorithm::AsymmetricSignature(alg))?;
        Ok(unsafe {
            psa_crypto_sys::PSA_SIGN_OUTPUT_SIZE(self.key_type.try_into()?, self.bits, alg.into())
        })
    }
}

/// The lifetime of a key indicates where it is stored and which application and system actions
/// will create and destroy it.
#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Lifetime {
    /// A volatile key only exists as long as the identifier to it is not destroyed.
    Volatile,
    /// A persistent key remains in storage until it is explicitly destroyed or until the
    /// corresponding storage area is wiped.
    Persistent,
    /// Implementations can offer other storage areas designated by other lifetime values as
    /// implementation-specific extensions.
    Custom(u32),
}

/// Enumeration of key types supported.
#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Type {
    /// Not a valid key type for any cryptographic operation but can be used to store arbitrary
    /// data in the key store.
    RawData,
    /// HMAC key.
    Hmac,
    /// A secret key for derivation.
    Derive,
    /// Key for a cipher, AEAD or MAC algorithm based on the AES block cipher.
    Aes,
    /// Key for a cipher or MAC algorithm based on DES or 3DES (Triple-DES).
    Des,
    /// Key for a cipher, AEAD or MAC algorithm based on the Camellia block cipher.
    Camellia,
    /// Key for the RC4 stream cipher.
    Arc4,
    /// Key for the ChaCha20 stream cipher or the Chacha20-Poly1305 AEAD algorithm.
    Chacha20,
    /// RSA public key.
    RsaPublicKey,
    /// RSA key pair: both the private and public key.
    RsaKeyPair,
    /// Elliptic curve key pair: both the private and public key.
    EccKeyPair {
        /// ECC curve family to use.
        curve_family: EccFamily,
    },
    /// Elliptic curve public key.
    EccPublicKey {
        /// ECC curve family to use.
        curve_family: EccFamily,
    },
    /// Diffie-Hellman key pair: both the private key and public key.
    DhKeyPair {
        /// Diffie-Hellman group family to use.
        group_family: DhFamily,
    },
    /// Diffie-Hellman public key.
    DhPublicKey {
        /// Diffie-Hellman group family to use.
        group_family: DhFamily,
    },
}

impl Type {
    /// Checks if a key type is ECC key pair with any curve family inside.
    pub fn is_ecc_key_pair(self) -> bool {
        match self {
            Type::EccKeyPair { .. } => true,
            _ => false,
        }
    }

    /// Checks if a key type is ECC public key with any curve family inside.
    ///
    /// # Example
    ///
    /// ```
    /// use psa_crypto::types::key::{Type, EccFamily};
    ///
    /// assert!(Type::EccPublicKey { curve_family: EccFamily::SecpK1}.is_ecc_public_key());
    /// ```
    pub fn is_ecc_public_key(self) -> bool {
        match self {
            Type::EccPublicKey { .. } => true,
            _ => false,
        }
    }

    /// Checks if a key type is DH public key with any group family inside.
    pub fn is_dh_public_key(self) -> bool {
        match self {
            Type::DhPublicKey { .. } => true,
            _ => false,
        }
    }

    /// Checks if a key type is DH key pair with any group family inside.
    pub fn is_dh_key_pair(self) -> bool {
        match self {
            Type::DhKeyPair { .. } => true,
            _ => false,
        }
    }

    /// If key is public or key pair, returns the corresponding public key type.
    #[cfg(feature = "with-mbed-crypto")]
    pub fn key_type_public_key_of_key_pair(self) -> Result<Type> {
        match self {
            Type::RsaKeyPair
            | Type::RsaPublicKey
            | Type::EccKeyPair { .. }
            | Type::EccPublicKey { .. }
            | Type::DhKeyPair { .. }
            | Type::DhPublicKey { .. } => {
                Ok(
                    unsafe {
                        psa_crypto_sys::PSA_KEY_TYPE_PUBLIC_KEY_OF_KEY_PAIR(self.try_into()?)
                    }
                    .try_into()?,
                )
            }
            _ => Err(Error::InvalidArgument),
        }
    }
}

/// Enumeration of elliptic curve families supported. They are needed to create an ECC key.
/// The specific curve used for each family is given by the `bits` field of the key attributes.
/// See the book for more details.
#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum EccFamily {
    /// SEC Koblitz curves over prime fields.
    /// This family comprises the following curves:
    ///   * secp192k1: `bits` = 192
    ///   * secp224k1: `bits` = 225
    ///   * secp256k1: `bits` = 256
    SecpK1,
    /// SEC random curves over prime fields.
    /// This family comprises the following curves:
    ///   * secp192r1: `bits` = 192
    ///   * secp224r1: `bits` = 224
    ///   * secp256r1: `bits` = 256
    ///   * secp384r1: `bits` = 384
    ///   * secp521r1: `bits` = 512
    SecpR1,
    /// SEC additional random curves over prime fields.
    /// This family comprises the following curves:
    ///   * secp160r2: `bits` = 160 (Deprecated)
    #[deprecated = "This family of curve is weak and deprecated."]
    SecpR2,
    /// SEC Koblitz curves over binary fields.
    /// This family comprises the following curves:
    ///   * sect163k1: `bits` = 163 (DEPRECATED)
    ///   * sect233k1: `bits` = 233
    ///   * sect239k1: `bits` = 239
    ///   * sect283k1: `bits` = 283
    ///   * sect409k1: `bits` = 409
    ///   * sect571k1: `bits` = 571
    SectK1,
    /// SEC random curves over binary fields.
    /// This family comprises the following curves:
    ///   * sect163r1: `bits` = 163 (DEPRECATED)
    ///   * sect233r1: `bits` = 233
    ///   * sect283r1: `bits` = 283
    ///   * sect409r1: `bits` = 409
    ///   * sect571r1: `bits` = 571
    SectR1,
    /// SEC additional random curves over binary fields.
    /// This family comprises the following curves:
    ///   * sect163r2 : bits = 163 (DEPRECATED)
    #[deprecated = "This family of curve is weak and deprecated."]
    SectR2,
    /// Brainpool P random curves.
    /// This family comprises the following curves:
    ///   * brainpoolP160r1: `bits` = 160 (DEPRECATED)
    ///   * brainpoolP192r1: `bits` = 192
    ///   * brainpoolP224r1: `bits` = 224
    ///   * brainpoolP256r1: `bits` = 256
    ///   * brainpoolP320r1: `bits` = 320
    ///   * brainpoolP384r1: `bits` = 384
    ///   * brainpoolP512r1: `bits` = 512
    BrainpoolPR1,
    /// Curve used primarily in France and elsewhere in Europe.
    /// This family comprises one 256-bit curve:
    ///   * FRP256v1: `bits` = 256
    Frp,
    /// Montgomery curves.
    /// This family comprises the following Montgomery curves:
    ///   * Curve25519: `bits` = 255
    ///   * Curve448: `bits` = 448
    Montgomery,
}

/// Enumeration of Diffie Hellman group families supported.
#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum DhFamily {
    /// Diffie-Hellman groups defined in RFC 7919 Appendix A.
    /// This family includes groups with the following `bits`: 2048, 3072, 4096, 6144, 8192.
    /// An implementation can support all of these sizes or only a subset.
    Rfc7919,
}

/// Definition of the key policy, what is permitted to do with the key.
#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Policy {
    /// Usage flags for the key.
    pub usage_flags: UsageFlags,
    /// Permitted algorithms to be used with the key.
    pub permitted_algorithms: Algorithm,
}

/// Definition of the usage flags. They encode what kind of operations are permitted on the key.
#[derive(Copy, Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct UsageFlags {
    /// Permission to export the key.
    pub export: bool,
    /// Permission to copy the key.
    pub copy: bool,
    /// Permission for the implementation to cache the key.
    pub cache: bool,
    /// Permission to encrypt a message with the key.
    pub encrypt: bool,
    /// Permission to decrypt a message with the key.
    pub decrypt: bool,
    /// Permission to sign a message with the key.
    pub sign_message: bool,
    /// Permission to verify a message signature with the key.
    pub verify_message: bool,
    /// Permission to sign a message hash with the key.
    pub sign_hash: bool,
    /// Permission to verify a message hash with the key.
    pub verify_hash: bool,
    /// Permission to derive other keys from this key.
    pub derive: bool,
}

/// Definition of the key ID.
#[cfg(feature = "with-mbed-crypto")]
#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Id {
    pub(crate) id: psa_key_id_t,
    pub(crate) handle: Option<psa_crypto_sys::psa_key_handle_t>,
}

#[cfg(feature = "with-mbed-crypto")]
impl Id {
    pub(crate) fn handle(self) -> Result<psa_crypto_sys::psa_key_handle_t> {
        Ok(match self.handle {
            Some(handle) => handle,
            None => {
                let mut handle = 0;
                Status::from(unsafe { psa_crypto_sys::psa_open_key(self.id, &mut handle) })
                    .to_result()?;

                handle
            }
        })
    }

    pub(crate) fn close_handle(self, handle: psa_crypto_sys::psa_key_handle_t) -> Result<()> {
        if self.handle.is_none() {
            Status::from(unsafe { psa_crypto_sys::psa_close_key(handle) }).to_result()
        } else {
            Ok(())
        }
    }
}

#[cfg(feature = "with-mbed-crypto")]
impl Id {
    /// Create a new Id from a persistent key ID
    pub fn from_persistent_key_id(id: u32) -> Self {
        Id { id, handle: None }
    }
}

#[cfg(feature = "with-mbed-crypto")]
impl TryFrom<Attributes> for psa_crypto_sys::psa_key_attributes_t {
    type Error = Error;
    fn try_from(attributes: Attributes) -> Result<Self> {
        let mut attrs = unsafe { psa_crypto_sys::psa_key_attributes_init() };
        unsafe { psa_crypto_sys::psa_set_key_lifetime(&mut attrs, attributes.lifetime.into()) };
        unsafe {
            psa_crypto_sys::psa_set_key_usage_flags(
                &mut attrs,
                attributes.policy.usage_flags.into(),
            )
        };
        unsafe {
            psa_crypto_sys::psa_set_key_algorithm(
                &mut attrs,
                attributes.policy.permitted_algorithms.try_into()?,
            )
        };
        unsafe { psa_crypto_sys::psa_set_key_type(&mut attrs, attributes.key_type.try_into()?) };
        unsafe { psa_crypto_sys::psa_set_key_bits(&mut attrs, attributes.bits) };

        Ok(attrs)
    }
}

#[cfg(feature = "with-mbed-crypto")]
impl TryFrom<psa_crypto_sys::psa_key_attributes_t> for Attributes {
    type Error = Error;
    fn try_from(attributes: psa_crypto_sys::psa_key_attributes_t) -> Result<Self> {
        Ok(Attributes {
            lifetime: unsafe { psa_crypto_sys::psa_get_key_lifetime(&attributes).into() },
            key_type: unsafe { psa_crypto_sys::psa_get_key_type(&attributes).try_into()? },
            bits: unsafe { psa_crypto_sys::psa_get_key_bits(&attributes) },
            policy: Policy {
                usage_flags: unsafe { psa_crypto_sys::psa_get_key_usage_flags(&attributes).into() },
                permitted_algorithms: unsafe {
                    psa_crypto_sys::psa_get_key_algorithm(&attributes).try_into()?
                },
            },
        })
    }
}

#[cfg(feature = "with-mbed-crypto")]
impl From<Lifetime> for psa_crypto_sys::psa_key_lifetime_t {
    fn from(lifetime: Lifetime) -> Self {
        match lifetime {
            Lifetime::Volatile => psa_crypto_sys::PSA_KEY_LIFETIME_VOLATILE,
            Lifetime::Persistent => psa_crypto_sys::PSA_KEY_LIFETIME_PERSISTENT,
            Lifetime::Custom(value) => value,
        }
    }
}

#[cfg(feature = "with-mbed-crypto")]
impl From<psa_crypto_sys::psa_key_lifetime_t> for Lifetime {
    fn from(lifetime: psa_crypto_sys::psa_key_lifetime_t) -> Self {
        match lifetime {
            psa_crypto_sys::PSA_KEY_LIFETIME_VOLATILE => Lifetime::Volatile,
            psa_crypto_sys::PSA_KEY_LIFETIME_PERSISTENT => Lifetime::Persistent,
            value => Lifetime::Custom(value),
        }
    }
}

#[cfg(feature = "with-mbed-crypto")]
impl From<UsageFlags> for psa_crypto_sys::psa_key_usage_t {
    fn from(flags: UsageFlags) -> Self {
        let mut usage_flags = 0;
        if flags.export {
            usage_flags |= psa_crypto_sys::PSA_KEY_USAGE_EXPORT;
        }
        if flags.encrypt {
            usage_flags |= psa_crypto_sys::PSA_KEY_USAGE_ENCRYPT;
        }
        if flags.decrypt {
            usage_flags |= psa_crypto_sys::PSA_KEY_USAGE_DECRYPT;
        }
        if flags.sign_message && flags.sign_hash {
            usage_flags |= psa_crypto_sys::PSA_KEY_USAGE_SIGN;
        }
        if flags.verify_message && flags.verify_hash {
            usage_flags |= psa_crypto_sys::PSA_KEY_USAGE_VERIFY;
        }
        if flags.derive {
            usage_flags |= psa_crypto_sys::PSA_KEY_USAGE_DERIVE;
        }
        usage_flags
    }
}

#[cfg(feature = "with-mbed-crypto")]
impl From<psa_crypto_sys::psa_key_usage_t> for UsageFlags {
    fn from(flags: psa_crypto_sys::psa_key_usage_t) -> Self {
        UsageFlags {
            export: flags & psa_crypto_sys::PSA_KEY_USAGE_EXPORT > 0,
            copy: false,
            cache: false,
            encrypt: flags & psa_crypto_sys::PSA_KEY_USAGE_ENCRYPT > 0,
            decrypt: flags & psa_crypto_sys::PSA_KEY_USAGE_DECRYPT > 0,
            sign_message: flags & psa_crypto_sys::PSA_KEY_USAGE_SIGN > 0,
            verify_message: flags & psa_crypto_sys::PSA_KEY_USAGE_VERIFY > 0,
            sign_hash: flags & psa_crypto_sys::PSA_KEY_USAGE_SIGN > 0,
            verify_hash: flags & psa_crypto_sys::PSA_KEY_USAGE_VERIFY > 0,
            derive: flags & psa_crypto_sys::PSA_KEY_USAGE_DERIVE > 0,
        }
    }
}

#[cfg(feature = "with-mbed-crypto")]
impl TryFrom<EccFamily> for psa_crypto_sys::psa_ecc_curve_t {
    type Error = Error;
    fn try_from(family: EccFamily) -> Result<Self> {
        match family {
            EccFamily::SecpK1 => Ok(psa_crypto_sys::PSA_ECC_FAMILY_SECP_K1),
            EccFamily::SecpR1 => Ok(psa_crypto_sys::PSA_ECC_FAMILY_SECP_R1),
            EccFamily::SecpR2 => Ok(psa_crypto_sys::PSA_ECC_FAMILY_SECP_R2),
            EccFamily::SectK1 => Ok(psa_crypto_sys::PSA_ECC_FAMILY_SECT_K1),
            EccFamily::SectR1 => Ok(psa_crypto_sys::PSA_ECC_FAMILY_SECT_R1),
            EccFamily::SectR2 => Ok(psa_crypto_sys::PSA_ECC_FAMILY_SECT_R2),
            EccFamily::BrainpoolPR1 => Ok(psa_crypto_sys::PSA_ECC_FAMILY_BRAINPOOL_P_R1),
            EccFamily::Frp => Err(Error::NotSupported),
            EccFamily::Montgomery => Ok(psa_crypto_sys::PSA_ECC_FAMILY_MONTGOMERY),
        }
    }
}

#[cfg(feature = "with-mbed-crypto")]
impl TryFrom<psa_crypto_sys::psa_ecc_curve_t> for EccFamily {
    type Error = Error;
    fn try_from(family: psa_crypto_sys::psa_ecc_curve_t) -> Result<Self> {
        match family {
            psa_crypto_sys::PSA_ECC_FAMILY_SECP_K1 => Ok(EccFamily::SecpK1),
            psa_crypto_sys::PSA_ECC_FAMILY_SECP_R1 => Ok(EccFamily::SecpR1),
            psa_crypto_sys::PSA_ECC_FAMILY_SECP_R2 => Ok(EccFamily::SecpR2),
            psa_crypto_sys::PSA_ECC_FAMILY_SECT_R1 => Ok(EccFamily::SectR1),
            psa_crypto_sys::PSA_ECC_FAMILY_SECT_R2 => Ok(EccFamily::SectR2),
            psa_crypto_sys::PSA_ECC_FAMILY_BRAINPOOL_P_R1 => Ok(EccFamily::BrainpoolPR1),
            //psa_crypto_sys::PSA_ECC_FAMILY_FRP => Ok(EccFamily::Frp),
            psa_crypto_sys::PSA_ECC_FAMILY_MONTGOMERY => Ok(EccFamily::Montgomery),
            f => {
                error!("Can not recognize the ECC family: {:?}.", f);
                Err(Error::GenericError)
            }
        }
    }
}

#[cfg(feature = "with-mbed-crypto")]
impl From<DhFamily> for psa_crypto_sys::psa_dh_group_t {
    fn from(group: DhFamily) -> Self {
        match group {
            DhFamily::Rfc7919 => psa_crypto_sys::PSA_DH_FAMILY_RFC7919,
        }
    }
}

#[cfg(feature = "with-mbed-crypto")]
impl TryFrom<psa_crypto_sys::psa_dh_group_t> for DhFamily {
    type Error = Error;
    fn try_from(group: psa_crypto_sys::psa_dh_group_t) -> Result<Self> {
        match group {
            psa_crypto_sys::PSA_DH_FAMILY_RFC7919 => Ok(DhFamily::Rfc7919),
            f => {
                error!("Can not recognize the DH family: {:?}.", f);
                Err(Error::GenericError)
            }
        }
    }
}

#[cfg(feature = "with-mbed-crypto")]
impl TryFrom<Type> for psa_crypto_sys::psa_key_type_t {
    type Error = Error;
    fn try_from(key_type: Type) -> Result<Self> {
        match key_type {
            Type::RawData => Ok(psa_crypto_sys::PSA_KEY_TYPE_RAW_DATA),
            Type::Hmac => Ok(psa_crypto_sys::PSA_KEY_TYPE_HMAC),
            Type::Derive => Ok(psa_crypto_sys::PSA_KEY_TYPE_DERIVE),
            Type::Aes => Ok(psa_crypto_sys::PSA_KEY_TYPE_AES),
            Type::Des => Ok(psa_crypto_sys::PSA_KEY_TYPE_DES),
            Type::Camellia => Ok(psa_crypto_sys::PSA_KEY_TYPE_CAMELLIA),
            Type::Arc4 => Ok(psa_crypto_sys::PSA_KEY_TYPE_ARC4),
            Type::Chacha20 => Ok(psa_crypto_sys::PSA_KEY_TYPE_CHACHA20),
            Type::RsaPublicKey => Ok(psa_crypto_sys::PSA_KEY_TYPE_RSA_PUBLIC_KEY),
            Type::RsaKeyPair => Ok(psa_crypto_sys::PSA_KEY_TYPE_RSA_KEY_PAIR),
            Type::EccKeyPair { curve_family } => Ok(psa_crypto_sys::PSA_KEY_TYPE_ECC_KEY_PAIR(
                curve_family.try_into()?,
            )),
            Type::EccPublicKey { curve_family } => Ok(psa_crypto_sys::PSA_KEY_TYPE_ECC_PUBLIC_KEY(
                curve_family.try_into()?,
            )),
            Type::DhKeyPair { group_family } => Ok(psa_crypto_sys::PSA_KEY_TYPE_DH_KEY_PAIR(
                group_family.into(),
            )),
            Type::DhPublicKey { group_family } => Ok(psa_crypto_sys::PSA_KEY_TYPE_DH_PUBLIC_KEY(
                group_family.into(),
            )),
        }
    }
}

#[cfg(feature = "with-mbed-crypto")]
impl TryFrom<psa_crypto_sys::psa_key_type_t> for Type {
    type Error = Error;
    fn try_from(key_type: psa_crypto_sys::psa_key_type_t) -> Result<Self> {
        match key_type {
            psa_crypto_sys::PSA_KEY_TYPE_RAW_DATA => Ok(Type::RawData),
            psa_crypto_sys::PSA_KEY_TYPE_HMAC => Ok(Type::Hmac),
            psa_crypto_sys::PSA_KEY_TYPE_DERIVE => Ok(Type::Derive),
            psa_crypto_sys::PSA_KEY_TYPE_AES => Ok(Type::Aes),
            psa_crypto_sys::PSA_KEY_TYPE_DES => Ok(Type::Des),
            psa_crypto_sys::PSA_KEY_TYPE_CAMELLIA => Ok(Type::Camellia),
            psa_crypto_sys::PSA_KEY_TYPE_ARC4 => Ok(Type::Arc4),
            psa_crypto_sys::PSA_KEY_TYPE_CHACHA20 => Ok(Type::Chacha20),
            psa_crypto_sys::PSA_KEY_TYPE_RSA_PUBLIC_KEY => Ok(Type::RsaPublicKey),
            psa_crypto_sys::PSA_KEY_TYPE_RSA_KEY_PAIR => Ok(Type::RsaKeyPair),
            key_type if psa_crypto_sys::PSA_KEY_TYPE_IS_ECC_KEY_PAIR(key_type) => {
                Ok(Type::EccKeyPair {
                    curve_family: psa_crypto_sys::PSA_KEY_TYPE_GET_CURVE(key_type).try_into()?,
                })
            }
            key_type if psa_crypto_sys::PSA_KEY_TYPE_IS_ECC_PUBLIC_KEY(key_type) => {
                Ok(Type::EccPublicKey {
                    curve_family: psa_crypto_sys::PSA_KEY_TYPE_GET_CURVE(key_type).try_into()?,
                })
            }
            key_type if psa_crypto_sys::PSA_KEY_TYPE_IS_DH_PUBLIC_KEY(key_type) => {
                Ok(Type::DhPublicKey {
                    group_family: psa_crypto_sys::PSA_KEY_TYPE_GET_GROUP(key_type).try_into()?,
                })
            }
            key_type if psa_crypto_sys::PSA_KEY_TYPE_IS_DH_KEY_PAIR(key_type) => {
                Ok(Type::DhKeyPair {
                    group_family: psa_crypto_sys::PSA_KEY_TYPE_GET_GROUP(key_type).try_into()?,
                })
            }
            key_type => {
                error!("Can not recognize the key type: {:?}.", key_type);
                Err(Error::GenericError)
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{Attributes, EccFamily, Lifetime, Policy, Type, UsageFlags};
    use crate::types::algorithm::{
        Aead, AeadWithDefaultLengthTag, Algorithm, AsymmetricSignature, Cipher, FullLengthMac,
        Hash, Mac, SignHash,
    };
    use core::convert::TryInto;

    #[test]
    fn usage_flags() {
        let permitted_alg = Algorithm::AsymmetricSignature(AsymmetricSignature::RsaPkcs1v15Sign {
            hash_alg: Hash::Sha256.into(),
        });
        let mut attributes = Attributes {
            key_type: Type::RsaKeyPair,
            bits: 1024,
            lifetime: Lifetime::Volatile,
            policy: Policy {
                usage_flags: UsageFlags {
                    export: false,
                    copy: false,
                    cache: false,
                    encrypt: false,
                    decrypt: false,
                    sign_message: false,
                    verify_message: false,
                    sign_hash: false,
                    verify_hash: false,
                    derive: false,
                },
                permitted_algorithms: permitted_alg,
            },
        };

        assert!(!attributes.is_exportable());
        assert!(!attributes.is_hash_signable());
        assert!(!attributes.is_hash_verifiable());
        attributes.policy.usage_flags.export = true;
        assert!(attributes.is_exportable());
        assert!(!attributes.is_hash_signable());
        assert!(!attributes.is_hash_verifiable());
        attributes.policy.usage_flags.sign_hash = true;
        assert!(attributes.is_exportable());
        assert!(attributes.is_hash_signable());
        assert!(!attributes.is_hash_verifiable());
        attributes.policy.usage_flags.verify_hash = true;
        assert!(attributes.is_exportable());
        assert!(attributes.is_hash_signable());
        assert!(attributes.is_hash_verifiable());
    }

    #[test]
    fn permits_good_alg() {
        let permitted_alg = Algorithm::AsymmetricSignature(AsymmetricSignature::RsaPkcs1v15Sign {
            hash_alg: Hash::Sha256.into(),
        });
        let alg = Algorithm::AsymmetricSignature(AsymmetricSignature::RsaPkcs1v15Sign {
            hash_alg: Hash::Sha256.into(),
        });
        let attributes = Attributes {
            key_type: Type::Hmac,
            bits: 1024,
            lifetime: Lifetime::Volatile,
            policy: Policy {
                usage_flags: UsageFlags {
                    export: false,
                    copy: false,
                    cache: false,
                    encrypt: false,
                    decrypt: false,
                    sign_message: false,
                    verify_message: false,
                    sign_hash: true,
                    verify_hash: false,
                    derive: false,
                },
                permitted_algorithms: permitted_alg,
            },
        };
        assert!(attributes.is_alg_permitted(alg));
    }

    #[test]
    fn permits_bad_alg() {
        let permitted_alg = Algorithm::Mac(Mac::FullLength(FullLengthMac::Hmac {
            hash_alg: Hash::Sha1,
        }));
        let alg = Algorithm::AsymmetricSignature(AsymmetricSignature::RsaPkcs1v15Sign {
            hash_alg: Hash::Sha1.into(),
        });
        let attributes = Attributes {
            key_type: Type::Hmac,
            bits: 1024,
            lifetime: Lifetime::Volatile,
            policy: Policy {
                usage_flags: UsageFlags {
                    export: false,
                    copy: false,
                    cache: false,
                    encrypt: false,
                    decrypt: false,
                    sign_message: false,
                    verify_message: false,
                    sign_hash: true,
                    verify_hash: false,
                    derive: false,
                },
                permitted_algorithms: permitted_alg,
            },
        };
        assert!(!attributes.is_alg_permitted(alg));
    }

    #[test]
    fn permits_wildcard_alg() {
        let permitted_alg = Algorithm::AsymmetricSignature(AsymmetricSignature::RsaPkcs1v15Sign {
            hash_alg: SignHash::Any,
        });
        let alg = Algorithm::AsymmetricSignature(AsymmetricSignature::RsaPkcs1v15Sign {
            hash_alg: Hash::Sha1.into(),
        });
        let attributes = Attributes {
            key_type: Type::Hmac,
            bits: 1024,
            lifetime: Lifetime::Volatile,
            policy: Policy {
                usage_flags: UsageFlags {
                    export: false,
                    copy: false,
                    cache: false,
                    encrypt: false,
                    decrypt: false,
                    sign_message: false,
                    verify_message: false,
                    sign_hash: true,
                    verify_hash: false,
                    derive: false,
                },
                permitted_algorithms: permitted_alg,
            },
        };
        assert!(attributes.is_alg_permitted(alg));
    }

    #[test]
    fn permits_bad_wildcard_alg() {
        let permitted_alg = Algorithm::AsymmetricSignature(AsymmetricSignature::RsaPkcs1v15Sign {
            hash_alg: Hash::Sha256.into(),
        });
        let alg = Algorithm::AsymmetricSignature(AsymmetricSignature::RsaPkcs1v15Sign {
            hash_alg: SignHash::Any,
        });
        let attributes = Attributes {
            key_type: Type::Hmac,
            bits: 1024,
            lifetime: Lifetime::Volatile,
            policy: Policy {
                usage_flags: UsageFlags {
                    export: false,
                    copy: false,
                    cache: false,
                    encrypt: false,
                    decrypt: false,
                    sign_message: false,
                    verify_message: false,
                    sign_hash: true,
                    verify_hash: false,
                    derive: false,
                },
                permitted_algorithms: permitted_alg,
            },
        };
        assert!(!attributes.is_alg_permitted(alg));
    }

    #[test]
    fn compat_rsa() {
        let permitted_alg = Algorithm::AsymmetricSignature(AsymmetricSignature::RsaPkcs1v15Sign {
            hash_alg: Hash::Sha256.into(),
        });
        let alg = Algorithm::AsymmetricSignature(AsymmetricSignature::RsaPkcs1v15Sign {
            hash_alg: Hash::Sha256.into(),
        });
        let mut attributes = Attributes {
            key_type: Type::RsaKeyPair,
            bits: 1024,
            lifetime: Lifetime::Volatile,
            policy: Policy {
                usage_flags: UsageFlags {
                    export: false,
                    copy: false,
                    cache: false,
                    encrypt: false,
                    decrypt: false,
                    sign_message: false,
                    verify_message: false,
                    sign_hash: false,
                    verify_hash: false,
                    derive: false,
                },
                permitted_algorithms: permitted_alg,
            },
        };

        assert!(attributes.is_compatible_with_alg(alg));
        attributes.key_type = Type::RsaPublicKey;
        assert!(attributes.is_compatible_with_alg(alg));
    }

    #[test]
    fn compat_raw_data() {
        let permitted_alg = Algorithm::None;
        let alg = Algorithm::AsymmetricSignature(AsymmetricSignature::RsaPkcs1v15Sign {
            hash_alg: Hash::Sha256.into(),
        });
        let attributes = Attributes {
            key_type: Type::RawData,
            bits: 1024,
            lifetime: Lifetime::Volatile,
            policy: Policy {
                usage_flags: UsageFlags {
                    export: false,
                    copy: false,
                    cache: false,
                    encrypt: false,
                    decrypt: false,
                    sign_message: false,
                    verify_message: false,
                    sign_hash: false,
                    verify_hash: false,
                    derive: false,
                },
                permitted_algorithms: permitted_alg,
            },
        };

        assert!(!attributes.is_compatible_with_alg(alg));
    }

    #[test]
    fn compat_block_cipher() {
        let permitted_alg = Algorithm::AsymmetricSignature(AsymmetricSignature::RsaPkcs1v15Sign {
            hash_alg: Hash::Sha256.into(),
        });
        let mut alg = Algorithm::Cipher(Cipher::Ofb);
        let mut attributes = Attributes {
            key_type: Type::Aes,
            bits: 1024,
            lifetime: Lifetime::Volatile,
            policy: Policy {
                usage_flags: UsageFlags {
                    export: false,
                    copy: false,
                    cache: false,
                    encrypt: false,
                    decrypt: false,
                    sign_message: false,
                    verify_message: false,
                    sign_hash: false,
                    verify_hash: false,
                    derive: false,
                },
                permitted_algorithms: permitted_alg,
            },
        };

        assert!(attributes.is_compatible_with_alg(alg));
        attributes.key_type = Type::Des;
        assert!(attributes.is_compatible_with_alg(alg));
        attributes.key_type = Type::Camellia;
        assert!(attributes.is_compatible_with_alg(alg));
        alg = Algorithm::Aead(Aead::AeadWithDefaultLengthTag(
            AeadWithDefaultLengthTag::Ccm,
        ));
        assert!(attributes.is_compatible_with_alg(alg));
        attributes.key_type = Type::Des;
        assert!(!attributes.is_compatible_with_alg(alg));
    }

    #[test]
    fn compat_chacha() {
        let permitted_alg = Algorithm::AsymmetricSignature(AsymmetricSignature::RsaPkcs1v15Sign {
            hash_alg: Hash::Sha256.into(),
        });
        let alg = Algorithm::Aead(Aead::AeadWithDefaultLengthTag(
            AeadWithDefaultLengthTag::Chacha20Poly1305,
        ));
        let attributes = Attributes {
            key_type: Type::Chacha20,
            bits: 1024,
            lifetime: Lifetime::Volatile,
            policy: Policy {
                usage_flags: UsageFlags {
                    export: false,
                    copy: false,
                    cache: false,
                    encrypt: false,
                    decrypt: false,
                    sign_message: false,
                    verify_message: false,
                    sign_hash: false,
                    verify_hash: false,
                    derive: false,
                },
                permitted_algorithms: permitted_alg,
            },
        };

        assert!(attributes.is_compatible_with_alg(alg));
    }

    #[test]
    fn bad_compat() {
        let permitted_alg = Algorithm::AsymmetricSignature(AsymmetricSignature::RsaPkcs1v15Sign {
            hash_alg: Hash::Sha256.into(),
        });
        let alg = Algorithm::AsymmetricSignature(AsymmetricSignature::RsaPkcs1v15Sign {
            hash_alg: Hash::Sha256.into(),
        });
        let attributes = Attributes {
            key_type: Type::Hmac,
            bits: 1024,
            lifetime: Lifetime::Volatile,
            policy: Policy {
                usage_flags: UsageFlags {
                    export: false,
                    copy: false,
                    cache: false,
                    encrypt: false,
                    decrypt: false,
                    sign_message: false,
                    verify_message: false,
                    sign_hash: false,
                    verify_hash: false,
                    derive: false,
                },
                permitted_algorithms: permitted_alg,
            },
        };

        assert!(!attributes.is_compatible_with_alg(alg));
    }

    #[test]
    fn convert() {
        let mut attrs = unsafe { psa_crypto_sys::psa_key_attributes_init() };
        unsafe {
            psa_crypto_sys::psa_set_key_lifetime(
                &mut attrs,
                psa_crypto_sys::PSA_KEY_LIFETIME_VOLATILE,
            )
        };
        unsafe {
            psa_crypto_sys::psa_set_key_usage_flags(
                &mut attrs,
                psa_crypto_sys::PSA_KEY_USAGE_SIGN | psa_crypto_sys::PSA_KEY_USAGE_VERIFY,
            )
        };
        unsafe {
            psa_crypto_sys::psa_set_key_algorithm(
                &mut attrs,
                psa_crypto_sys::PSA_ALG_ECDSA(psa_crypto_sys::PSA_ALG_SHA_256),
            )
        };
        unsafe {
            psa_crypto_sys::psa_set_key_type(
                &mut attrs,
                psa_crypto_sys::PSA_KEY_TYPE_ECC_KEY_PAIR(psa_crypto_sys::PSA_ECC_FAMILY_SECP_K1),
            )
        };
        unsafe { psa_crypto_sys::psa_set_key_bits(&mut attrs, 2048) };

        assert_eq!(
            Attributes {
                key_type: Type::EccKeyPair {
                    curve_family: EccFamily::SecpK1,
                },
                bits: 2048,
                lifetime: Lifetime::Volatile,
                policy: Policy {
                    usage_flags: UsageFlags {
                        export: false,
                        copy: false,
                        cache: false,
                        encrypt: false,
                        decrypt: false,
                        sign_message: true,
                        verify_message: true,
                        sign_hash: true,
                        verify_hash: true,
                        derive: false,
                    },
                    permitted_algorithms: AsymmetricSignature::Ecdsa {
                        hash_alg: Hash::Sha256.into(),
                    }
                    .into(),
                },
            },
            attrs.try_into().unwrap()
        );
    }
}