Debian Codegraph @

ansible_collections/community/crypto/plugins/module_utils/_openssh/cryptography.py

raw
1 # Copyright (c) 2021, Andrew Pantuso (@ajpantuso) <[email protected]>
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
6 # Do not use this from other collections or standalone plugins/modules!
7
8 from __future__ import annotations
9
10 import os
11 import typing as t
12 from base64 import b64decode, b64encode
13 from getpass import getuser
14 from socket import gethostname
15
16 try:
17 from cryptography import __version__ as CRYPTOGRAPHY_VERSION
18 from cryptography.exceptions import InvalidSignature, UnsupportedAlgorithm
19 from cryptography.hazmat.primitives import hashes, serialization
20 from cryptography.hazmat.primitives.asymmetric import dsa, ec, padding, rsa
21 from cryptography.hazmat.primitives.asymmetric.ed448 import Ed448PrivateKey
22 from cryptography.hazmat.primitives.asymmetric.ed25519 import (
23 Ed25519PrivateKey,
24 Ed25519PublicKey,
25 )
26
27 HAS_OPENSSH_SUPPORT = True
28
29 _ALGORITHM_PARAMETERS = {
30 "rsa": {
31 "default_size": 2048,
32 "valid_sizes": range(1024, 16384),
33 "signer_params": {
34 "padding": padding.PSS(
35 mgf=padding.MGF1(hashes.SHA256()),
36 salt_length=padding.PSS.MAX_LENGTH,
37 ),
38 "algorithm": hashes.SHA256(),
39 },
40 },
41 "dsa": {
42 "default_size": 1024,
43 "valid_sizes": [1024],
44 "signer_params": {
45 "algorithm": hashes.SHA256(),
46 },
47 },
48 "ed25519": {
49 "default_size": 256,
50 "valid_sizes": [256],
51 "signer_params": {},
52 },
53 "ecdsa": {
54 "default_size": 256,
55 "valid_sizes": [256, 384, 521],
56 "signer_params": {
57 "signature_algorithm": ec.ECDSA(hashes.SHA256()),
58 },
59 "curves": {
60 256: ec.SECP256R1(),
61 384: ec.SECP384R1(),
62 521: ec.SECP521R1(),
63 },
64 },
65 }
66 except ImportError:
67 HAS_OPENSSH_SUPPORT = False
68 CRYPTOGRAPHY_VERSION = "0.0"
69 _ALGORITHM_PARAMETERS = {}
70
71 from ansible_collections.community.crypto.plugins.module_utils._crypto.cryptography_support import (
72 is_potential_certificate_issuer_private_key,
73 )
74
75 if t.TYPE_CHECKING:
76 KeyFormat = t.Literal["SSH", "PKCS8", "PKCS1"] # pragma: no cover
77 KeySerializationFormat = t.Literal["PEM", "DER", "SSH"] # pragma: no cover
78 KeyType = t.Literal["rsa", "dsa", "ed25519", "ecdsa"] # pragma: no cover
79 PubKeyType = t.Literal[
80 "rsa", "dsa", "ed25519", "ecdsa-nistp256", "ecdsa-nistp384", "ecdsa-nistp521"
81 ] # pragma: no cover
82
83 PrivateKeyTypes = t.Union[ # noqa: UP007
84 rsa.RSAPrivateKey,
85 dsa.DSAPrivateKey,
86 ec.EllipticCurvePrivateKey,
87 Ed25519PrivateKey,
88 ] # pragma: no cover
89 PublicKeyTypes = t.Union[ # noqa: UP007
90 rsa.RSAPublicKey, dsa.DSAPublicKey, ec.EllipticCurvePublicKey, Ed25519PublicKey
91 ] # pragma: no cover
92
93 from cryptography.hazmat.primitives.asymmetric.types import (
94 PublicKeyTypes as AllPublicKeyTypes, # pragma: no cover
95 )
96
97
98 _TEXT_ENCODING = "UTF-8"
99
100
101 class OpenSSHError(Exception):
102 pass
103
104
105 class InvalidAlgorithmError(OpenSSHError):
106 pass
107
108
109 class InvalidCommentError(OpenSSHError):
110 pass
111
112
113 class InvalidDataError(OpenSSHError):
114 pass
115
116
117 class InvalidPrivateKeyFileError(OpenSSHError):
118 pass
119
120
121 class InvalidPublicKeyFileError(OpenSSHError):
122 pass
123
124
125 class InvalidKeyFormatError(OpenSSHError):
126 pass
127
128
129 class InvalidKeySizeError(OpenSSHError):
130 pass
131
132
133 class InvalidKeyTypeError(OpenSSHError):
134 pass
135
136
137 class InvalidPassphraseError(OpenSSHError):
138 pass
139
140
141 class InvalidSignatureError(OpenSSHError):
142 pass
143
144
145 _AsymmetricKeypair = t.TypeVar("_AsymmetricKeypair", bound="AsymmetricKeypair")
146
147
148 class AsymmetricKeypair:
149 """Container for newly generated asymmetric key pairs or those loaded from existing files"""
150
151 @classmethod
152 def generate(
153 cls: type[_AsymmetricKeypair],
154 *,
155 keytype: KeyType = "rsa",
156 size: int | None = None,
157 passphrase: bytes | None = None,
158 ) -> _AsymmetricKeypair:
159 """Returns an Asymmetric_Keypair object generated with the supplied parameters
160 or defaults to an unencrypted RSA-2048 key
161
162 :keytype: One of rsa, dsa, ecdsa, ed25519
163 :size: The key length for newly generated keys
164 :passphrase: Secret of type Bytes used to encrypt the private key being generated
165 """
166
167 if keytype not in _ALGORITHM_PARAMETERS:
168 raise InvalidKeyTypeError(
169 f"{keytype} is not a valid keytype. Valid keytypes are {', '.join(_ALGORITHM_PARAMETERS)}"
170 )
171
172 if not size:
173 size = _ALGORITHM_PARAMETERS[keytype]["default_size"] # type: ignore
174 else:
175 if size not in _ALGORITHM_PARAMETERS[keytype]["valid_sizes"]: # type: ignore
176 raise InvalidKeySizeError(
177 f"{size} is not a valid key size for {keytype} keys"
178 )
179 size = t.cast(int, size)
180
181 privatekey: PrivateKeyTypes
182 if passphrase:
183 encryption_algorithm = get_encryption_algorithm(passphrase)
184 else:
185 encryption_algorithm = serialization.NoEncryption()
186
187 if keytype == "rsa":
188 privatekey = rsa.generate_private_key(
189 # Public exponent should always be 65537 to prevent issues
190 # if improper padding is used during signing
191 public_exponent=65537,
192 key_size=size,
193 )
194 elif keytype == "dsa":
195 privatekey = dsa.generate_private_key(
196 key_size=size,
197 )
198 elif keytype == "ed25519":
199 privatekey = Ed25519PrivateKey.generate()
200 elif keytype == "ecdsa":
201 privatekey = ec.generate_private_key(
202 _ALGORITHM_PARAMETERS["ecdsa"]["curves"][size], # type: ignore
203 )
204
205 publickey = privatekey.public_key()
206
207 return cls(
208 keytype=keytype,
209 size=size,
210 privatekey=privatekey,
211 publickey=publickey,
212 encryption_algorithm=encryption_algorithm,
213 )
214
215 @classmethod
216 def load(
217 cls: type[_AsymmetricKeypair],
218 *,
219 path: str | os.PathLike,
220 passphrase: bytes | None = None,
221 private_key_format: KeySerializationFormat = "PEM",
222 public_key_format: KeySerializationFormat = "PEM",
223 no_public_key: bool = False,
224 ) -> _AsymmetricKeypair:
225 """Returns an Asymmetric_Keypair object loaded from the supplied file path
226
227 :path: A path to an existing private key to be loaded
228 :passphrase: Secret of type bytes used to decrypt the private key being loaded
229 :private_key_format: Format of private key to be loaded
230 :public_key_format: Format of public key to be loaded
231 :no_public_key: Set 'True' to only load a private key and automatically populate the matching public key
232 """
233
234 if passphrase:
235 encryption_algorithm = get_encryption_algorithm(passphrase)
236 else:
237 encryption_algorithm = serialization.NoEncryption()
238
239 privatekey = load_privatekey(
240 path=path, passphrase=passphrase, key_format=private_key_format
241 )
242 publickey: AllPublicKeyTypes
243 if no_public_key:
244 publickey = privatekey.public_key()
245 else:
246 # TODO: Maybe we should check whether the public key actually fits the private key?
247 publickey = load_publickey(
248 path=str(path) + ".pub", key_format=public_key_format
249 )
250
251 # Ed25519 keys are always of size 256 and do not have a key_size attribute
252 if isinstance(privatekey, Ed25519PrivateKey):
253 size: int = _ALGORITHM_PARAMETERS["ed25519"]["default_size"] # type: ignore
254 else:
255 size = privatekey.key_size
256
257 keytype: KeyType
258 if isinstance(privatekey, rsa.RSAPrivateKey):
259 keytype = "rsa"
260 if not isinstance(publickey, rsa.RSAPublicKey):
261 raise InvalidKeyTypeError(
262 f"Private key is an RSA key, but public key is of type '{type(publickey)}'"
263 )
264 elif isinstance(privatekey, dsa.DSAPrivateKey):
265 keytype = "dsa"
266 if not isinstance(publickey, dsa.DSAPublicKey):
267 raise InvalidKeyTypeError(
268 f"Private key is a DSA key, but public key is of type '{type(publickey)}'"
269 )
270 elif isinstance(privatekey, ec.EllipticCurvePrivateKey):
271 keytype = "ecdsa"
272 if not isinstance(publickey, ec.EllipticCurvePublicKey):
273 raise InvalidKeyTypeError(
274 f"Private key is an Elliptic Curve key, but public key is of type '{type(publickey)}'"
275 )
276 elif isinstance(privatekey, Ed25519PrivateKey):
277 keytype = "ed25519"
278 if not isinstance(publickey, Ed25519PublicKey):
279 raise InvalidKeyTypeError(
280 f"Private key is an Ed25519 key, but public key is of type '{type(publickey)}'"
281 )
282 else:
283 raise InvalidKeyTypeError(f"Key type '{type(privatekey)}' is not supported")
284
285 return cls(
286 keytype=keytype,
287 size=size,
288 privatekey=privatekey,
289 publickey=publickey,
290 encryption_algorithm=encryption_algorithm,
291 )
292
293 def __init__(
294 self,
295 *,
296 keytype: KeyType,
297 size: int,
298 privatekey: PrivateKeyTypes,
299 publickey: PublicKeyTypes,
300 encryption_algorithm: serialization.KeySerializationEncryption,
301 ) -> None:
302 """
303 :keytype: One of rsa, dsa, ecdsa, ed25519
304 :size: The key length for the private key of this key pair
305 :privatekey: Private key object of this key pair
306 :publickey: Public key object of this key pair
307 :encryption_algorithm: Hashed secret used to encrypt the private key of this key pair
308 """
309
310 self.__size = size
311 self.__keytype = keytype
312 self.__privatekey = privatekey
313 self.__publickey = publickey
314 self.__encryption_algorithm = encryption_algorithm
315
316 try:
317 self.verify(signature=self.sign(b"message"), data=b"message")
318 except InvalidSignatureError as e:
319 raise InvalidPublicKeyFileError(
320 "The private key and public key of this keypair do not match"
321 ) from e
322
323 def __eq__(self, other: object) -> bool:
324 if not isinstance(other, AsymmetricKeypair):
325 return NotImplemented
326
327 return compare_publickeys(
328 self.public_key, other.public_key
329 ) and compare_encryption_algorithms(
330 self.encryption_algorithm, other.encryption_algorithm
331 )
332
333 def __ne__(self, other: object) -> bool:
334 return not self == other
335
336 @property
337 def private_key(self) -> PrivateKeyTypes:
338 """Returns the private key of this key pair"""
339
340 return self.__privatekey
341
342 @property
343 def public_key(self) -> PublicKeyTypes:
344 """Returns the public key of this key pair"""
345
346 return self.__publickey
347
348 @property
349 def size(self) -> int:
350 """Returns the size of the private key of this key pair"""
351
352 return self.__size
353
354 @property
355 def key_type(self) -> KeyType:
356 """Returns the key type of this key pair"""
357
358 return self.__keytype
359
360 @property
361 def encryption_algorithm(self) -> serialization.KeySerializationEncryption:
362 """Returns the key encryption algorithm of this key pair"""
363
364 return self.__encryption_algorithm
365
366 def sign(self, data: bytes) -> bytes:
367 """Returns signature of data signed with the private key of this key pair
368
369 :data: byteslike data to sign
370 """
371
372 try:
373 return self.__privatekey.sign(
374 data,
375 **_ALGORITHM_PARAMETERS[self.__keytype]["signer_params"], # type: ignore
376 )
377 except TypeError as e:
378 raise InvalidDataError(e) from e
379
380 def verify(self, *, signature: bytes, data: bytes) -> None:
381 """Verifies that the signature associated with the provided data was signed
382 by the private key of this key pair.
383
384 :signature: signature to verify
385 :data: byteslike data signed by the provided signature
386 """
387 try:
388 self.__publickey.verify(
389 signature,
390 data,
391 **_ALGORITHM_PARAMETERS[self.__keytype]["signer_params"], # type: ignore
392 )
393 except InvalidSignature as e:
394 raise InvalidSignatureError from e
395
396 def update_passphrase(self, passphrase: bytes | None = None) -> None:
397 """Updates the encryption algorithm of this key pair
398
399 :passphrase: Byte secret used to encrypt this key pair
400 """
401
402 if passphrase:
403 self.__encryption_algorithm = get_encryption_algorithm(passphrase)
404 else:
405 self.__encryption_algorithm = serialization.NoEncryption()
406
407
408 _OpensshKeypair = t.TypeVar("_OpensshKeypair", bound="OpensshKeypair")
409
410
411 class OpensshKeypair:
412 """Container for OpenSSH encoded asymmetric key pairs"""
413
414 @classmethod
415 def generate(
416 cls: type[_OpensshKeypair],
417 *,
418 keytype: KeyType = "rsa",
419 size: int | None = None,
420 passphrase: bytes | None = None,
421 comment: str | None = None,
422 ) -> _OpensshKeypair:
423 """Returns an Openssh_Keypair object generated using the supplied parameters or defaults to a RSA-2048 key
424
425 :keytype: One of rsa, dsa, ecdsa, ed25519
426 :size: The key length for newly generated keys
427 :passphrase: Secret of type Bytes used to encrypt the newly generated private key
428 :comment: Comment for a newly generated OpenSSH public key
429 """
430
431 if comment is None:
432 comment = f"{getuser()}@{gethostname()}"
433
434 asym_keypair = AsymmetricKeypair.generate(
435 keytype=keytype, size=size, passphrase=passphrase
436 )
437 openssh_privatekey = cls.encode_openssh_privatekey(
438 asym_keypair=asym_keypair, key_format="SSH"
439 )
440 openssh_publickey = cls.encode_openssh_publickey(
441 asym_keypair=asym_keypair, comment=comment
442 )
443 fingerprint = calculate_fingerprint(openssh_publickey)
444
445 return cls(
446 asym_keypair=asym_keypair,
447 openssh_privatekey=openssh_privatekey,
448 openssh_publickey=openssh_publickey,
449 fingerprint=fingerprint,
450 comment=comment,
451 )
452
453 @classmethod
454 def load(
455 cls: type[_OpensshKeypair],
456 *,
457 path: str | os.PathLike,
458 passphrase: bytes | None = None,
459 no_public_key: bool = False,
460 ) -> _OpensshKeypair:
461 """Returns an Openssh_Keypair object loaded from the supplied file path
462
463 :path: A path to an existing private key to be loaded
464 :passphrase: Secret used to decrypt the private key being loaded
465 :no_public_key: Set 'True' to only load a private key and automatically populate the matching public key
466 """
467
468 if no_public_key:
469 comment = ""
470 else:
471 comment = extract_comment(str(path) + ".pub")
472
473 asym_keypair = AsymmetricKeypair.load(
474 path=path,
475 passphrase=passphrase,
476 private_key_format="SSH",
477 public_key_format="SSH",
478 no_public_key=no_public_key,
479 )
480 openssh_privatekey = cls.encode_openssh_privatekey(
481 asym_keypair=asym_keypair, key_format="SSH"
482 )
483 openssh_publickey = cls.encode_openssh_publickey(
484 asym_keypair=asym_keypair, comment=comment
485 )
486 fingerprint = calculate_fingerprint(openssh_publickey)
487
488 return cls(
489 asym_keypair=asym_keypair,
490 openssh_privatekey=openssh_privatekey,
491 openssh_publickey=openssh_publickey,
492 fingerprint=fingerprint,
493 comment=comment,
494 )
495
496 @staticmethod
497 def encode_openssh_privatekey(
498 *, asym_keypair: AsymmetricKeypair, key_format: KeyFormat
499 ) -> bytes:
500 """Returns an OpenSSH encoded private key for a given keypair
501
502 :asym_keypair: Asymmetric_Keypair from the private key is extracted
503 :key_format: Format of the encoded private key.
504 """
505
506 if key_format == "SSH":
507 privatekey_format = serialization.PrivateFormat.OpenSSH
508 elif key_format == "PKCS8":
509 privatekey_format = serialization.PrivateFormat.PKCS8
510 elif key_format == "PKCS1":
511 if asym_keypair.key_type == "ed25519":
512 raise InvalidKeyFormatError(
513 "ed25519 keys cannot be represented in PKCS1 format"
514 )
515 privatekey_format = serialization.PrivateFormat.TraditionalOpenSSL
516 else:
517 raise InvalidKeyFormatError(
518 "The accepted private key formats are SSH, PKCS8, and PKCS1"
519 )
520
521 encoded_privatekey = asym_keypair.private_key.private_bytes(
522 encoding=serialization.Encoding.PEM,
523 format=privatekey_format,
524 encryption_algorithm=asym_keypair.encryption_algorithm,
525 )
526
527 return encoded_privatekey
528
529 @staticmethod
530 def encode_openssh_publickey(
531 *, asym_keypair: AsymmetricKeypair, comment: str
532 ) -> bytes:
533 """Returns an OpenSSH encoded public key for a given keypair
534
535 :asym_keypair: Asymmetric_Keypair from the public key is extracted
536 :comment: Comment to apply to the end of the returned OpenSSH encoded public key
537 """
538 encoded_publickey = asym_keypair.public_key.public_bytes(
539 encoding=serialization.Encoding.OpenSSH,
540 format=serialization.PublicFormat.OpenSSH,
541 )
542
543 validate_comment(comment)
544
545 encoded_publickey += (
546 (b" " + comment.encode(encoding=_TEXT_ENCODING)) if comment else b""
547 )
548
549 return encoded_publickey
550
551 def __init__(
552 self,
553 *,
554 asym_keypair: AsymmetricKeypair,
555 openssh_privatekey: bytes,
556 openssh_publickey: bytes,
557 fingerprint: str,
558 comment: str | None,
559 ) -> None:
560 """
561 :asym_keypair: An Asymmetric_Keypair object from which the OpenSSH encoded keypair is derived
562 :openssh_privatekey: An OpenSSH encoded private key
563 :openssh_privatekey: An OpenSSH encoded public key
564 :fingerprint: The fingerprint of the OpenSSH encoded public key of this keypair
565 :comment: Comment applied to the OpenSSH public key of this keypair
566 """
567
568 self.__asym_keypair = asym_keypair
569 self.__openssh_privatekey = openssh_privatekey
570 self.__openssh_publickey = openssh_publickey
571 self.__fingerprint = fingerprint
572 self.__comment = comment
573
574 def __eq__(self, other: object) -> bool:
575 if not isinstance(other, OpensshKeypair):
576 return NotImplemented
577
578 return (
579 self.asymmetric_keypair == other.asymmetric_keypair
580 and self.comment == other.comment
581 )
582
583 @property
584 def asymmetric_keypair(self) -> AsymmetricKeypair:
585 """Returns the underlying asymmetric key pair of this OpenSSH encoded key pair"""
586
587 return self.__asym_keypair
588
589 @property
590 def private_key(self) -> bytes:
591 """Returns the OpenSSH formatted private key of this key pair"""
592
593 return self.__openssh_privatekey
594
595 @property
596 def public_key(self) -> bytes:
597 """Returns the OpenSSH formatted public key of this key pair"""
598
599 return self.__openssh_publickey
600
601 @property
602 def size(self) -> int:
603 """Returns the size of the private key of this key pair"""
604
605 return self.__asym_keypair.size
606
607 @property
608 def key_type(self) -> KeyType:
609 """Returns the key type of this key pair"""
610
611 return self.__asym_keypair.key_type
612
613 @property
614 def fingerprint(self) -> str:
615 """Returns the fingerprint (SHA256 Hash) of the public key of this key pair"""
616
617 return self.__fingerprint
618
619 @property
620 def comment(self) -> str | None:
621 """Returns the comment applied to the OpenSSH formatted public key of this key pair"""
622
623 return self.__comment
624
625 @comment.setter
626 def comment(self, comment: str) -> bytes:
627 """Updates the comment applied to the OpenSSH formatted public key of this key pair
628
629 :comment: Text to update the OpenSSH public key comment
630 """
631
632 validate_comment(comment)
633
634 self.__comment = comment
635 encoded_comment = (
636 f" {self.__comment}".encode(encoding=_TEXT_ENCODING)
637 if self.__comment
638 else b""
639 )
640 self.__openssh_publickey = (
641 b" ".join(self.__openssh_publickey.split(b" ", 2)[:2]) + encoded_comment
642 )
643 return self.__openssh_publickey
644
645 def update_passphrase(self, passphrase: bytes | None) -> None:
646 """Updates the passphrase used to encrypt the private key of this keypair
647
648 :passphrase: Text secret used for encryption
649 """
650
651 self.__asym_keypair.update_passphrase(passphrase)
652 self.__openssh_privatekey = OpensshKeypair.encode_openssh_privatekey(
653 asym_keypair=self.__asym_keypair, key_format="SSH"
654 )
655
656
657 def load_privatekey(
658 *,
659 path: str | os.PathLike,
660 passphrase: bytes | None,
661 key_format: KeySerializationFormat,
662 ) -> PrivateKeyTypes:
663 privatekey_loaders = {
664 "PEM": serialization.load_pem_private_key,
665 "DER": serialization.load_der_private_key,
666 "SSH": serialization.load_ssh_private_key,
667 }
668
669 try:
670 privatekey_loader = privatekey_loaders[key_format]
671 except KeyError as e:
672 raise InvalidKeyFormatError(
673 f"{key_format} is not a valid key format ({','.join(privatekey_loaders)})"
674 ) from e
675
676 if not os.path.exists(path):
677 raise InvalidPrivateKeyFileError(f"No file was found at {path}")
678
679 try:
680 with open(path, "rb") as f:
681 content = f.read()
682
683 try:
684 privatekey = privatekey_loader(
685 data=content,
686 password=passphrase,
687 )
688 except ValueError as exc:
689 # Revert to PEM if key could not be loaded in SSH format
690 if key_format == "SSH":
691 privatekey = privatekey_loaders["PEM"](
692 data=content,
693 password=passphrase,
694 )
695 else:
696 raise InvalidPrivateKeyFileError(exc) from exc
697 except ValueError as e:
698 raise InvalidPrivateKeyFileError(e) from e
699 except TypeError as e:
700 raise InvalidPassphraseError(e) from e
701 except UnsupportedAlgorithm as e:
702 raise InvalidAlgorithmError(e) from e
703
704 if not is_potential_certificate_issuer_private_key(privatekey) or isinstance(
705 privatekey, Ed448PrivateKey
706 ):
707 raise InvalidPrivateKeyFileError(
708 f"{privatekey} is not a supported private key type"
709 )
710 return privatekey
711
712
713 def load_publickey(
714 *, path: str | os.PathLike, key_format: KeySerializationFormat
715 ) -> AllPublicKeyTypes:
716 publickey_loaders = {
717 "PEM": serialization.load_pem_public_key,
718 "DER": serialization.load_der_public_key,
719 "SSH": serialization.load_ssh_public_key,
720 }
721
722 try:
723 publickey_loader = publickey_loaders[key_format]
724 except KeyError as e:
725 raise InvalidKeyFormatError(
726 f"{key_format} is not a valid key format ({','.join(publickey_loaders)})"
727 ) from e
728
729 if not os.path.exists(path):
730 raise InvalidPublicKeyFileError(f"No file was found at {path}")
731
732 try:
733 with open(path, "rb") as f:
734 content = f.read()
735
736 publickey = publickey_loader(
737 data=content,
738 )
739 except ValueError as e:
740 raise InvalidPublicKeyFileError(e) from e
741 except UnsupportedAlgorithm as e:
742 raise InvalidAlgorithmError(e) from e
743
744 return publickey
745
746
747 def compare_publickeys(pk1: PublicKeyTypes, pk2: PublicKeyTypes) -> bool:
748 a = isinstance(pk1, Ed25519PublicKey)
749 b = isinstance(pk2, Ed25519PublicKey)
750 if a or b:
751 if not a or not b:
752 return False
753 a_bytes = pk1.public_bytes(
754 serialization.Encoding.Raw, serialization.PublicFormat.Raw
755 )
756 b_bytes = pk2.public_bytes(
757 serialization.Encoding.Raw, serialization.PublicFormat.Raw
758 )
759 return a_bytes == b_bytes
760 return pk1.public_numbers() == pk2.public_numbers() # type: ignore
761
762
763 def compare_encryption_algorithms(
764 ea1: serialization.KeySerializationEncryption,
765 ea2: serialization.KeySerializationEncryption,
766 ) -> bool:
767 if isinstance(ea1, serialization.NoEncryption) and isinstance(
768 ea2, serialization.NoEncryption
769 ):
770 return True
771 if isinstance(ea1, serialization.BestAvailableEncryption) and isinstance(
772 ea2, serialization.BestAvailableEncryption
773 ):
774 return ea1.password == ea2.password
775 return False
776
777
778 def get_encryption_algorithm(
779 passphrase: bytes,
780 ) -> serialization.KeySerializationEncryption:
781 try:
782 return serialization.BestAvailableEncryption(passphrase)
783 except ValueError as e:
784 raise InvalidPassphraseError(e) from e
785
786
787 def validate_comment(comment: str) -> None:
788 if not hasattr(comment, "encode"):
789 raise InvalidCommentError(f"{comment} cannot be encoded to text")
790
791
792 def extract_comment(path: str | os.PathLike) -> str:
793 if not os.path.exists(path):
794 raise InvalidPublicKeyFileError(f"No file was found at {path}")
795
796 try:
797 with open(path, "rb") as f:
798 fields = f.read().split(b" ", 2)
799 if len(fields) == 3:
800 comment = fields[2].decode(_TEXT_ENCODING)
801 else:
802 comment = ""
803 except (IOError, OSError) as e:
804 raise InvalidPublicKeyFileError(e) from e
805
806 return comment
807
808
809 def calculate_fingerprint(openssh_publickey: bytes) -> str:
810 digest = hashes.Hash(hashes.SHA256())
811 decoded_pubkey = b64decode(openssh_publickey.split(b" ")[1])
812 digest.update(decoded_pubkey)
813
814 value = b64encode(digest.finalize()).decode(encoding=_TEXT_ENCODING).rstrip("=")
815 return f"SHA256:{value}"
816
817
818 __all__ = (
819 "CRYPTOGRAPHY_VERSION",
820 "HAS_OPENSSH_SUPPORT",
821 "AsymmetricKeypair",
822 "InvalidAlgorithmError",
823 "InvalidCommentError",
824 "InvalidDataError",
825 "InvalidKeyFormatError",
826 "InvalidKeySizeError",
827 "InvalidKeyTypeError",
828 "InvalidPassphraseError",
829 "InvalidPrivateKeyFileError",
830 "InvalidPublicKeyFileError",
831 "InvalidSignatureError",
832 "OpenSSHError",
833 "OpensshKeypair",
834 "calculate_fingerprint",
835 "compare_encryption_algorithms",
836 "compare_publickeys",
837 "extract_comment",
838 "get_encryption_algorithm",
839 "load_privatekey",
840 "load_publickey",
841 "validate_comment",
842 )