diff options
author | Paul Kehrer <paul.l.kehrer@gmail.com> | 2016-07-29 15:31:04 +0800 |
---|---|---|
committer | Cory Benfield <lukasaoz@gmail.com> | 2016-07-29 08:31:04 +0100 |
commit | 72d968b2dea6937c2e2b1fe62bf404b667a98a80 (patch) | |
tree | c6b5209a5036d8eb55d6c7db9996147ab1cbef0e /src/OpenSSL/crypto.py | |
parent | db8ec13b1ebec5ec3d5f2ff185adf0c961841163 (diff) | |
download | pyopenssl-git-72d968b2dea6937c2e2b1fe62bf404b667a98a80.tar.gz |
Convert between pyOpenSSL and cryptography objects (#439)
* convert pkey to cryptography keys and vice versa
* pep8 and such
* Add documentation and changelog
* add a type check and verify that it rejects ECDSA keys from cryptography
Diffstat (limited to 'src/OpenSSL/crypto.py')
-rw-r--r-- | src/OpenSSL/crypto.py | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/src/OpenSSL/crypto.py b/src/OpenSSL/crypto.py index 4a379e8..c37f20b 100644 --- a/src/OpenSSL/crypto.py +++ b/src/OpenSSL/crypto.py @@ -10,6 +10,9 @@ from six import ( text_type as _text_type, PY3 as _PY3) +from cryptography.hazmat.backends.openssl.backend import backend +from cryptography.hazmat.primitives.asymmetric import dsa, rsa + from OpenSSL._util import ( ffi as _ffi, lib as _lib, @@ -167,6 +170,45 @@ class PKey(object): self._pkey = _ffi.gc(pkey, _lib.EVP_PKEY_free) self._initialized = False + def to_cryptography_key(self): + """ + Export as a ``cryptography`` key. + + :rtype: One of ``cryptography``'s `key interfaces`_. + + .. _key interfaces: https://cryptography.io/en/latest/hazmat/\ + primitives/asymmetric/rsa/#key-interfaces + + .. versionadded:: 16.1.0 + """ + if self._only_public: + return backend._evp_pkey_to_public_key(self._pkey) + else: + return backend._evp_pkey_to_private_key(self._pkey) + + @classmethod + def from_cryptography_key(cls, crypto_key): + """ + Construct based on a ``cryptography`` *crypto_key*. + + :param crypto_key: A ``cryptography`` key. + :type crypto_key: One of ``cryptography``'s `key interfaces`_. + + :rtype: PKey + + .. versionadded:: 16.1.0 + """ + pkey = cls() + if not isinstance(crypto_key, (rsa.RSAPublicKey, rsa.RSAPrivateKey, + dsa.DSAPublicKey, dsa.DSAPrivateKey)): + raise TypeError("Unsupported key type") + + pkey._pkey = crypto_key._evp_pkey + if isinstance(crypto_key, (rsa.RSAPublicKey, dsa.DSAPublicKey)): + pkey._only_public = True + pkey._initialized = True + return pkey + def generate_key(self, type, bits): """ Generate a key pair of the given type, with the given number of bits. |