pkcs12.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # This file is dual licensed under the terms of the Apache License, Version
  2. # 2.0, and the BSD License. See the LICENSE file in the root of this repository
  3. # for complete details.
  4. import typing
  5. from cryptography import x509
  6. from cryptography.hazmat.backends import _get_backend
  7. from cryptography.hazmat.backends.interfaces import Backend
  8. from cryptography.hazmat.primitives import serialization
  9. from cryptography.hazmat.primitives.asymmetric import dsa, ec, rsa
  10. _ALLOWED_PKCS12_TYPES = typing.Union[
  11. rsa.RSAPrivateKey,
  12. dsa.DSAPrivateKey,
  13. ec.EllipticCurvePrivateKey,
  14. ]
  15. def load_key_and_certificates(
  16. data: bytes,
  17. password: typing.Optional[bytes],
  18. backend: typing.Optional[Backend] = None,
  19. ) -> typing.Tuple[
  20. typing.Optional[_ALLOWED_PKCS12_TYPES],
  21. typing.Optional[x509.Certificate],
  22. typing.List[x509.Certificate],
  23. ]:
  24. backend = _get_backend(backend)
  25. return backend.load_key_and_certificates_from_pkcs12(data, password)
  26. def serialize_key_and_certificates(
  27. name: typing.Optional[bytes],
  28. key: typing.Optional[_ALLOWED_PKCS12_TYPES],
  29. cert: typing.Optional[x509.Certificate],
  30. cas: typing.Optional[typing.Iterable[x509.Certificate]],
  31. encryption_algorithm: serialization.KeySerializationEncryption,
  32. ) -> bytes:
  33. if key is not None and not isinstance(
  34. key,
  35. (
  36. rsa.RSAPrivateKey,
  37. dsa.DSAPrivateKey,
  38. ec.EllipticCurvePrivateKey,
  39. ),
  40. ):
  41. raise TypeError("Key must be RSA, DSA, or EllipticCurve private key.")
  42. if cert is not None and not isinstance(cert, x509.Certificate):
  43. raise TypeError("cert must be a certificate")
  44. if cas is not None:
  45. cas = list(cas)
  46. if not all(isinstance(val, x509.Certificate) for val in cas):
  47. raise TypeError("all values in cas must be certificates")
  48. if not isinstance(
  49. encryption_algorithm, serialization.KeySerializationEncryption
  50. ):
  51. raise TypeError(
  52. "Key encryption algorithm must be a "
  53. "KeySerializationEncryption instance"
  54. )
  55. if key is None and cert is None and not cas:
  56. raise ValueError("You must supply at least one of key, cert, or cas")
  57. backend = _get_backend(None)
  58. return backend.serialize_key_and_certificates_to_pkcs12(
  59. name, key, cert, cas, encryption_algorithm
  60. )