pkcs12.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. from __future__ import absolute_import, division, print_function
  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. def load_key_and_certificates(data, password, backend=None):
  10. backend = _get_backend(backend)
  11. return backend.load_key_and_certificates_from_pkcs12(data, password)
  12. def serialize_key_and_certificates(name, key, cert, cas, encryption_algorithm):
  13. if key is not None and not isinstance(
  14. key,
  15. (
  16. rsa.RSAPrivateKeyWithSerialization,
  17. dsa.DSAPrivateKeyWithSerialization,
  18. ec.EllipticCurvePrivateKeyWithSerialization,
  19. ),
  20. ):
  21. raise TypeError("Key must be RSA, DSA, or EllipticCurve private key.")
  22. if cert is not None and not isinstance(cert, x509.Certificate):
  23. raise TypeError("cert must be a certificate")
  24. if cas is not None:
  25. cas = list(cas)
  26. if not all(isinstance(val, x509.Certificate) for val in cas):
  27. raise TypeError("all values in cas must be certificates")
  28. if not isinstance(
  29. encryption_algorithm, serialization.KeySerializationEncryption
  30. ):
  31. raise TypeError(
  32. "Key encryption algorithm must be a "
  33. "KeySerializationEncryption instance"
  34. )
  35. if key is None and cert is None and not cas:
  36. raise ValueError("You must supply at least one of key, cert, or cas")
  37. backend = _get_backend(None)
  38. return backend.serialize_key_and_certificates_to_pkcs12(
  39. name, key, cert, cas, encryption_algorithm
  40. )