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