Python OpenSSL.crypto.load_privatekey() Examples
The following are 30
code examples of OpenSSL.crypto.load_privatekey().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
OpenSSL.crypto
, or try the search function
.
Example #1
Source File: test_crypto.py From oss-ftp with MIT License | 6 votes |
def test_dump_privatekey_passphraseCallback(self): """ :py:obj:`dump_privatekey` writes an encrypted PEM when given a callback which returns the correct passphrase. """ passphrase = b("foo") called = [] def cb(writing): called.append(writing) return passphrase key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM) pem = dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, cb) self.assertTrue(isinstance(pem, binary_type)) self.assertEqual(called, [True]) loadedKey = load_privatekey(FILETYPE_PEM, pem, passphrase) self.assertTrue(isinstance(loadedKey, PKeyType)) self.assertEqual(loadedKey.type(), key.type()) self.assertEqual(loadedKey.bits(), key.bits())
Example #2
Source File: certs.py From pycopia with Apache License 2.0 | 6 votes |
def __init__(self, filename=None, text=None, passphrase=None, filetype="pem", bits=2048, _key=None): self.__passphrase = passphrase # can also be a callable if _key is not None: key = _key else: ftype = _FILETYPES[filetype] if filename is not None: ftype, text = get_type_and_text(filename) if text is not None: if passphrase is not None: key = crypto.load_privatekey(ftype, text, passphrase) else: key = crypto.load_privatekey(ftype, text) else: key = crypto.PKey() key.generate_key(crypto.TYPE_RSA, bits) key.check() self._key = key
Example #3
Source File: crypt.py From splunk-ref-pas-code with Apache License 2.0 | 6 votes |
def from_string(key, password='notasecret'): """Construct a Signer instance from a string. Args: key: string, private key in PKCS12 or PEM format. password: string, password for the private key file. Returns: Signer instance. Raises: OpenSSL.crypto.Error if the key can't be parsed. """ if key.startswith('-----BEGIN '): pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key) else: pkey = crypto.load_pkcs12(key, password).get_privatekey() return OpenSSLSigner(pkey)
Example #4
Source File: test_crypto.py From oss-ftp with MIT License | 6 votes |
def test_key_only(self): """ A :py:obj:`PKCS12` with only a private key can be exported using :py:obj:`PKCS12.export` and loaded again using :py:obj:`load_pkcs12`. """ passwd = b"blah" p12 = PKCS12() pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM) p12.set_privatekey(pkey) self.assertEqual(None, p12.get_certificate()) self.assertEqual(pkey, p12.get_privatekey()) try: dumped_p12 = p12.export(passphrase=passwd, iter=2, maciter=3) except Error: # Some versions of OpenSSL will throw an exception # for this nearly useless PKCS12 we tried to generate: # [('PKCS12 routines', 'PKCS12_create', 'invalid null argument')] return p12 = load_pkcs12(dumped_p12, passwd) self.assertEqual(None, p12.get_ca_certificates()) self.assertEqual(None, p12.get_certificate()) # OpenSSL fails to bring the key back to us. So sad. Perhaps in the # future this will be improved. self.assertTrue(isinstance(p12.get_privatekey(), (PKey, type(None))))
Example #5
Source File: test_crypto.py From oss-ftp with MIT License | 6 votes |
def gen_pkcs12(self, cert_pem=None, key_pem=None, ca_pem=None, friendly_name=None): """ Generate a PKCS12 object with components from PEM. Verify that the set functions return None. """ p12 = PKCS12() if cert_pem: ret = p12.set_certificate(load_certificate(FILETYPE_PEM, cert_pem)) self.assertEqual(ret, None) if key_pem: ret = p12.set_privatekey(load_privatekey(FILETYPE_PEM, key_pem)) self.assertEqual(ret, None) if ca_pem: ret = p12.set_ca_certificates((load_certificate(FILETYPE_PEM, ca_pem),)) self.assertEqual(ret, None) if friendly_name: ret = p12.set_friendlyname(friendly_name) self.assertEqual(ret, None) return p12
Example #6
Source File: test_crypto.py From oss-ftp with MIT License | 6 votes |
def test_replace(self): """ :py:obj:`PKCS12.set_certificate` replaces the certificate in a PKCS12 cluster. :py:obj:`PKCS12.set_privatekey` replaces the private key. :py:obj:`PKCS12.set_ca_certificates` replaces the CA certificates. """ p12 = self.gen_pkcs12(client_cert_pem, client_key_pem, root_cert_pem) p12.set_certificate(load_certificate(FILETYPE_PEM, server_cert_pem)) p12.set_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem)) root_cert = load_certificate(FILETYPE_PEM, root_cert_pem) client_cert = load_certificate(FILETYPE_PEM, client_cert_pem) p12.set_ca_certificates([root_cert]) # not a tuple self.assertEqual(1, len(p12.get_ca_certificates())) self.assertEqual(root_cert, p12.get_ca_certificates()[0]) p12.set_ca_certificates([client_cert, root_cert]) self.assertEqual(2, len(p12.get_ca_certificates())) self.assertEqual(client_cert, p12.get_ca_certificates()[0]) self.assertEqual(root_cert, p12.get_ca_certificates()[1])
Example #7
Source File: crypt.py From earthengine with MIT License | 6 votes |
def from_string(key_pem, is_x509_cert): """Construct a Verified instance from a string. Args: key_pem: string, public key in PEM format. is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it is expected to be an RSA key in PEM format. Returns: Verifier instance. Raises: OpenSSL.crypto.Error if the key_pem can't be parsed. """ if is_x509_cert: pubkey = crypto.load_certificate(crypto.FILETYPE_PEM, key_pem) else: pubkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key_pem) return OpenSSLVerifier(pubkey)
Example #8
Source File: requests.py From google-auth-library-python with Apache License 2.0 | 6 votes |
def __init__(self, cert, key): import certifi from OpenSSL import crypto import urllib3.contrib.pyopenssl urllib3.contrib.pyopenssl.inject_into_urllib3() pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key) x509 = crypto.load_certificate(crypto.FILETYPE_PEM, cert) ctx_poolmanager = create_urllib3_context() ctx_poolmanager.load_verify_locations(cafile=certifi.where()) ctx_poolmanager._ctx.use_certificate(x509) ctx_poolmanager._ctx.use_privatekey(pkey) self._ctx_poolmanager = ctx_poolmanager ctx_proxymanager = create_urllib3_context() ctx_proxymanager.load_verify_locations(cafile=certifi.where()) ctx_proxymanager._ctx.use_certificate(x509) ctx_proxymanager._ctx.use_privatekey(pkey) self._ctx_proxymanager = ctx_proxymanager super(_MutualTlsAdapter, self).__init__()
Example #9
Source File: crypt.py From splunk-ref-pas-code with Apache License 2.0 | 6 votes |
def from_string(key_pem, is_x509_cert): """Construct a Verified instance from a string. Args: key_pem: string, public key in PEM format. is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it is expected to be an RSA key in PEM format. Returns: Verifier instance. Raises: OpenSSL.crypto.Error if the key_pem can't be parsed. """ if is_x509_cert: pubkey = crypto.load_certificate(crypto.FILETYPE_PEM, key_pem) else: pubkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key_pem) return OpenSSLVerifier(pubkey)
Example #10
Source File: oss_fuzz_generate_certs_test.py From clusterfuzz with Apache License 2.0 | 6 votes |
def test_execute(self): """Tests executing of cron job.""" # Defer import to avoid issues on Python 2. from OpenSSL import crypto self.app.get('/generate-certs') # New cert. tls_cert = ndb.Key(data_types.WorkerTlsCert, 'project1').get() cert = crypto.load_certificate(crypto.FILETYPE_PEM, tls_cert.cert_contents) self.assertEqual('US', cert.get_subject().C) self.assertEqual('*.c.test-clusterfuzz.internal', cert.get_subject().CN) self.assertEqual('project1', cert.get_subject().O) self.assertEqual(9001, cert.get_serial_number()) self.assertEqual(b'20000101000000Z', cert.get_notBefore()) self.assertEqual(b'21000101000000Z', cert.get_notAfter()) private_key = crypto.load_privatekey(crypto.FILETYPE_PEM, tls_cert.key_contents) self.assertTrue(private_key.check()) # Should be unchanged. tls_cert = ndb.Key(data_types.WorkerTlsCert, 'project2').get() self.assertEqual(b'cert_contents', tls_cert.cert_contents) self.assertEqual(b'key_contents', tls_cert.key_contents)
Example #11
Source File: crypt.py From sndlatr with Apache License 2.0 | 6 votes |
def from_string(key, password='notasecret'): """Construct a Signer instance from a string. Args: key: string, private key in PKCS12 or PEM format. password: string, password for the private key file. Returns: Signer instance. Raises: OpenSSL.crypto.Error if the key can't be parsed. """ if key.startswith('-----BEGIN '): pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key) else: pkey = crypto.load_pkcs12(key, password).get_privatekey() return OpenSSLSigner(pkey)
Example #12
Source File: certificatetoken.py From privacyidea with GNU Affero General Public License v3.0 | 6 votes |
def _create_pkcs12_bin(self): """ Helper function to create an encrypted pkcs12 binary for download :return: PKCS12 binary """ certificate = self.get_tokeninfo("certificate") privatekey = self.get_tokeninfo("privatekey") pkcs12 = crypto.PKCS12() pkcs12.set_certificate(crypto.load_certificate( crypto.FILETYPE_PEM, certificate)) pkcs12.set_privatekey(crypto.load_privatekey(crypto.FILETYPE_PEM, privatekey)) # TODO define a random passphrase and hand it to the user passphrase = self.token.get_pin() if passphrase == -1: passphrase = "" pkcs12_bin = pkcs12.export(passphrase=passphrase) return pkcs12_bin
Example #13
Source File: crypt.py From billing-export-python with Apache License 2.0 | 6 votes |
def from_string(key, password='notasecret'): """Construct a Signer instance from a string. Args: key: string, private key in PKCS12 or PEM format. password: string, password for the private key file. Returns: Signer instance. Raises: OpenSSL.crypto.Error if the key can't be parsed. """ if key.startswith('-----BEGIN '): pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key) else: pkey = crypto.load_pkcs12(key, password).get_privatekey() return OpenSSLSigner(pkey)
Example #14
Source File: test_ssl.py From oss-ftp with MIT License | 6 votes |
def test_set_verify_callback_exception(self): """ If the verify callback passed to :py:obj:`Context.set_verify` raises an exception, verification fails and the exception is propagated to the caller of :py:obj:`Connection.do_handshake`. """ serverContext = Context(TLSv1_METHOD) serverContext.use_privatekey( load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM)) serverContext.use_certificate( load_certificate(FILETYPE_PEM, cleartextCertificatePEM)) clientContext = Context(TLSv1_METHOD) def verify_callback(*args): raise Exception("silly verify failure") clientContext.set_verify(VERIFY_PEER, verify_callback) exc = self.assertRaises( Exception, self._handshake_test, serverContext, clientContext) self.assertEqual("silly verify failure", str(exc))
Example #15
Source File: test_ssl.py From oss-ftp with MIT License | 6 votes |
def _client(self, sock): """ Create a new client-side SSL :py:obj:`Connection` object wrapped around :py:obj:`sock`. """ # Now create the client side Connection. Similar boilerplate to the # above. client_ctx = Context(TLSv1_METHOD) client_ctx.set_options(OP_NO_SSLv2 | OP_NO_SSLv3 | OP_SINGLE_DH_USE ) client_ctx.set_verify(VERIFY_PEER|VERIFY_FAIL_IF_NO_PEER_CERT|VERIFY_CLIENT_ONCE, verify_cb) client_store = client_ctx.get_cert_store() client_ctx.use_privatekey(load_privatekey(FILETYPE_PEM, client_key_pem)) client_ctx.use_certificate(load_certificate(FILETYPE_PEM, client_cert_pem)) client_ctx.check_privatekey() client_store.add_cert(load_certificate(FILETYPE_PEM, root_cert_pem)) client_conn = Connection(client_ctx, sock) client_conn.set_connect_state() return client_conn
Example #16
Source File: test_ssl.py From oss-ftp with MIT License | 6 votes |
def test_shutdown_truncated(self): """ If the underlying connection is truncated, :obj:`Connection.shutdown` raises an :obj:`Error`. """ server_ctx = Context(TLSv1_METHOD) client_ctx = Context(TLSv1_METHOD) server_ctx.use_privatekey( load_privatekey(FILETYPE_PEM, server_key_pem)) server_ctx.use_certificate( load_certificate(FILETYPE_PEM, server_cert_pem)) server = Connection(server_ctx, None) client = Connection(client_ctx, None) self._handshakeInMemory(client, server) self.assertEqual(server.shutdown(), False) self.assertRaises(WantReadError, server.shutdown) server.bio_shutdown() self.assertRaises(Error, server.shutdown)
Example #17
Source File: test_ssl.py From oss-ftp with MIT License | 6 votes |
def test_accept(self): """ :py:obj:`Connection.accept` accepts a pending connection attempt and returns a tuple of a new :py:obj:`Connection` (the accepted client) and the address the connection originated from. """ ctx = Context(TLSv1_METHOD) ctx.use_privatekey(load_privatekey(FILETYPE_PEM, server_key_pem)) ctx.use_certificate(load_certificate(FILETYPE_PEM, server_cert_pem)) port = socket() portSSL = Connection(ctx, port) portSSL.bind(('', 0)) portSSL.listen(3) clientSSL = Connection(Context(TLSv1_METHOD), socket()) # Calling portSSL.getsockname() here to get the server IP address sounds # great, but frequently fails on Windows. clientSSL.connect(('127.0.0.1', portSSL.getsockname()[1])) serverSSL, address = portSSL.accept() self.assertTrue(isinstance(serverSSL, Connection)) self.assertIdentical(serverSSL.get_context(), ctx) self.assertEquals(address, clientSSL.getsockname())
Example #18
Source File: crypt.py From billing-export-python with Apache License 2.0 | 6 votes |
def from_string(key_pem, is_x509_cert): """Construct a Verified instance from a string. Args: key_pem: string, public key in PEM format. is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it is expected to be an RSA key in PEM format. Returns: Verifier instance. Raises: OpenSSL.crypto.Error if the key_pem can't be parsed. """ if is_x509_cert: pubkey = crypto.load_certificate(crypto.FILETYPE_PEM, key_pem) else: pubkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key_pem) return OpenSSLVerifier(pubkey)
Example #19
Source File: crypt.py From sndlatr with Apache License 2.0 | 6 votes |
def from_string(key_pem, is_x509_cert): """Construct a Verified instance from a string. Args: key_pem: string, public key in PEM format. is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it is expected to be an RSA key in PEM format. Returns: Verifier instance. Raises: OpenSSL.crypto.Error if the key_pem can't be parsed. """ if is_x509_cert: pubkey = crypto.load_certificate(crypto.FILETYPE_PEM, key_pem) else: pubkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key_pem) return OpenSSLVerifier(pubkey)
Example #20
Source File: test_crypto.py From oss-ftp with MIT License | 5 votes |
def test_load_privatekey_passphraseWrongType(self): """ :py:obj:`load_privatekey` raises :py:obj:`ValueError` when it is passed a passphrase with a private key encoded in a format, that doesn't support encryption. """ key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM) blob = dump_privatekey(FILETYPE_ASN1, key) self.assertRaises(ValueError, load_privatekey, FILETYPE_ASN1, blob, "secret")
Example #21
Source File: test_crypto.py From oss-ftp with MIT License | 5 votes |
def test_load_privatekey_passphrase_wrong_return_type(self): """ :py:obj:`load_privatekey` raises :py:obj:`ValueError` if the passphrase callback returns something other than a byte string. """ self.assertRaises( ValueError, load_privatekey, FILETYPE_PEM, encryptedPrivateKeyPEM, lambda *args: 3)
Example #22
Source File: test_crypto.py From oss-ftp with MIT License | 5 votes |
def test_dump_privatekey_passphrase(self): """ :py:obj:`dump_privatekey` writes an encrypted PEM when given a passphrase. """ passphrase = b("foo") key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM) pem = dump_privatekey(FILETYPE_PEM, key, GOOD_CIPHER, passphrase) self.assertTrue(isinstance(pem, binary_type)) loadedKey = load_privatekey(FILETYPE_PEM, pem, passphrase) self.assertTrue(isinstance(loadedKey, PKeyType)) self.assertEqual(loadedKey.type(), key.type()) self.assertEqual(loadedKey.bits(), key.bits())
Example #23
Source File: test_crypto.py From oss-ftp with MIT License | 5 votes |
def test_load_privatekey_passphraseCallbackLength(self): """ :py:obj:`crypto.load_privatekey` should raise an error when the passphrase provided by the callback is too long, not silently truncate it. """ def cb(ignored): return "a" * 1025 self.assertRaises(ValueError, load_privatekey, FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
Example #24
Source File: test_crypto.py From oss-ftp with MIT License | 5 votes |
def test_load_privatekey_passphraseCallback(self): """ :py:obj:`load_privatekey` can create a :py:obj:`PKey` object from an encrypted PEM string if given a passphrase callback which returns the correct password. """ called = [] def cb(writing): called.append(writing) return encryptedPrivateKeyPEMPassphrase key = load_privatekey(FILETYPE_PEM, encryptedPrivateKeyPEM, cb) self.assertTrue(isinstance(key, PKeyType)) self.assertEqual(called, [False])
Example #25
Source File: test_crypto.py From oss-ftp with MIT License | 5 votes |
def test_dump_privatekey_asn1(self): """ :py:obj:`dump_privatekey` writes a DER """ key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM) dumped_pem = dump_privatekey(FILETYPE_PEM, key) dumped_der = dump_privatekey(FILETYPE_ASN1, key) # XXX This OpenSSL call writes "writing RSA key" to standard out. Sad. good_der = _runopenssl(dumped_pem, b"rsa", b"-outform", b"DER") self.assertEqual(dumped_der, good_der) key2 = load_privatekey(FILETYPE_ASN1, dumped_der) dumped_pem2 = dump_privatekey(FILETYPE_PEM, key2) self.assertEqual(dumped_pem2, cleartextPrivateKeyPEM)
Example #26
Source File: test_crypto.py From oss-ftp with MIT License | 5 votes |
def test_dump_privatekey_text(self): """ :py:obj:`dump_privatekey` writes a text """ key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM) dumped_pem = dump_privatekey(FILETYPE_PEM, key) dumped_text = dump_privatekey(FILETYPE_TEXT, key) good_text = _runopenssl(dumped_pem, b"rsa", b"-noout", b"-text") self.assertEqual(dumped_text, good_text)
Example #27
Source File: test_crypto.py From oss-ftp with MIT License | 5 votes |
def test_load_privatekey_passphrase(self): """ :py:obj:`load_privatekey` can create a :py:obj:`PKey` object from an encrypted PEM string if given the passphrase. """ key = load_privatekey( FILETYPE_PEM, encryptedPrivateKeyPEM, encryptedPrivateKeyPEMPassphrase) self.assertTrue(isinstance(key, PKeyType))
Example #28
Source File: test_crypto.py From oss-ftp with MIT License | 5 votes |
def test_verify_wrong_key(self): """ :py:obj:`X509Req.verify` raises :py:obj:`OpenSSL.crypto.Error` if called with a :py:obj:`OpenSSL.crypto.PKey` which does not represent the public part of the key which signed the request. """ request = X509Req() pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM) request.sign(pkey, GOOD_DIGEST) another_pkey = load_privatekey(FILETYPE_PEM, client_key_pem) self.assertRaises(Error, request.verify, another_pkey)
Example #29
Source File: test_crypto.py From oss-ftp with MIT License | 5 votes |
def test_load_privatekey_passphrase_exception(self): """ If the passphrase callback raises an exception, that exception is raised by :py:obj:`load_privatekey`. """ def cb(ignored): raise ArithmeticError self.assertRaises(ArithmeticError, load_privatekey, FILETYPE_PEM, encryptedPrivateKeyPEM, cb)
Example #30
Source File: test_crypto.py From oss-ftp with MIT License | 5 votes |
def test_dump_privatekey_passphraseWrongType(self): """ :py:obj:`dump_privatekey` raises :py:obj:`ValueError` when it is passed a passphrase with a private key encoded in a format, that doesn't support encryption. """ key = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM) self.assertRaises(ValueError, dump_privatekey, FILETYPE_ASN1, key, GOOD_CIPHER, "secret")