File: objects.py

package info (click to toggle)
python-yubihsm 3.1.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 452 kB
  • sloc: python: 4,882; makefile: 4
file content (1884 lines) | stat: -rw-r--r-- 66,342 bytes parent folder | download | duplicates (2)
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
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
# Copyright 2016-2018 Yubico AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Classes for interacting with objects on a YubiHSM."""

import copy
import gzip
import struct
from dataclasses import dataclass
from typing import ClassVar, NamedTuple, Optional, Type, TypeVar, Union

from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import ec, ed25519, rsa
from cryptography.hazmat.primitives.asymmetric.utils import Prehashed
from cryptography.hazmat.primitives.serialization import (
    Encoding,
    NoEncryption,
    PrivateFormat,
    PublicFormat,
)

from . import core
from .defs import ALGORITHM, CAPABILITY, COMMAND, OBJECT, ORIGIN, Version
from .exceptions import YubiHsmInvalidResponseError
from .utils import password_to_key

LABEL_LENGTH = 40

MAX_AES_PAYLOAD_SIZE = 2026
AES_BLOCK_SIZE = 16

RSA_PUBLIC_EXPONENT = 65537
RSA_SIZES = [
    2048,
    3072,
    4096,
]


def _label_pack(label: Union[str, bytes]) -> bytes:
    """Pack a label into binary form."""
    if isinstance(label, str):
        label = label.encode()
    if len(label) > LABEL_LENGTH:
        raise ValueError("Label must be no longer than %d bytes" % LABEL_LENGTH)
    return label


def _label_unpack(packed: bytes) -> Union[str, bytes]:
    """Unpack a label from its binary form."""
    try:
        return packed.split(b"\0", 2)[0].decode()
    except UnicodeDecodeError:
        # Not valid UTF-8 string, return the raw data.
        return packed


def _calc_hash(data: bytes, hash: hashes.HashAlgorithm) -> bytes:
    if not isinstance(hash, Prehashed):
        digest = hashes.Hash(hash, backend=default_backend())
        digest.update(data)
        data = digest.finalize()

    return data


@dataclass(frozen=True)
class ObjectInfo:
    """Data structure holding various information about an object.

    :ivar capabilities: The capabilities of the object.
    :ivar id: The ID of the object.
    :ivar size: The size of the object.
    :ivar domains: The set of domains the object belongs to.
    :ivar object_type: The type of the object.
    :ivar algorithm: The algorithm of the object.
    :ivar sequence: The sequence number of the object.
    :ivar origin: How the object was created/imported.
    :ivar label: The label of the object.
    :ivar delegated_capabilities: The set of delegated capabilities for the object.
    """

    FORMAT: ClassVar[str] = "!QHHHBBBB%dsQ" % LABEL_LENGTH
    LENGTH: ClassVar[int] = struct.calcsize(FORMAT)

    capabilities: CAPABILITY
    id: int
    size: int
    domains: int
    object_type: OBJECT
    algorithm: ALGORITHM
    sequence: int
    origin: ORIGIN
    label: Union[str, bytes]
    delegated_capabilities: CAPABILITY

    @classmethod
    def parse(cls, value: bytes) -> "ObjectInfo":
        """Parse an ObjectInfo from its binary representation."""
        data = list(struct.unpack(cls.FORMAT, value))
        data[4] = OBJECT(data[4])
        data[5] = ALGORITHM(data[5])
        data[7] = ORIGIN(data[7])
        data[8] = _label_unpack(data[8])
        return cls(*data)


def _get_bytes(c: x509.Certificate, oid: int) -> bytes:
    return c.extensions.get_extension_for_oid(
        x509.ObjectIdentifier(f"1.3.6.1.4.1.41482.4.{oid}")
    ).value.public_bytes()


def _get_int(c: x509.Certificate, oid: int) -> int:
    return int.from_bytes(_get_bytes(c, oid)[2:], "big")


T_AttestationExtensions = TypeVar(
    "T_AttestationExtensions", bound="AttestationExtensions"
)


@dataclass
class AttestationExtensions:
    """Base attestation extensions.

    :ivar firmware_version: YubiHSM firmware version.
    :ivar serial: YubiHSM serial number.
    """

    firmware_version: Version
    serial: int

    @classmethod
    def parse(
        cls: Type[T_AttestationExtensions], certificate: x509.Certificate, *args
    ) -> T_AttestationExtensions:
        if cls == AttestationExtensions:
            # When called on the base class, identify which subclass to use
            try:
                _get_bytes(certificate, 3)
                return KeyAttestationExtensions.parse(certificate)  # type: ignore
            except x509.ExtensionNotFound:
                return DeviceAttestationExtensions.parse(certificate)  # type: ignore

        version: Version = tuple(_get_bytes(certificate, 1)[-3:])  # type: ignore
        serial = _get_int(certificate, 2)
        return cls(version, serial, *args)


@dataclass
class DeviceAttestationExtensions(AttestationExtensions):
    """Device attestation extensions. Available on YubiHSM FIPS only.

    :ivar fips_certificate: The FIPS certificate.
    """

    fips_certificate: Optional[int]

    @classmethod
    def parse(cls, certificate: x509.Certificate, *args):
        # Available on YubiHSM FIPS only
        try:
            fips_certificate = _get_int(certificate, 10)
        except x509.ExtensionNotFound:
            fips_certificate = None

        return super(DeviceAttestationExtensions, cls).parse(
            certificate, fips_certificate
        )


@dataclass
class KeyAttestationExtensions(AttestationExtensions):
    """Key attestation extensions.

    :ivar origin: The origin of the key.
    :ivar domains: The set of domains assigned to the key object.
    :ivar capabilities: The set of capabilities assigned to the key object.
    :ivar object_id: The ID of the key object.
    :ivar label: The label of the key object.
    :ivar fips_approved: (available on YubiHSM FIPS >= 2.4.1 only) True if
        the key attestation was generated in FIPS-approved mode.
    """

    origin: ORIGIN
    domains: int
    capabilities: CAPABILITY
    object_id: int
    label: Union[str, bytes]
    fips_approved: Optional[bool]

    @classmethod
    def parse(cls, certificate: x509.Certificate, *args):
        """Extracts the attributes from an an attestation certificate."""

        origin = ORIGIN(_get_int(certificate, 3))
        domains = _get_int(certificate, 4)
        capabilities = CAPABILITY(_get_int(certificate, 5))
        object_id = _get_int(certificate, 6)
        label = _label_unpack(_get_bytes(certificate, 9)[2:])

        # Available on YubiHSM FIPS >= 2.4.1 only
        try:
            fips_approved = bool(_get_int(certificate, 12))
        except x509.ExtensionNotFound:
            fips_approved = None

        return super(KeyAttestationExtensions, cls).parse(
            certificate, origin, domains, capabilities, object_id, label, fips_approved
        )


T_Object = TypeVar("T_Object", bound="YhsmObject")


class YhsmObject:
    """A reference to an object stored in a YubiHSM.

    YubiHSM objects are uniquely identified by their type and ID combined.

    :ivar session: The session to use for YubiHSM communication.
    :ivar id: The ID of the object.
    :ivar object_type: The type of the object.
    """

    object_type: ClassVar[OBJECT]

    def __init__(
        self, session: "core.AuthSession", object_id: int, seq: Optional[int] = None
    ):
        self.session = session
        self.id: int = object_id
        self._seq = seq

    def with_session(self: T_Object, session: "core.AuthSession") -> T_Object:
        """Get a copy of the object reference, using the given session.

        :param session: The session to use for the created reference.
        :return: A new reference to the object, associated wth the given session.
        """
        other = copy.copy(self)
        other.session = session
        return other

    def get_info(self) -> ObjectInfo:
        """Read extended information about the object from the YubiHSM.

        :return: Information about the object.
        """
        msg = struct.pack("!HB", self.id, self.object_type)
        resp = self.session.send_secure_cmd(COMMAND.GET_OBJECT_INFO, msg)
        try:
            return ObjectInfo.parse(resp)
        except ValueError:
            raise YubiHsmInvalidResponseError()

    def delete(self) -> None:
        """Delete the object from the YubiHSM.

        .. warning:: This action in irreversible.
        """
        msg = struct.pack("!HB", self.id, self.object_type)
        if self.session.send_secure_cmd(COMMAND.DELETE_OBJECT, msg) != b"":
            raise YubiHsmInvalidResponseError()

    @staticmethod
    def _create(
        object_type: OBJECT,
        session: "core.AuthSession",
        object_id: int,
        seq: Optional[int] = None,
    ) -> "YhsmObject":
        """
        Create instance of `object_type`.

        When object type is not recognized, _create constructs an
        instance of `_UnknownYhsmObject`.
        """
        for cls in YhsmObject.__subclasses__():
            if getattr(cls, "object_type", None) == object_type:
                return cls(session, object_id, seq)
        return _UnknownYhsmObject(object_type, session, object_id, seq)

    @classmethod
    def _from_command(
        cls: Type[T_Object], session: "core.AuthSession", cmd: COMMAND, data: bytes
    ) -> T_Object:
        ret = session.send_secure_cmd(cmd, data)
        return cls(session, struct.unpack("!H", ret)[0])

    def __repr__(self):
        return "{0.__class__.__name__}(id={0.id})".format(self)


class _UnknownYhsmObject(YhsmObject):
    """
    _UnknownYhsmObject is a generic YhsmObject with `self.object_type`
    set to the specified `object_type` parameter.
    """

    def __init__(self, object_type: OBJECT, *args, **kwargs):
        super(_UnknownYhsmObject, self).__init__(*args, **kwargs)
        self.object_type = object_type  # type: ignore


class Opaque(YhsmObject):
    """Object used to store arbitrary data on the YubiHSM.

    Supported algorithms:
        - :class:`~yubihsm.defs.ALGORITHM.OPAQUE_DATA`
        - :class:`~yubihsm.defs.ALGORITHM.OPAQUE_X509_CERTIFICATE`
    """

    object_type = OBJECT.OPAQUE

    @classmethod
    def put(
        cls,
        session: "core.AuthSession",
        object_id: int,
        label: str,
        domains: int,
        capabilities: CAPABILITY,
        algorithm: ALGORITHM,
        data: bytes,
    ) -> "Opaque":
        """Import an Opaque object into the YubiHSM.

        :param session: The session to import via.
        :param object_id: The ID to set for the object. Set to 0 to let the
            YubiHSM designate an ID.
        :param label: A text label to give the object.
        :param domains: The set of domains to assign the object to.
        :param capabilities: The set of capabilities to give the object.
        :param algorithm: The algorithm to use for the object.
        :param data: The binary data to store.
        :return: A reference to the newly created object.
        """
        if not data:
            raise ValueError("Cannot store empty data")
        msg = struct.pack(
            "!H%dsHQB" % LABEL_LENGTH,
            object_id,
            _label_pack(label),
            domains,
            capabilities,
            algorithm,
        )
        msg += data
        return cls._from_command(session, COMMAND.PUT_OPAQUE, msg)

    def get(self) -> bytes:
        """Read the data of an Opaque object from the YubiHSM.

        :return: The data stored for the object.
        """
        msg = struct.pack("!H", self.id)
        return self.session.send_secure_cmd(COMMAND.GET_OPAQUE, msg)

    @classmethod
    def put_certificate(
        cls,
        session: "core.AuthSession",
        object_id: int,
        label: str,
        domains: int,
        capabilities: CAPABILITY,
        certificate: x509.Certificate,
        compress: bool = False,
    ) -> "Opaque":
        """Import an X509 certificate into the YubiHSM as an Opaque.

        :param session: The session to import via.
        :param object_id: The ID to set for the object. Set to 0 to let the
            YubiHSM designate an ID.
        :param label: A text label to give the object.
        :param domains: The set of domains to assign the object to.
        :param capabilities: The set of capabilities to give the object.
        :param certificate: A certificate to import.
        :param compress: (optional) Compress the certificate.
        :return: A reference to the newly created object.
        """
        encoded_cert = certificate.public_bytes(Encoding.DER)
        if compress:
            encoded_cert = gzip.compress(encoded_cert)
        return cls.put(
            session,
            object_id,
            label,
            domains,
            capabilities,
            ALGORITHM.OPAQUE_X509_CERTIFICATE,
            encoded_cert,
        )

    def get_certificate(self) -> x509.Certificate:
        """Read an Opaque object from the YubiHSM, parsed as a certificate.

        :return: The certificate stored for the object.
        """
        cert_data = self.get()
        try:
            # Try to decompress cert
            cert_data = gzip.decompress(cert_data)
        except gzip.BadGzipFile:
            pass
        return x509.load_der_x509_certificate(cert_data, default_backend())


class AuthenticationKey(YhsmObject):
    """Used to authenticate a session with the YubiHSM.

    AuthenticationKeys use two separate keys to mutually authenticate and set up
    a secure session with a YubiHSM. These two keys can either be given
    explicitly, or be derived from a password.
    """

    object_type = OBJECT.AUTHENTICATION_KEY

    @classmethod
    def put_derived(
        cls,
        session: "core.AuthSession",
        object_id: int,
        label: str,
        domains: int,
        capabilities: CAPABILITY,
        delegated_capabilities: CAPABILITY,
        password: str,
    ) -> "AuthenticationKey":
        """Create an AuthenticationKey derived from a password.

        :param session: The session to import via.
        :param object_id: The ID to set for the object. Set to 0 to let the
            YubiHSM designate an ID.
        :param label: A text label to give the object.
        :param domains: The set of domains to assign the object to.
        :param capabilities: The set of capabilities to give the object.
        :param delegated_capabilities: The set of capabilities that the
            AuthenticationKey can give to objects created when authenticated
            using it.
        :param password: The password to derive raw keys from.
        :return: A reference to the newly created object.
        """
        key_enc, key_mac = password_to_key(password)
        return cls.put(
            session,
            object_id,
            label,
            domains,
            capabilities,
            delegated_capabilities,
            key_enc,
            key_mac,
        )

    @classmethod
    def put(
        cls,
        session: "core.AuthSession",
        object_id: int,
        label: str,
        domains: int,
        capabilities: CAPABILITY,
        delegated_capabilities: CAPABILITY,
        key_enc: bytes,
        key_mac: bytes,
    ) -> "AuthenticationKey":
        """Create an AuthenticationKey by providing raw keys.

        :param session: The session to import via.
        :param object_id: The ID to set for the object. Set to 0 to let the
            YubiHSM designate an ID.
        :param label: A text label to give the object.
        :param domains: The set of domains to assign the object to.
        :param capabilities: The set of capabilities to give the object.
        :param delegated_capabilities: The set of capabilities that the
            AuthenticationKey can give to objects created when authenticated
            using it.
        :param key_enc: The raw encryption key.
        :param key_mac: The raw MAC key.
        :return: A reference to the newly created object.
        """
        msg = struct.pack(
            "!H%dsHQBQ" % LABEL_LENGTH,
            object_id,
            _label_pack(label),
            domains,
            capabilities,
            ALGORITHM.AES128_YUBICO_AUTHENTICATION,
            delegated_capabilities,
        )
        msg += key_enc + key_mac
        return cls._from_command(session, COMMAND.PUT_AUTHENTICATION_KEY, msg)

    @classmethod
    def put_public_key(
        cls,
        session: "core.AuthSession",
        object_id: int,
        label: str,
        domains: int,
        capabilities: CAPABILITY,
        delegated_capabilities: CAPABILITY,
        public_key: ec.EllipticCurvePublicKey,
    ) -> "AuthenticationKey":
        """Create an asymmetric AuthenticationKey by providing a public key

        :param session: The session to import via.
        :param object_id: The ID to set for the object. Set to 0 to let the
            YubiHSM designate an ID.
        :param label: A text label to give the object.
        :param domains: The set of domains to assign the object to.
        :param capabilities: The set of capabilities to give the object.
        :param delegated_capabilities: The set of capabilities that the
            AuthenticationKey can give to objects created when authenticated
            using it.
        :param public_key: The public key to import.
        :return: A reference to the newly created object.
        """
        if not isinstance(public_key.curve, ec.SECP256R1):
            raise ValueError("Unsupported curve")

        msg = struct.pack(
            "!H%dsHQBQ" % LABEL_LENGTH,
            object_id,
            _label_pack(label),
            domains,
            capabilities,
            ALGORITHM.EC_P256_YUBICO_AUTHENTICATION,
            delegated_capabilities,
        )
        numbers = public_key.public_numbers()
        msg += int.to_bytes(numbers.x, public_key.key_size // 8, "big")
        msg += int.to_bytes(numbers.y, public_key.key_size // 8, "big")
        return cls._from_command(session, COMMAND.PUT_AUTHENTICATION_KEY, msg)

    def change_password(self, password: str) -> None:
        """Change the password used to authenticate a session.

        Changes the raw keys used for authentication, by deriving them from a
        password.

        :param password: The password to derive raw keys from.
        """
        key_enc, key_mac = password_to_key(password)
        self.change_key(key_enc, key_mac)

    def change_key(self, key_enc: bytes, key_mac: bytes) -> None:
        """Change the raw keys used to authenticate a session.

        :param key_enc: The raw encryption key.
        :param key_mac: The raw MAC key.
        """
        msg = (
            struct.pack("!HB", self.id, ALGORITHM.AES128_YUBICO_AUTHENTICATION)
            + key_enc
            + key_mac
        )
        resp = self.session.send_secure_cmd(COMMAND.CHANGE_AUTHENTICATION_KEY, msg)
        if struct.unpack("!H", resp)[0] != self.id:
            raise YubiHsmInvalidResponseError("Wrong ID returned")

    def change_public_key(self, public_key: ec.EllipticCurvePublicKey) -> None:
        """Change an asymmetric AuthenticationKey's public key

        :param public_key: The new public key.
        """
        if not isinstance(public_key.curve, ec.SECP256R1):
            raise ValueError("Unsupported curve")

        msg = struct.pack("!HB", self.id, ALGORITHM.EC_P256_YUBICO_AUTHENTICATION)
        numbers = public_key.public_numbers()
        msg += int.to_bytes(numbers.x, public_key.key_size // 8, "big")
        msg += int.to_bytes(numbers.y, public_key.key_size // 8, "big")
        resp = self.session.send_secure_cmd(COMMAND.CHANGE_AUTHENTICATION_KEY, msg)
        if struct.unpack("!H", resp)[0] != self.id:
            raise YubiHsmInvalidResponseError("Wrong ID returned")


class AsymmetricKey(YhsmObject):
    """Used to sign/decrypt data with the private key of an asymmetric key pair.

    Supported algorithms:
        - :class:`~yubihsm.defs.ALGORITHM.RSA_2048`
        - :class:`~yubihsm.defs.ALGORITHM.RSA_3072`
        - :class:`~yubihsm.defs.ALGORITHM.RSA_4096`
        - :class:`~yubihsm.defs.ALGORITHM.EC_P224`
        - :class:`~yubihsm.defs.ALGORITHM.EC_P256`
        - :class:`~yubihsm.defs.ALGORITHM.EC_P384`
        - :class:`~yubihsm.defs.ALGORITHM.EC_P521`
        - :class:`~yubihsm.defs.ALGORITHM.EC_K256`
        - :class:`~yubihsm.defs.ALGORITHM.EC_BP256`
        - :class:`~yubihsm.defs.ALGORITHM.EC_BP384`
        - :class:`~yubihsm.defs.ALGORITHM.EC_BP512`
        - :class:`~yubihsm.defs.ALGORITHM.EC_ED25519`
    """

    object_type = OBJECT.ASYMMETRIC_KEY

    @classmethod
    def put(
        cls,
        session: "core.AuthSession",
        object_id: int,
        label: str,
        domains: int,
        capabilities: CAPABILITY,
        key,
    ) -> "AsymmetricKey":
        """Import a private key into the YubiHSM.

        RSA and EC keys can be created by using the cryptography APIs. You can
        then pass either a
        :class:`~cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey`
        , a
        :class:`~cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey`
        , or a
        :class:`~cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PrivateKey`
        as `key`.

        :param session: The session to import via.
        :param object_id: The ID to set for the object. Set to 0 to let the
            YubiHSM designate an ID.
        :param label: A text label to give the object.
        :param domains: The set of domains to assign the object to.
        :param capabilities: The set of capabilities to give the object.
        :param key: The private key to import.
        :return: A reference to the newly created object.
        """
        if isinstance(key, rsa.RSAPrivateKeyWithSerialization):
            rsa_numbers = key.private_numbers()
            if rsa_numbers.public_numbers.e != RSA_PUBLIC_EXPONENT:
                raise ValueError("Unsupported public exponent")
            if key.key_size not in RSA_SIZES:
                raise ValueError("Unsupported key size")
            serialized = int.to_bytes(
                rsa_numbers.p, key.key_size // 8 // 2, "big"
            ) + int.to_bytes(rsa_numbers.q, key.key_size // 8 // 2, "big")
            algo = getattr(ALGORITHM, "RSA_%d" % key.key_size)
        elif isinstance(key, ec.EllipticCurvePrivateKeyWithSerialization):
            ec_numbers = key.private_numbers()
            serialized = int.to_bytes(
                ec_numbers.private_value, (key.curve.key_size + 7) // 8, "big"
            )
            algo = ALGORITHM.for_curve(key.curve)
        elif isinstance(key, ed25519.Ed25519PrivateKey):
            serialized = key.private_bytes(
                Encoding.Raw, PrivateFormat.Raw, NoEncryption()
            )
            algo = ALGORITHM.EC_ED25519
        else:
            raise ValueError("Unsupported key")

        msg = (
            struct.pack(
                "!H%dsHQB" % LABEL_LENGTH,
                object_id,
                _label_pack(label),
                domains,
                capabilities,
                algo,
            )
            + serialized
        )
        return cls._from_command(session, COMMAND.PUT_ASYMMETRIC_KEY, msg)

    @classmethod
    def generate(
        cls,
        session: "core.AuthSession",
        object_id: int,
        label: str,
        domains: int,
        capabilities: CAPABILITY,
        algorithm: ALGORITHM,
    ) -> "AsymmetricKey":
        """Generate a new private key in the YubiHSM.

        :param session: The session to import via.
        :param object_id: The ID to set for the object. Set to 0 to let the
            YubiHSM designate an ID.
        :param label: A text label to give the object.
        :param domains: The set of domains to assign the object to.
        :param capabilities: The set of capabilities to give the object.
        :param algorithm: The algorithm to use for the private key.
        :return: A reference to the newly created object.
        """
        msg = struct.pack(
            "!H%dsHQB" % LABEL_LENGTH,
            object_id,
            _label_pack(label),
            domains,
            capabilities,
            algorithm,
        )
        return cls._from_command(session, COMMAND.GENERATE_ASYMMETRIC_KEY, msg)

    def get_public_key(self):
        """Get the public key of the key pair.

        This will return either a
        :class:`~cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey`
        or a
        :class:`~cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey`
        depending on the algorithm of the key.

        Ed25519 keys will be returned as a Cryptography
        :class:`~cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PublicKey`
        object if possible (requires Cryptography 2.6 or later), or an internal
        representation if not, either which can be serialized using the
        :func:`~yubihsm.eddsa.serialize_ed25519_public_key` function.

        :return: The public key of the key pair.
        """
        msg = struct.pack("!H", self.id)
        ret = self.session.send_secure_cmd(COMMAND.GET_PUBLIC_KEY, msg)
        algo = ALGORITHM(ret[0])
        raw_key = ret[1:]
        if algo in [ALGORITHM.RSA_2048, ALGORITHM.RSA_3072, ALGORITHM.RSA_4096]:
            num = int.from_bytes(raw_key, "big")
            return rsa.RSAPublicNumbers(e=RSA_PUBLIC_EXPONENT, n=num).public_key(
                backend=default_backend()
            )
        elif algo in [
            ALGORITHM.EC_P224,
            ALGORITHM.EC_P256,
            ALGORITHM.EC_P384,
            ALGORITHM.EC_P521,
            ALGORITHM.EC_K256,
            ALGORITHM.EC_BP256,
            ALGORITHM.EC_BP384,
            ALGORITHM.EC_BP512,
        ]:
            c_len = len(raw_key) // 2
            x = int.from_bytes(raw_key[:c_len], "big")
            y = int.from_bytes(raw_key[c_len:], "big")
            return ec.EllipticCurvePublicNumbers(
                curve=algo.to_curve(), x=x, y=y
            ).public_key(backend=default_backend())
        elif algo in [ALGORITHM.EC_ED25519]:
            return ed25519.Ed25519PublicKey.from_public_bytes(raw_key)
        else:
            raise TypeError("Invalid ALGORITHM")

    def get_certificate(self) -> x509.Certificate:
        """Get the X509 certificate associated with the key.

        An X509 certificate is associated with an asymmetric key if it is stored
        as an Opaque object with the same object ID as the key, and it has the
        :class:`~yubihsm.defs.ALGORITHM.OPAQUE_X509_CERTIFICATE` algorithm set.

        Equivalent to calling `Opaque(session, key_id).get_certificate()`.

        :return: The certificate stored for the object.
        """
        return Opaque(self.session, self.id).get_certificate()

    def put_certificate(
        self,
        label: str,
        domains: int,
        capabilities: CAPABILITY,
        certificate: x509.Certificate,
    ) -> Opaque:
        """Store an X509 certificate associated with this key.

        Equivalent to calling `Opaque.put_certificate(session, key_id, ...)`.

        :param label: A text label to give the object.
        :param domains: The set of domains to assign the object to.
        :param capabilities: The set of capabilities to give the object.
        :param certificate: A certificate to import.
        :return: A reference to the newly created object.
        """
        return Opaque.put_certificate(
            self.session, self.id, label, domains, capabilities, certificate
        )

    def sign_ecdsa(
        self, data: bytes, hash: hashes.HashAlgorithm = hashes.SHA256(), length: int = 0
    ) -> bytes:
        """Sign data using ECDSA.

        :param data: The data to sign.
        :param hash: (optional) The algorithm to use when hashing the data.
        :param length: (optional) length to pad/truncate the hash to.
        :return: The resulting signature.
        """
        data = _calc_hash(data, hash)

        if not length:
            length = hash.digest_size

        msg = struct.pack("!H%ds" % length, self.id, data.rjust(length, b"\0"))
        return self.session.send_secure_cmd(COMMAND.SIGN_ECDSA, msg)

    def derive_ecdh(self, public_key: ec.EllipticCurvePublicKey) -> bytes:
        """Perform an ECDH key exchange as specified in SP 800-56A.

        :param public_key: The public key to use for the key exchange.
        :return: The resulting shared key.
        """
        point = public_key.public_bytes(Encoding.X962, PublicFormat.UncompressedPoint)
        msg = struct.pack("!H", self.id) + point
        return self.session.send_secure_cmd(COMMAND.DERIVE_ECDH, msg)

    def sign_pkcs1v1_5(
        self, data: bytes, hash: hashes.HashAlgorithm = hashes.SHA256()
    ) -> bytes:
        """Sign data using RSASSA-PKCS1-v1_5.

        :param data: The data to sign.
        :param hash: (optional) The algorithm to use when hashing the data.
        :return: The resulting signature.
        """
        data = _calc_hash(data, hash)

        msg = struct.pack("!H", self.id) + data
        return self.session.send_secure_cmd(COMMAND.SIGN_PKCS1, msg)

    def decrypt_pkcs1v1_5(self, data: bytes) -> bytes:
        """Decrypt data encrypted with RSAES-PKCS1-v1_5.

        :param data: The ciphertext to decrypt.
        :return: The decrypted plaintext.
        """
        msg = struct.pack("!H", self.id) + data
        return self.session.send_secure_cmd(COMMAND.DECRYPT_PKCS1, msg)

    def sign_pss(
        self,
        data: bytes,
        salt_len: int,
        hash: hashes.HashAlgorithm = hashes.SHA256(),
        mgf_hash: hashes.HashAlgorithm = hashes.SHA256(),
    ) -> bytes:
        """Sign data using RSASSA-PSS with MGF1.

        :param data: The data to sign.
        :param salt_len: The length of the salt to use.
        :param hash: (optional) The algorithm to use when hashing the data.
        :param mgf_hash: (optional) The algorithm to use for MGF1.
        :return: The resulting signature.
        """
        data = _calc_hash(data, hash)

        mgf = getattr(ALGORITHM, "RSA_MGF1_%s" % mgf_hash.name.upper())

        msg = struct.pack("!HBH", self.id, mgf, salt_len) + data
        return self.session.send_secure_cmd(COMMAND.SIGN_PSS, msg)

    def decrypt_oaep(
        self,
        data: bytes,
        label: bytes = b"",
        hash: hashes.HashAlgorithm = hashes.SHA256(),
        mgf_hash: hashes.HashAlgorithm = hashes.SHA256(),
    ) -> bytes:
        """Decrypt data encrypted with RSAES-OAEP.

        :param data: The ciphertext to decrypt.
        :param label: (optional) OAEP label.
        :param hash: (optional) The algorithm to use when hashing the data.
        :param mgf_hash: (optional) The algorithm to use for MGF1.
        :return: The decrypted plaintext.
        """
        digest = hashes.Hash(hash, backend=default_backend())
        digest.update(label)

        mgf = getattr(ALGORITHM, "RSA_MGF1_%s" % mgf_hash.name.upper())

        msg = struct.pack("!HB", self.id, mgf) + data + digest.finalize()
        return self.session.send_secure_cmd(COMMAND.DECRYPT_OAEP, msg)

    def sign_eddsa(self, data: bytes) -> bytes:
        """Sign data using EdDSA.

        :param data: The data to sign.
        :return: The resulting signature.
        """
        msg = struct.pack("!H", self.id) + data
        return self.session.send_secure_cmd(COMMAND.SIGN_EDDSA, msg)

    def attest(self, attesting_key_id: int = 0) -> x509.Certificate:
        """Attest this asymmetric key.

        Creates an X509 certificate containing this key pair's public key,
        signed by the asymmetric key identified by the given ID.
        You also need a X509 certificate stored with the same ID as the
        attesting key in the YubiHSM, to be used as a template.

        :param attesting_key_id: (optional) The ID of the asymmetric key used to attest.
            If omitted, the built-in Yubico attestation key is used.
        :return: The attestation certificate.
        """
        msg = struct.pack("!HH", self.id, attesting_key_id)
        resp = self.session.send_secure_cmd(COMMAND.SIGN_ATTESTATION_CERTIFICATE, msg)
        return x509.load_der_x509_certificate(resp, default_backend())

    def sign_ssh_certificate(
        self,
        template_id: int,
        request: bytes,
        algorithm: ALGORITHM = ALGORITHM.RSA_PKCS1_SHA1,
    ) -> bytes:
        """Sign an SSH certificate request.

        :param template_id: The ID of the SSH TEMPLATE to use.
        :param request: The SSH certificate request.
        :return: The SSH certificate signature.
        """
        msg = struct.pack("!HHB", self.id, template_id, algorithm) + request
        return self.session.send_secure_cmd(COMMAND.SIGN_SSH_CERTIFICATE, msg)


class WrapKey(YhsmObject):
    """Used to import and export other objects under wrap.

    Asymmetric wrapkeys are only used for importing wrapped objects.
    To export objects under asymmetric wrap, use
    :class:`~yubihsm.objects.PublicWrapKey`.

    Supported algorithms:
        - :class:`~yubihsm.defs.ALGORITHM.AES128_CCM_WRAP`
        - :class:`~yubihsm.defs.ALGORITHM.AES192_CCM_WRAP`
        - :class:`~yubihsm.defs.ALGORITHM.AES256_CCM_WRAP`
        - :class:`~yubihsm.defs.ALGORITHM.RSA_2048`
        - :class:`~yubihsm.defs.ALGORITHM.RSA_3072`
        - :class:`~yubihsm.defs.ALGORITHM.RSA_4096`
    """

    object_type = OBJECT.WRAP_KEY

    @classmethod
    def generate(
        cls,
        session: "core.AuthSession",
        object_id: int,
        label: str,
        domains: int,
        capabilities: CAPABILITY,
        algorithm: ALGORITHM,
        delegated_capabilities: CAPABILITY,
    ) -> "WrapKey":
        """Generate a new wrap key in the YubiHSM.

        :param session: The session to import via.
        :param object_id: The ID to set for the object. Set to 0 to let the YubiHSM
            designate an ID.
        :param label: A text label to give the object.
        :param domains: The set of domains to assign the object to.
        :param capabilities: The set of capabilities to give the object.
        :param algorithm: The algorithm to use for the wrap key.
        :return: A reference to the newly created object.
        """
        if algorithm not in [
            ALGORITHM.AES128_CCM_WRAP,
            ALGORITHM.AES192_CCM_WRAP,
            ALGORITHM.AES256_CCM_WRAP,
            ALGORITHM.RSA_2048,
            ALGORITHM.RSA_3072,
            ALGORITHM.RSA_4096,
        ]:
            raise ValueError("Invalid algorithm")

        msg = struct.pack(
            "!H%dsHQBQ" % LABEL_LENGTH,
            object_id,
            _label_pack(label),
            domains,
            capabilities,
            algorithm,
            delegated_capabilities,
        )
        return cls._from_command(session, COMMAND.GENERATE_WRAP_KEY, msg)

    @classmethod
    def put(
        cls,
        session: "core.AuthSession",
        object_id: int,
        label: str,
        domains: int,
        capabilities: CAPABILITY,
        algorithm: ALGORITHM,
        delegated_capabilities: CAPABILITY,
        key: Union[bytes, rsa.RSAPrivateKey],
    ) -> "WrapKey":
        """Import a wrap key into the YubiHSM.

        Asymmetric keys can be imported using the cryptography API. You can
        then pass a
        :class:`~cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey`
        as `key`.

        :param session: The session to import via.
        :param object_id: The ID to set for the object. Set to 0 to let the YubiHSM
            designate an ID.
        :param label: A text label to give the object.
        :param domains: The set of domains to assign the object to.
        :param capabilities: The set of capabilities to give the object.
        :param algorithm: The algorithm to use for the wrap key.
        :param delegated_capabilities: The set of capabilities that the WrapKey can give
            to objects that it imports.
        :param key: The encryption key corresponding to the algorithm.
        :return: A reference to the newly created object.
        """
        if algorithm not in [
            ALGORITHM.AES128_CCM_WRAP,
            ALGORITHM.AES192_CCM_WRAP,
            ALGORITHM.AES256_CCM_WRAP,
            ALGORITHM.RSA_2048,
            ALGORITHM.RSA_3072,
            ALGORITHM.RSA_4096,
        ]:
            raise ValueError("Invalid algorithm")

        if isinstance(key, rsa.RSAPrivateKeyWithSerialization):
            rsa_numbers = key.private_numbers()
            if rsa_numbers.public_numbers.e != RSA_PUBLIC_EXPONENT:
                raise ValueError("Unsupported public exponent")
            if key.key_size not in RSA_SIZES:
                raise ValueError("Unsupported key size")
            algo = getattr(ALGORITHM, "RSA_%d" % key.key_size)
            if algo != algorithm:
                raise ValueError("Key does not match algorithm (%s)" % algorithm.name)
            key_data = int.to_bytes(
                rsa_numbers.p, key.key_size // 8 // 2, "big"
            ) + int.to_bytes(rsa_numbers.q, key.key_size // 8 // 2, "big")
        else:
            if len(key) != algorithm.to_key_size():
                raise ValueError(
                    "Key length (%d) not matching algorithm (%s)"
                    % (len(key), algorithm.name)
                )
            key_data = key

        msg = struct.pack(
            "!H%dsHQBQ" % LABEL_LENGTH,
            object_id,
            _label_pack(label),
            domains,
            capabilities,
            algorithm,
            delegated_capabilities,
        )
        msg += key_data
        return cls._from_command(session, COMMAND.PUT_WRAP_KEY, msg)

    def get_public_key(self) -> rsa.RSAPublicKey:
        """Get the public key of the wrapkey pair."""
        msg = struct.pack("!HB", self.id, self.object_type)
        ret = self.session.send_secure_cmd(COMMAND.GET_PUBLIC_KEY, msg)
        raw_key = ret[1:]
        num = int.from_bytes(raw_key, "big")
        return rsa.RSAPublicNumbers(e=RSA_PUBLIC_EXPONENT, n=num).public_key(
            backend=default_backend()
        )

    def wrap_data(self, data: bytes) -> bytes:
        """Wrap (encrypt) arbitrary data.

        :param data: The data to encrypt.
        :return: The encrypted data.
        """
        msg = struct.pack("!H", self.id) + data
        return self.session.send_secure_cmd(COMMAND.WRAP_DATA, msg)

    def unwrap_data(self, data: bytes) -> bytes:
        """Unwrap (decrypt) arbitrary data.

        :param data: The encrypted data to decrypt.
        :return: The decrypted data.
        """
        msg = struct.pack("!H", self.id) + data
        return self.session.send_secure_cmd(COMMAND.UNWRAP_DATA, msg)

    def export_wrapped(self, obj: YhsmObject, seed: bool = False) -> bytes:
        """Export an object under wrap.

        :param obj: The object to export.
        :param seed: (optional) Export key with seed. Only applicable
            for ed25519 key objects.
        :return: The encrypted object data.
        """
        if seed:
            msg = struct.pack("!HBHB", self.id, obj.object_type, obj.id, 1)
        else:
            msg = struct.pack("!HBH", self.id, obj.object_type, obj.id)
        return self.session.send_secure_cmd(COMMAND.EXPORT_WRAPPED, msg)

    def import_wrapped(self, wrapped_obj: bytes) -> YhsmObject:
        """Import an object previously exported under wrap.

        :param wraped_obj: The encrypted object data.
        :return: A reference to the imported object.
        """
        msg = struct.pack("!H", self.id) + wrapped_obj
        ret = self.session.send_secure_cmd(COMMAND.IMPORT_WRAPPED, msg)
        object_type, object_id = struct.unpack("!BH", ret)
        return YhsmObject._create(object_type, self.session, object_id)

    def import_wrapped_rsa(
        self,
        wrapped_obj: bytes,
        oaep_hash: hashes.HashAlgorithm = hashes.SHA256(),
        mgf_hash: hashes.HashAlgorithm = hashes.SHA256(),
        oaep_label: bytes = b"",
    ) -> YhsmObject:
        """Import an object previously exported under asymmetric wrap.

        :param wrapped_obj: The encrypted object data.
        :param oaep_hash: (optional) The hash algorithm to use for OAEP label.
        :param mgf_hash: (optional) The hash algorithm to use for MGF1.
        :param oaep_label: (optional) OAEP label.
        :return: A reference to the imported object.
        """
        digest = hashes.Hash(oaep_hash, backend=default_backend())
        digest.update(oaep_label)

        hash = getattr(ALGORITHM, "RSA_OAEP_%s" % oaep_hash.name.upper())
        mgf = getattr(ALGORITHM, "RSA_MGF1_%s" % mgf_hash.name.upper())

        msg = struct.pack("!HBB", self.id, hash, mgf) + wrapped_obj + digest.finalize()
        ret = self.session.send_secure_cmd(COMMAND.IMPORT_WRAPPED_RSA, msg)
        object_type, object_id = struct.unpack("!BH", ret)
        return YhsmObject._create(object_type, self.session, object_id)

    def import_raw_key(
        self,
        object_id: int,
        object_type: OBJECT,
        label: str,
        domains: int,
        capabilities: CAPABILITY,
        algorithm: ALGORITHM,
        wrapped: bytes,
        oaep_hash: hashes.HashAlgorithm = hashes.SHA256(),
        mgf_hash: hashes.HashAlgorithm = hashes.SHA256(),
        oaep_label: bytes = b"",
    ) -> YhsmObject:
        """Import an (a)symmetric key previously exported under asymmetric wrap.

        Asymmetric keys are expected to have been serialized as
        PKCS#8.

        :param object_id: The ID to set for the object. Set to 0 to let the YubiHSM
            designate an ID.
        :param object_type: The key object type (`OBJECT.ASYMMETRIC_KEY`
            or `OBJECT.SYMMETRIC_KEY`).
        :param label: A text label to give the object.
        :param domains: The set of domains to assign the object to.
        :param capabilities: The set of capabilities to give the object.
        :param algorithm: The algorithm of the key.
        :param wrapped: The wrapped key object.
        :param oaep_hash: (optional) The hash algorithm to use for OAEP label.
        :param mgf_hash: (optional) The hash algorithm to use for MGF1.
        :param oaep_label: (optional) OAEP label.
        :return: A reference to the imported key object.
        """
        digest = hashes.Hash(oaep_hash, backend=default_backend())
        digest.update(oaep_label)

        hash = getattr(ALGORITHM, "RSA_OAEP_%s" % oaep_hash.name.upper())
        mgf = getattr(ALGORITHM, "RSA_MGF1_%s" % mgf_hash.name.upper())

        msg = (
            struct.pack(
                "!HBH%dsHQBBB" % LABEL_LENGTH,
                self.id,
                object_type,
                object_id,
                _label_pack(label),
                domains,
                capabilities,
                algorithm,
                hash,
                mgf,
            )
            + wrapped
            + digest.finalize()
        )
        ret = self.session.send_secure_cmd(COMMAND.UNWRAP_KEY_RSA, msg)
        object_type, object_id = struct.unpack("!BH", ret)
        return YhsmObject._create(object_type, self.session, object_id)


class PublicWrapKey(YhsmObject):
    """Used to export other objects under wrap using the public key of an
    asymmetric key pair.

    The algorithm used for wrapping is CKM_RSA_AES_KEY_WRAP,
    as specified in PKCS#11.

    Supported algorithms:
    - :class:`~yubihsm.defs.ALGORITHM.RSA_2048`
    - :class:`~yubihsm.defs.ALGORITHM.RSA_3072`
    - :class:`~yubihsm.defs.ALGORITHM.RSA_4096`
    """

    object_type = OBJECT.PUBLIC_WRAP_KEY

    @classmethod
    def put(
        cls,
        session: "core.AuthSession",
        object_id: int,
        label: str,
        domains: int,
        capabilities: CAPABILITY,
        delegated_capabilities: CAPABILITY,
        public_key: rsa.RSAPublicKey,
    ) -> "PublicWrapKey":
        """Import a public RSA wrapkey into the YubiHSM.

        The RSA public key can be supplied using the cryptography API. You can
        then pass a
        :class:`~cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey`
        as `public_key`.

        :param session: The session to import via.
        :param object_id: The ID to set for the object. Set to 0 to let the YubiHSM
            designate an ID.
        :param label: A text label to give the object.
        :param domains: The set of domains to assign the object to.
        :param capabilities: The set of capabilities to give the object.
        :param delegated_capabilities: The set of capabilities that the WrapKey can give
            to objects that it imports.
        :param public_key: The public key to import.
        :return: A reference to the newly created object.
        """
        algorithm = getattr(ALGORITHM, "RSA_%d" % public_key.key_size)
        if algorithm not in [
            ALGORITHM.RSA_2048,
            ALGORITHM.RSA_3072,
            ALGORITHM.RSA_4096,
        ]:
            raise ValueError("Invalid algorithm")

        public_numbers = public_key.public_numbers()
        if public_numbers.e != RSA_PUBLIC_EXPONENT:
            raise ValueError("Unsupported public exponent")
        serialized = public_numbers.n.to_bytes((public_key.key_size + 7) // 8, "big")

        msg = (
            struct.pack(
                "!H%dsHQBQ" % LABEL_LENGTH,
                object_id,
                _label_pack(label),
                domains,
                capabilities,
                algorithm,
                delegated_capabilities,
            )
            + serialized
        )

        return cls._from_command(session, COMMAND.PUT_PUBLIC_WRAP_KEY, msg)

    def get_public_key(self) -> rsa.RSAPublicKey:
        """Get the public wrapkey."""
        msg = struct.pack("!HB", self.id, self.object_type)
        ret = self.session.send_secure_cmd(COMMAND.GET_PUBLIC_KEY, msg)
        raw_key = ret[1:]
        num = int.from_bytes(raw_key, "big")
        return rsa.RSAPublicNumbers(e=RSA_PUBLIC_EXPONENT, n=num).public_key(
            backend=default_backend()
        )

    def _rsa_wrap_cmd_data(
        self,
        obj: YhsmObject,
        algorithm: ALGORITHM,
        oaep_hash: hashes.HashAlgorithm,
        mgf_hash: hashes.HashAlgorithm,
        oaep_label: bytes,
    ) -> bytes:
        digest = hashes.Hash(oaep_hash, backend=default_backend())
        digest.update(oaep_label)

        hash = getattr(ALGORITHM, "RSA_OAEP_%s" % oaep_hash.name.upper())
        mgf = getattr(ALGORITHM, "RSA_MGF1_%s" % mgf_hash.name.upper())

        msg = (
            struct.pack(
                "!HBHBBB",
                self.id,
                obj.object_type,
                obj.id,
                algorithm,
                hash,
                mgf,
            )
            + digest.finalize()
        )

        return msg

    def export_wrapped_rsa(
        self,
        obj: YhsmObject,
        algorithm: ALGORITHM = ALGORITHM.AES256,
        oaep_hash: hashes.HashAlgorithm = hashes.SHA256(),
        mgf_hash: hashes.HashAlgorithm = hashes.SHA256(),
        oaep_label: bytes = b"",
    ) -> bytes:
        """Export an object under asymmetric wrap.

        :param obj: The object to export.
        :param algorithm: (optional) The algorithm to use for the ephemeral key.
        :param oaep_hash: (optional) The hash algorithm to use for OAEP label.
        :param mgf_hash: (optional) The hash algorithm to use for MGF1.
        :param oaep_label: (optional) OAEP label.
        :return: The encrypted object data.
        """
        msg = self._rsa_wrap_cmd_data(
            obj,
            algorithm,
            oaep_hash,
            mgf_hash,
            oaep_label,
        )

        return self.session.send_secure_cmd(COMMAND.EXPORT_WRAPPED_RSA, msg)

    def export_raw_key(
        self,
        key: Union[AsymmetricKey, "SymmetricKey"],
        algorithm: ALGORITHM = ALGORITHM.AES256,
        oaep_hash: hashes.HashAlgorithm = hashes.SHA256(),
        mgf_hash: hashes.HashAlgorithm = hashes.SHA256(),
        oaep_label: bytes = b"",
    ) -> bytes:
        """Export an (a)symmetric key object under asymmetric wrap.

        This command wraps only the raw key material of the key object.
        Asymmetric keys are serialized as PKCS#8.

        :param key: The (a)symmetric key object to wrap.
        :param algorithm: (optional) The algorithm for the ephemeral key.
        :param oaep_hash: (optional) The hash algorithm to use for OAEP label.
        :param mgf_hash: (optional) The hash algorithm to use for MGF1.
        :param oaep_label: (optional) OAEP label.
        :return: The encrypted key.
        """
        msg = self._rsa_wrap_cmd_data(
            key,
            algorithm,
            oaep_hash,
            mgf_hash,
            oaep_label,
        )

        return self.session.send_secure_cmd(COMMAND.WRAP_KEY_RSA, msg)


class HmacKey(YhsmObject):
    """Used to calculate and verify HMAC signatures.

    Supported algorithms:
        - :class:`~yubihsm.defs.ALGORITHM.HMAC_SHA1`
        - :class:`~yubihsm.defs.ALGORITHM.HMAC_SHA256`
        - :class:`~yubihsm.defs.ALGORITHM.HMAC_SHA384`
        - :class:`~yubihsm.defs.ALGORITHM.HMAC_SHA512`
    """

    object_type = OBJECT.HMAC_KEY

    @classmethod
    def generate(
        cls,
        session: "core.AuthSession",
        object_id: int,
        label: str,
        domains: int,
        capabilities: CAPABILITY,
        algorithm: ALGORITHM = ALGORITHM.HMAC_SHA256,
    ) -> "HmacKey":
        """Generate a new HMAC key in the YubiHSM.

        :param session: The session to import via.
        :param object_id: The ID to set for the object. Set to 0 to let the YubiHSM
            designate an ID.
        :param label: A text label to give the object.
        :param domains: The set of domains to assign the object to.
        :param capabilities: The set of capabilities to give the object.
        :param algorithm: (optional) The algorithm to use for the HMAC key.
        :return: A reference to the newly created object.
        """
        if algorithm not in [
            ALGORITHM.HMAC_SHA1,
            ALGORITHM.HMAC_SHA256,
            ALGORITHM.HMAC_SHA384,
            ALGORITHM.HMAC_SHA512,
        ]:
            raise ValueError("Invalid algorithm")

        msg = struct.pack(
            "!H%dsHQB" % LABEL_LENGTH,
            object_id,
            _label_pack(label),
            domains,
            capabilities,
            algorithm,
        )
        return cls._from_command(session, COMMAND.GENERATE_HMAC_KEY, msg)

    @classmethod
    def put(
        cls,
        session: "core.AuthSession",
        object_id: int,
        label: str,
        domains: int,
        capabilities: CAPABILITY,
        key: bytes,
        algorithm=ALGORITHM.HMAC_SHA256,
    ) -> "HmacKey":
        """Import an HMAC key into the YubiHSM.

        :param session: The session to import via.
        :param object_id: The ID to set for the object. Set to 0 to let the YubiHSM
            designate an ID.
        :param label: A text label to give the object.
        :param domains: The set of domains to assign the object to.
        :param capabilities: The set of capabilities to give the object.
        :param key: The raw key corresponding to the algorithm.
        :param algorithm: (optional) The algorithm to use for the HMAC key.
        :return: A reference to the newly created object.
        """

        if algorithm not in [
            ALGORITHM.HMAC_SHA1,
            ALGORITHM.HMAC_SHA256,
            ALGORITHM.HMAC_SHA384,
            ALGORITHM.HMAC_SHA512,
        ]:
            raise ValueError("Invalid algorithm")

        if len(key) > algorithm.to_key_size():
            # Hash key using corresponding hash algorithm
            key = _calc_hash(key, algorithm.to_hash_algorithm())

        msg = (
            struct.pack(
                "!H%dsHQB" % LABEL_LENGTH,
                object_id,
                _label_pack(label),
                domains,
                capabilities,
                algorithm,
            )
            + key
        )
        return cls._from_command(session, COMMAND.PUT_HMAC_KEY, msg)

    def sign_hmac(self, data: bytes) -> bytes:
        """Calculate the HMAC signature of the given data.

        :param data: The data to sign.
        :return: The signature.
        """
        msg = struct.pack("!H", self.id) + data
        return self.session.send_secure_cmd(COMMAND.SIGN_HMAC, msg)

    def verify_hmac(self, signature: bytes, data: bytes) -> bool:
        """Verify an HMAC signature.

        :param signature: The signature to verify.
        :param data: The data to verify the signature against.
        :return: True if verification succeeded, False if not.
        """
        msg = struct.pack("!H", self.id) + signature + data
        return self.session.send_secure_cmd(COMMAND.VERIFY_HMAC, msg) == b"\1"


class Template(YhsmObject):
    """Binary template used to validate SSH certificate requests.

    Supported algorithms:
        - :class:`~yubihsm.defs.ALGORITHM.TEMPLATE_SSH`
    """

    object_type = OBJECT.TEMPLATE

    @classmethod
    def put(
        cls,
        session: "core.AuthSession",
        object_id: int,
        label: str,
        domains: int,
        capabilities: CAPABILITY,
        algorithm: ALGORITHM,
        data: bytes,
    ) -> "Template":
        """Import a Template into the YubiHSM.

        :param session: The session to import via.
        :param object_id: The ID to set for the object. Set to 0 to let the
            YubiHSM designate an ID.
        :param label: A text label to give the object.
        :param domains: The set of domains to assign the object to.
        :param capabilities: The set of capabilities to give the object.
        :param algorithm: The algorithm to use for the template.
        :param data: The template data.
        :return: A reference to the newly created object.
        """
        msg = struct.pack(
            "!H%dsHQB" % LABEL_LENGTH,
            object_id,
            _label_pack(label),
            domains,
            capabilities,
            algorithm,
        )
        msg += data
        return cls._from_command(session, COMMAND.PUT_TEMPLATE, msg)

    def get(self) -> bytes:
        """Read a Template from the YubiHSM.

        :return: The template data.
        """
        msg = struct.pack("!H", self.id)
        return self.session.send_secure_cmd(COMMAND.GET_TEMPLATE, msg)


class OtpData(NamedTuple):
    """Decrypted OTP counter values.

    :param use_counter: 16 bit counter incremented on each power cycle.
    :param session_counter: 8 bit counter incremented on each touch.
    :param timestamp_high: 8 bit high part of the timestamp.
    :param timestamp_low: 16 bit low part of the timestamp.
    """

    use_counter: int
    session_counter: int
    timestamp_high: int
    timestamp_low: int


class OtpAeadKey(YhsmObject):
    """Used to decrypt and use a Yubico OTP AEAD for OTP decryption.

    Supported algorithms:
        - :class:`~yubihsm.defs.ALGORITHM.AES128_YUBICO_OTP`
        - :class:`~yubihsm.defs.ALGORITHM.AES192_YUBICO_OTP`
        - :class:`~yubihsm.defs.ALGORITHM.AES256_YUBICO_OTP`
    """

    object_type = OBJECT.OTP_AEAD_KEY

    @classmethod
    def put(
        cls,
        session: "core.AuthSession",
        object_id: int,
        label: str,
        domains: int,
        capabilities: CAPABILITY,
        algorithm: ALGORITHM,
        nonce_id: int,
        key: bytes,
    ) -> "OtpAeadKey":
        """Import an OTP AEAD key into the YubiHSM.

        :param session: The session to import via.
        :param object_id: The ID to set for the object. Set to 0 to let the
            YubiHSM designate an ID.
        :param label: A text label to give the object.
        :param domains: The set of domains to assign the object to.
        :param capabilities: The set of capabilities to give the object.
        :param algorithm: The algorithm to use for the key.
        :param nonce_id: The nonce ID used for AEADs.
        :param key: The key to import, corresponding to the algorithm.
        :return: A reference to the newly created object.

        """
        if algorithm not in [
            ALGORITHM.AES128_YUBICO_OTP,
            ALGORITHM.AES192_YUBICO_OTP,
            ALGORITHM.AES256_YUBICO_OTP,
        ]:
            raise ValueError("Invalid algorithm")

        if len(key) != algorithm.to_key_size():
            raise ValueError(
                "Key length (%d) not matching algorithm (%s)"
                % (len(key), algorithm.name)
            )

        msg = struct.pack(
            "!H%dsHQB" % LABEL_LENGTH,
            object_id,
            _label_pack(label),
            domains,
            capabilities,
            algorithm,
        ) + struct.pack("<I", nonce_id)  # nonce ID is stored in little-endian.
        msg += key
        return cls._from_command(session, COMMAND.PUT_OTP_AEAD_KEY, msg)

    @classmethod
    def generate(
        cls,
        session: "core.AuthSession",
        object_id: int,
        label: str,
        domains: int,
        capabilities: CAPABILITY,
        algorithm: ALGORITHM,
        nonce_id: int,
    ) -> "OtpAeadKey":
        """Generate a new OTP AEAD key in the YubiHSM.

        :param session: The session to import via.
        :param object_id: The ID to set for the object. Set to 0 to let the
            YubiHSM designate an ID.
        :param label: A text label to give the object.
        :param domains: The set of domains to assign the object to.
        :param capabilities: The set of capabilities to give the object.
        :param algorithm: The algorithm to use for the key.
        :param nonce_id: The nonce ID used for AEADs.
        :return: A reference to the newly created object.
        """

        if algorithm not in [
            ALGORITHM.AES128_YUBICO_OTP,
            ALGORITHM.AES192_YUBICO_OTP,
            ALGORITHM.AES256_YUBICO_OTP,
        ]:
            raise ValueError("Invalid algorithm")

        msg = struct.pack(
            "!H%dsHQBL" % LABEL_LENGTH,
            object_id,
            _label_pack(label),
            domains,
            capabilities,
            algorithm,
            nonce_id,
        )
        return cls._from_command(session, COMMAND.GENERATE_OTP_AEAD_KEY, msg)

    def create_otp_aead(self, key: bytes, identity: bytes) -> bytes:
        """Create a new Yubico OTP credential AEAD.

        :param key: 16 byte AES key for the credential.
        :param identity: 6 byte private ID for the credential.
        :return: A new AEAD.
        """
        msg = struct.pack("!H", self.id) + key + identity
        return self.session.send_secure_cmd(COMMAND.CREATE_OTP_AEAD, msg)

    def randomize_otp_aead(self) -> bytes:
        """Create a new Yubico OTP credential AEAD using random data.

        :return: A new AEAD.
        """
        msg = struct.pack("!H", self.id)
        return self.session.send_secure_cmd(COMMAND.RANDOMIZE_OTP_AEAD, msg)

    def decrypt_otp(self, aead: bytes, otp: bytes) -> OtpData:
        """Decrypt a Yubico OTP using an AEAD.

        :param aead: The AEAD containing encrypted credential data.
        :param otp: The 16 byte encrypted OTP payload to decrypt.
        :return: The decrypted OTP data.
        """
        msg = struct.pack("!H", self.id) + aead + otp
        resp = self.session.send_secure_cmd(COMMAND.DECRYPT_OTP, msg)
        return OtpData(*struct.unpack("<HBBH", resp))

    def rewrap_otp_aead(self, new_key_id: int, aead: bytes) -> bytes:
        """Decrypt and re-encrypt an AEAD from one key to another.

        :param new_key_id: The ID of the OtpAeadKey to wrap to.
        :param aead: The AEAD to re-wrap.
        :return: The new AEAD.
        """
        msg = struct.pack("!HH", self.id, new_key_id) + aead
        return self.session.send_secure_cmd(COMMAND.REWRAP_OTP_AEAD, msg)


class SymmetricKey(YhsmObject):
    """Used to encrypt/decrypt data using a symmetric key.

    Supported algorithms:
        - :class:`~yubihsm.defs.ALGORITHM.AES128`
        - :class:`~yubihsm.defs.ALGORITHM.AES192`
        - :class:`~yubihsm.defs.ALGORITHM.AES256`
    """

    object_type = OBJECT.SYMMETRIC_KEY

    @classmethod
    def put(
        cls,
        session: "core.AuthSession",
        object_id: int,
        label: str,
        domains: int,
        capabilities: CAPABILITY,
        algorithm: ALGORITHM,
        key: bytes,
    ) -> "SymmetricKey":
        """Import a symmetric key into the YubiHSM.

        :param session: The session to import via.
        :param object_id: The ID to set for the object. Set to 0 to let the
            YubiHSM designate an ID.
        :param label: A text label to give the object.
        :param domains: The set of domains to assign the object to.
        :param capabilities: The set of capabilities to give the object.
        :param algorithm: The algorithm to use for the symmetric key.
        :param key: The raw encryption key corresponding to the algorithm.
        :return: A reference to the newly created object.
        """

        if algorithm not in [ALGORITHM.AES128, ALGORITHM.AES192, ALGORITHM.AES256]:
            raise ValueError("Invalid algorithm")

        if len(key) != algorithm.to_key_size():
            raise ValueError(
                "Key length (%d) not matching algorithm (%s)"
                % (len(key), algorithm.name)
            )

        msg = struct.pack(
            "!H%dsHQB" % LABEL_LENGTH,
            object_id,
            _label_pack(label),
            domains,
            capabilities,
            algorithm,
        )
        msg += key

        return cls._from_command(session, COMMAND.PUT_SYMMETRIC_KEY, msg)

    @classmethod
    def generate(
        cls,
        session: "core.AuthSession",
        object_id: int,
        label: str,
        domains: int,
        capabilities: CAPABILITY,
        algorithm: ALGORITHM,
    ) -> "SymmetricKey":
        """Generate a new symmetric key in the YubiHSM.

        :param session: The session to import via.
        :param object_id: The ID to set for the object. Set to 0 to let the YubiHSM
            designate an ID.
        :param label: A text label to give the object.
        :param domains: The set of domains to assign the object to.
        :param capabilities: The set of capabilities to give the object.
        :param algorithm: The algorithm to use for the symmetric key.
        :return: A reference to the newly created object.

        """

        if algorithm not in [ALGORITHM.AES128, ALGORITHM.AES192, ALGORITHM.AES256]:
            raise ValueError("Invalid algorithm")

        msg = struct.pack(
            "!H%dsHQB" % LABEL_LENGTH,
            object_id,
            _label_pack(label),
            domains,
            capabilities,
            algorithm,
        )
        return cls._from_command(session, COMMAND.GENERATE_SYMMETRIC_KEY, msg)

    def _chain_ecb(self, cmd: COMMAND, data: bytes) -> bytes:
        if len(data) % AES_BLOCK_SIZE != 0:
            raise ValueError("Data is not a multiple of %d bytes" % AES_BLOCK_SIZE)

        chunk_size = MAX_AES_PAYLOAD_SIZE // AES_BLOCK_SIZE * AES_BLOCK_SIZE

        out = b""
        rem = data

        while rem:
            if len(rem) <= chunk_size:
                chunk_in = rem
                rem = b""
            else:
                chunk_in = rem[:chunk_size]
                rem = rem[chunk_size:]

            msg = struct.pack("!H", self.id) + chunk_in
            chunk_out = self.session.send_secure_cmd(cmd, msg)

            out += chunk_out

        return out

    def _chain_cbc(self, cmd: COMMAND, iv: bytes, data: bytes) -> bytes:
        if len(iv) != AES_BLOCK_SIZE:
            raise ValueError("IV is not 16 bytes")
        if len(data) % AES_BLOCK_SIZE != 0:
            raise ValueError("Data is not a multiple of %d bytes" % AES_BLOCK_SIZE)

        chunk_size = (MAX_AES_PAYLOAD_SIZE - len(iv)) // AES_BLOCK_SIZE * AES_BLOCK_SIZE

        out = b""
        rem = data

        while rem:
            if len(rem) <= chunk_size:
                chunk_in = rem
                rem = b""
            else:
                chunk_in = rem[:chunk_size]
                rem = rem[chunk_size:]

            msg = struct.pack("!H", self.id) + iv + chunk_in
            chunk_out = self.session.send_secure_cmd(cmd, msg)
            out += chunk_out
            iv = (
                out[-AES_BLOCK_SIZE:]
                if cmd == COMMAND.ENCRYPT_CBC
                else chunk_in[-AES_BLOCK_SIZE:]
            )

        return out

    def encrypt_ecb(self, data: bytes) -> bytes:
        """Encrypt data in ECB mode.

        :param data: The data to encrypt.
        :return: The encrypted data.
        """

        return self._chain_ecb(COMMAND.ENCRYPT_ECB, data)

    def decrypt_ecb(self, data: bytes) -> bytes:
        """Decrypt data in ECB mode.

        :param data: The data to decrypt.
        :return: The decrypted data.
        """

        return self._chain_ecb(COMMAND.DECRYPT_ECB, data)

    def encrypt_cbc(self, iv: bytes, data: bytes) -> bytes:
        """Encrypt data in CBC mode.

        :param iv: The initialization vector.
        :param data: The data to encrypt.
        :return: The encrypted data.
        """

        return self._chain_cbc(COMMAND.ENCRYPT_CBC, iv, data)

    def decrypt_cbc(self, iv: bytes, data: bytes) -> bytes:
        """Decrypt data in CBC mode.

        :param iv: The initialization vector.
        :param data: The data to decrypt.
        :return: The decrypted data.
        """

        return self._chain_cbc(COMMAND.DECRYPT_CBC, iv, data)