Python OpenSSL.crypto() Examples
The following are 17
code examples of OpenSSL.crypto().
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
, or try the search function
.
Example #1
Source File: test_utilities_extract_ssl_cert_from_url.py From resilient-community-apps with MIT License | 6 votes |
def test_validate_cert(self, circuits_app, https_url, expected_results): """ Test the functions return type 'Certificate' When the function is successful in parsing the URL It should return a value we can parse into a certificate OpenSSL.crypto.load_certificate should be able to get a valid certificate When the function isint successful -- None""" function_params = { "https_url": https_url } # If we expected the result to be unsuccesful it should raise an error if expected_results['successful'] == False: with pytest.raises(Exception): call_utilities_extract_ssl_cert_from_url_function(circuits_app, function_params) else: results = call_utilities_extract_ssl_cert_from_url_function(circuits_app, function_params) if results['successful']: assert (isinstance( OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, json.loads(results['certificate'])), X509)) # Assert our successful results are of type X509 else: assert (isinstance(results['certificate'], type(None)))
Example #2
Source File: certificate_generator.py From pynubank with MIT License | 5 votes |
def _get_public_key(self, key) -> str: return OpenSSL.crypto.dump_publickey(OpenSSL.crypto.FILETYPE_PEM, key).decode()
Example #3
Source File: cert_util.py From XX-Net-mini with GNU General Public License v3.0 | 5 votes |
def verify_certificate(ca, cert): if hasattr(OpenSSL.crypto, "X509StoreContext"): store = OpenSSL.crypto.X509Store() store.add_cert(ca) try: OpenSSL.crypto.X509StoreContext(store, cert).verify_certificate() except: return False else: return True else: # A fake verify, just check generated time. return ca.get_subject().OU == cert.get_issuer().OU
Example #4
Source File: cert_util.py From XX-Net-mini with GNU General Public License v3.0 | 5 votes |
def _get_old_cert(commonname): certfile = os.path.join(CertUtil.ca_certdir, utils.to_str(commonname) + '.crt') if os.path.exists(certfile): with open(certfile, 'rb') as fp: cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, fp.read()) if datetime.datetime.strptime(utils.to_str(cert.get_notAfter()), '%Y%m%d%H%M%SZ') < datetime.datetime.utcnow() + datetime.timedelta(days=30): try: os.remove(certfile) except OSError as e: xlog.warning('CertUtil._get_old_cert failed: unable to remove outdated cert, %r', e) else: return # well, have to use the old one return certfile
Example #5
Source File: cert_util.py From XX-Net-mini with GNU General Public License v3.0 | 5 votes |
def generate_cert_keyfile(): xlog.info("generate certs's key file:%s", CertUtil.cert_keyfile) pkey = OpenSSL.crypto.PKey() pkey.generate_key(OpenSSL.crypto.TYPE_RSA, 2048) with open(CertUtil.cert_keyfile, 'wb') as fp: fp.write(OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, pkey)) fp.write(OpenSSL.crypto.dump_publickey(OpenSSL.crypto.FILETYPE_PEM, pkey)) CertUtil.cert_publickey = pkey
Example #6
Source File: cert_util.py From XX-Net-mini with GNU General Public License v3.0 | 5 votes |
def generate_ca_file(): xlog.info("generate CA file:%s", CertUtil.ca_keyfile) key, ca = CertUtil.create_ca() with open(CertUtil.ca_certfile, 'wb') as fp: fp.write(OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, ca)) with open(CertUtil.ca_keyfile, 'wb') as fp: fp.write(OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, ca)) fp.write(OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, key))
Example #7
Source File: cert_util.py From XX-Net-mini with GNU General Public License v3.0 | 5 votes |
def create_ca(): key = OpenSSL.crypto.PKey() key.generate_key(OpenSSL.crypto.TYPE_RSA, 2048) ca = OpenSSL.crypto.X509() ca.set_version(2) ca.set_serial_number(0) subj = ca.get_subject() subj.countryName = 'CN' subj.stateOrProvinceName = 'Internet' subj.localityName = 'Cernet' subj.organizationName = CertUtil.ca_vendor # Log generated time. subj.organizationalUnitName = '%s Root - %d' % (CertUtil.ca_vendor, int(time.time())) subj.commonName = '%s XX-Net' % CertUtil.ca_vendor ca.gmtime_adj_notBefore(- 3600 * 24) ca.gmtime_adj_notAfter(CertUtil.ca_validity - 3600 * 24) ca.set_issuer(subj) ca.set_subject(subj) ca.set_pubkey(key) ca.add_extensions([ OpenSSL.crypto.X509Extension( b'basicConstraints', False, b'CA:TRUE', subject=ca, issuer=ca) ]) ca.sign(key, CertUtil.ca_digest) #xlog.debug("CA key:%s", key) xlog.info("create CA") return key, ca
Example #8
Source File: connect_creator.py From XX-Net-mini with GNU General Public License v3.0 | 5 votes |
def get_subj_alt_name(peer_cert): ''' Copied from ndg.httpsclient.ssl_peer_verification.ServerSSLCertVerification Extract subjectAltName DNS name settings from certificate extensions @param peer_cert: peer certificate in SSL connection. subjectAltName settings if any will be extracted from this @type peer_cert: OpenSSL.crypto.X509 ''' # Search through extensions dns_name = [] general_names = SubjectAltName() for i in range(peer_cert.get_extension_count()): ext = peer_cert.get_extension(i) ext_name = ext.get_short_name() if ext_name == b"subjectAltName": # PyOpenSSL returns extension data in ASN.1 encoded form ext_dat = ext.get_data() decoded_dat = der_decoder.decode(ext_dat, asn1Spec=general_names) for name in decoded_dat: if isinstance(name, SubjectAltName): for entry in range(len(name)): component = name.getComponentByPosition(entry) n = bytes(component.getComponent()) if n.startswith(b"*"): continue dns_name.append(n) return dns_name
Example #9
Source File: utils.py From flask-saml2 with MIT License | 5 votes |
def certificate_to_string(certificate: TS.X509) -> str: """ Take an x509 certificate and encode it to a string suitable for adding to XML responses. :param certificate: A certificate, perhaps loaded from :func:`certificate_from_file`. """ pem_bytes = OpenSSL.crypto.dump_certificate( OpenSSL.crypto.FILETYPE_PEM, certificate) return ''.join(pem_bytes.decode('ascii').strip().split('\n')[1:-1])
Example #10
Source File: certificate_generator.py From pynubank with MIT License | 5 votes |
def _generate_key(self): key = OpenSSL.crypto.PKey() key.generate_key(OpenSSL.crypto.TYPE_RSA, 2048) return key
Example #11
Source File: certificate_generator.py From pynubank with MIT License | 5 votes |
def _gen_cert(self, key, cert): p12 = OpenSSL.crypto.PKCS12() p12.set_privatekey(key) p12.set_certificate(cert) return p12
Example #12
Source File: certificate_generator.py From pynubank with MIT License | 5 votes |
def _parse_cert(self, content: str) -> X509: return OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, content.encode())
Example #13
Source File: utils.py From flask-saml2 with MIT License | 5 votes |
def private_key_from_file( filename: Union[str, pathlib.Path], format=OpenSSL.crypto.FILETYPE_PEM, ) -> TS.PKey: """Load a private key from ``filename``. :param filename: The path to the private key on disk. :param format: The format of the private key, from :doc:`OpenSSL:api/crypto`. """ with open(filename, 'r') as handle: return private_key_from_string(handle.read(), format)
Example #14
Source File: utils.py From flask-saml2 with MIT License | 5 votes |
def private_key_from_string( private_key: str, format=OpenSSL.crypto.FILETYPE_PEM, ) -> TS.PKey: """Load a private key from a string. :param str: A private key string. :param format: The format of the private key, from :doc:`OpenSSL:api/crypto`. """ return OpenSSL.crypto.load_privatekey(format, private_key)
Example #15
Source File: utils.py From flask-saml2 with MIT License | 5 votes |
def certificate_from_file( filename: Union[str, pathlib.Path], format=OpenSSL.crypto.FILETYPE_PEM, ) -> TS.X509: """Load an X509 certificate from ``filename``. :param filename: The path to the certificate on disk. :param format: The format of the certificate, from :doc:`OpenSSL:api/crypto`. """ with open(filename, 'r') as handle: return certificate_from_string(handle.read(), format)
Example #16
Source File: utils.py From flask-saml2 with MIT License | 5 votes |
def certificate_from_string( certificate: str, format=OpenSSL.crypto.FILETYPE_PEM, ) -> TS.X509: """ Load an X509 certificate from a string. This just strips off the header and footer text. :param str: A certificate string. :param format: The format of the certificate, from :doc:`OpenSSL:api/crypto`. """ return OpenSSL.crypto.load_certificate(format, certificate)
Example #17
Source File: connect_creator.py From XX-Net-mini with GNU General Public License v3.0 | 4 votes |
def check_cert(self, ssl_sock): cert_chain = ssl_sock.get_peer_cert_chain() if not cert_chain: raise socket.error('certificate is none, sni:%s' % ssl_sock.sni) if len(cert_chain) < self.config.min_intermediate_CA: raise socket.error('No intermediate CA was found.') if self.config.check_pkp and hasattr(OpenSSL.crypto, "dump_publickey"): # old OpenSSL not support this function. pub_key = OpenSSL.crypto.dump_publickey(OpenSSL.crypto.FILETYPE_PEM, cert_chain[1].get_pubkey()) if pub_key not in self.config.CHECK_PKP: # google_ip.report_connect_fail(ip, force_remove=True) raise socket.error('The intermediate CA is mismatching.') self.get_ssl_cert_domain(ssl_sock) issuer_commonname = next((v for k, v in cert_chain[0].get_issuer().get_components() if k == b'CN'), '') if self.debug: for cert in cert_chain: for k, v in cert.get_issuer().get_components(): if k != b"CN": continue cn = v self.logger.debug("cn:%s", cn) self.logger.debug("issued by:%s", issuer_commonname) self.logger.debug("Common Name:%s", ssl_sock.domain) if self.config.check_commonname and not issuer_commonname.startswith(self.config.check_commonname): raise socket.error(' certificate is issued by %r' % (issuer_commonname)) cert = ssl_sock.get_peer_certificate() if not cert: raise socket.error('certificate is none') if self.config.check_sni: # get_subj_alt_name cost near 100ms. be careful. try: alt_names = ConnectCreator.get_subj_alt_name(cert) except Exception as e: # self.logger.warn("get_subj_alt_name fail:%r", e) alt_names = [b""] if self.debug: self.logger.debug('alt names: "%s"', b'", "'.join(alt_names)) if isinstance(self.config.check_sni, str): if self.config.check_sni not in alt_names: raise socket.error('check sni fail, alt_names:%s' % (alt_names)) else: alt_names = tuple(alt_names) if not ssl_sock.sni.endswith(alt_names): raise socket.error('check sni:%s fail, alt_names:%s' % (ssl_sock.sni, alt_names))