pkcs12.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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.primitives import serialization
  8. from cryptography.hazmat.primitives.asymmetric import dsa, ec, rsa
  9. _ALLOWED_PKCS12_TYPES = typing.Union[
  10. rsa.RSAPrivateKey,
  11. dsa.DSAPrivateKey,
  12. ec.EllipticCurvePrivateKey,
  13. ]
  14. def load_key_and_certificates(
  15. data: bytes, password: typing.Optional[bytes], backend=None
  16. ) -> typing.Tuple[
  17. typing.Optional[_ALLOWED_PKCS12_TYPES],
  18. typing.Optional[x509.Certificate],
  19. typing.List[x509.Certificate],
  20. ]:
  21. backend = _get_backend(backend)
  22. return backend.load_key_and_certificates_from_pkcs12(data, password)
  23. def serialize_key_and_certificates(
  24. name: typing.Optional[bytes],
  25. key: typing.Optional[_ALLOWED_PKCS12_TYPES],
  26. cert: typing.Optional[x509.Certificate],
  27. cas: typing.Optional[typing.Iterable[x509.Certificate]],
  28. encryption_algorithm: serialization.KeySerializationEncryption,
  29. ) -> bytes:
  30. if key is not None and not isinstance(
  31. key,
  32. (
  33. rsa.RSAPrivateKey,
  34. dsa.DSAPrivateKey,
  35. ec.EllipticCurvePrivateKey,
  36. ),
  37. ):
  38. raise TypeError("Key must be RSA, DSA, or EllipticCurve private key.")
  39. if cert is not None and not isinstance(cert, x509.Certificate):
  40. raise TypeError("cert must be a certificate")
  41. if cas is not None:
  42. cas = list(cas)
  43. if not all(isinstance(val, x509.Certificate) for val in cas):
  44. raise TypeError("all values in cas must be certificates")
  45. if not isinstance(
  46. encryption_algorithm, serialization.KeySerializationEncryption
  47. ):
  48. raise TypeError(
  49. "Key encryption algorithm must be a "
  50. "KeySerializationEncryption instance"
  51. )
  52. if key is None and cert is None and not cas:
  53. raise ValueError("You must supply at least one of key, cert, or cas")
  54. backend = _get_backend(None)
  55. return backend.serialize_key_and_certificates_to_pkcs12(
  56. name, key, cert, cas, encryption_algorithm
  57. )