我们从Python开源项目中,提取了以下48个代码示例,用于说明如何使用OpenSSL.crypto.load_pkcs12()。
def from_string(key, password=b'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. """ key = _to_bytes(key) parsed_pem_key = _parse_pem_key(key) if parsed_pem_key: pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, parsed_pem_key) else: password = _to_bytes(password, encoding='utf-8') pkey = crypto.load_pkcs12(key, password).get_privatekey() return OpenSSLSigner(pkey)
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)
def test_key_only(self): """ A L{PKCS12} with only a private key can be exported using L{PKCS12.export} and loaded again using L{load_pkcs12}. """ passwd = '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))))
def test_load_pkcs12(self): """ A PKCS12 string generated using the openssl command line can be loaded with L{load_pkcs12} and its components extracted and examined. """ passwd = 'whatever' pem = client_key_pem + client_cert_pem p12_str = _runopenssl( pem, "pkcs12", '-export', '-clcerts', '-passout', 'pass:' + passwd) p12 = load_pkcs12(p12_str, passwd) # verify self.assertTrue(isinstance(p12, PKCS12)) cert_pem = dump_certificate(FILETYPE_PEM, p12.get_certificate()) self.assertEqual(cert_pem, client_cert_pem) key_pem = dump_privatekey(FILETYPE_PEM, p12.get_privatekey()) self.assertEqual(key_pem, client_key_pem) self.assertEqual(None, p12.get_ca_certificates())
def from_string(key, password=b'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. """ key = _helpers._to_bytes(key) parsed_pem_key = _helpers._parse_pem_key(key) if parsed_pem_key: pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, parsed_pem_key) else: password = _helpers._to_bytes(password, encoding='utf-8') pkey = crypto.load_pkcs12(key, password).get_privatekey() return OpenSSLSigner(pkey)
def extrair_certificado_a1(self, arquivo, senha): ''' Extrai o conteúdo do certificado A1 @param arquivo:arquivo binário do certificado @param senha: senha do certificado. @return: dicionário com a string do certificado, chave privada, emissor, proprietario, data_inicio_validade e data_final_validade. ''' conteudo_pkcs12 = crypto.load_pkcs12(arquivo, senha) key_str = crypto.dump_privatekey(crypto.FILETYPE_PEM, conteudo_pkcs12.get_privatekey()) cert_str = crypto.dump_certificate(crypto.FILETYPE_PEM, conteudo_pkcs12.get_certificate()) certificado = Certificado() certificado.prepara_certificado_txt(cert_str.decode('utf-8')) vals = {'cert': cert_str.decode('utf-8'), 'key': key_str.decode('utf-8'), 'emissor': certificado.emissor.get('OU'), 'proprietario': certificado.proprietario.get('CN'), 'data_inicio_validade': certificado.data_inicio_validade, 'data_final_validade': certificado.data_fim_validade, } return vals
def from_string(key, password=b'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. """ from OpenSSL import crypto parsed_pem_key = _parse_pem_key(key) if parsed_pem_key: pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, parsed_pem_key) else: if isinstance(password, six.text_type): password = password.encode('utf-8') pkey = crypto.load_pkcs12(key, password).get_privatekey() return OpenSSLSigner(pkey)
def pkcs12_key_as_pem(private_key_text, private_key_password): """Convert the contents of a PKCS12 key to PEM using OpenSSL. Args: private_key_text: String. Private key. private_key_password: String. Password for PKCS12. Returns: String. PEM contents of ``private_key_text``. """ from OpenSSL import crypto decoded_body = base64.b64decode(private_key_text) if isinstance(private_key_password, six.string_types): private_key_password = private_key_password.encode('ascii') pkcs12 = crypto.load_pkcs12(decoded_body, private_key_password) return crypto.dump_privatekey(crypto.FILETYPE_PEM, pkcs12.get_privatekey())
def test_key_only(self): """ A `PKCS12` with only a private key can be exported using `PKCS12.export` and loaded again using `load_pkcs12`. """ passwd = b"blah" p12 = PKCS12() pkey = load_privatekey(FILETYPE_PEM, cleartextPrivateKeyPEM) p12.set_privatekey(pkey) assert None is p12.get_certificate() assert 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) assert None is p12.get_ca_certificates() assert None is p12.get_certificate() # OpenSSL fails to bring the key back to us. So sad. Perhaps in the # future this will be improved. assert isinstance(p12.get_privatekey(), (PKey, type(None)))
def test_load_pkcs12(self): """ A PKCS12 string generated using the openssl command line can be loaded with `load_pkcs12` and its components extracted and examined. """ passwd = b"whatever" pem = client_key_pem + client_cert_pem p12_str = _runopenssl( pem, b"pkcs12", b"-export", b"-clcerts", b"-passout", b"pass:" + passwd ) p12 = load_pkcs12(p12_str, passphrase=passwd) self.verify_pkcs12_container(p12)
def test_load_pkcs12_text_passphrase(self): """ A PKCS12 string generated using the openssl command line can be loaded with `load_pkcs12` and its components extracted and examined. Using text as passphrase instead of bytes. DeprecationWarning expected. """ pem = client_key_pem + client_cert_pem passwd = b"whatever" p12_str = _runopenssl(pem, b"pkcs12", b"-export", b"-clcerts", b"-passout", b"pass:" + passwd) with pytest.warns(DeprecationWarning) as w: simplefilter("always") p12 = load_pkcs12(p12_str, passphrase=b"whatever".decode("ascii")) assert ( "{0} for passphrase is no longer accepted, use bytes".format( WARNING_TYPE_EXPECTED ) == str(w[-1].message)) self.verify_pkcs12_container(p12)
def test_load_without_mac(self): """ Loading a PKCS12 without a MAC does something other than crash. """ passwd = b"Lake Michigan" p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem) dumped_p12 = p12.export(maciter=-1, passphrase=passwd, iter=2) try: recovered_p12 = load_pkcs12(dumped_p12, passwd) # The person who generated this PCKS12 should be flogged, # or better yet we should have a means to determine # whether a PCKS12 had a MAC that was verified. # Anyway, libopenssl chooses to allow it, so the # pyopenssl binding does as well. assert isinstance(recovered_p12, PKCS12) except Error: # Failing here with an exception is preferred as some openssl # versions do. pass
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. """ parsed_pem_key = _parse_pem_key(key) if parsed_pem_key: pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, parsed_pem_key) else: pkey = crypto.load_pkcs12(key, password.encode('utf8')).get_privatekey() return OpenSSLSigner(pkey)
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))))
def test_load_pkcs12_text_passphrase(self): """ A PKCS12 string generated using the openssl command line can be loaded with :py:obj:`load_pkcs12` and its components extracted and examined. Using text as passphrase instead of bytes. DeprecationWarning expected. """ pem = client_key_pem + client_cert_pem passwd = b"whatever" p12_str = _runopenssl(pem, b"pkcs12", b"-export", b"-clcerts", b"-passout", b"pass:" + passwd) with catch_warnings(record=True) as w: simplefilter("always") p12 = load_pkcs12(p12_str, passphrase=b"whatever".decode("ascii")) self.assertEqual( "{0} for passphrase is no longer accepted, use bytes".format( WARNING_TYPE_EXPECTED ), str(w[-1].message) ) self.assertIs(w[-1].category, DeprecationWarning) self.verify_pkcs12_container(p12)
def test_load_without_mac(self): """ Loading a PKCS12 without a MAC does something other than crash. """ passwd = b"Lake Michigan" p12 = self.gen_pkcs12(server_cert_pem, server_key_pem, root_cert_pem) dumped_p12 = p12.export(maciter=-1, passphrase=passwd, iter=2) try: recovered_p12 = load_pkcs12(dumped_p12, passwd) # The person who generated this PCKS12 should be flogged, # or better yet we should have a means to determine # whether a PCKS12 had a MAC that was verified. # Anyway, libopenssl chooses to allow it, so the # pyopenssl binding does as well. self.assertTrue(isinstance(recovered_p12, PKCS12)) except Error: # Failing here with an exception is preferred as some openssl # versions do. pass
def from_string(key, password=b'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. """ parsed_pem_key = _parse_pem_key(key) if parsed_pem_key: pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, parsed_pem_key) else: password = _to_bytes(password, encoding='utf-8') pkey = crypto.load_pkcs12(key, password).get_privatekey() return OpenSSLSigner(pkey)
def pkcs12_key_as_pem(private_key_text, private_key_password): """Convert the contents of a PKCS12 key to PEM using OpenSSL. Args: private_key_text: String. Private key. private_key_password: String. Password for PKCS12. Returns: String. PEM contents of ``private_key_text``. """ decoded_body = base64.b64decode(private_key_text) private_key_password = _to_bytes(private_key_password) pkcs12 = crypto.load_pkcs12(decoded_body, private_key_password) return crypto.dump_privatekey(crypto.FILETYPE_PEM, pkcs12.get_privatekey())
def _compute_expiry_date(self): try: pfx = base64.decodestring( self.with_context(bin_size=False).nfe_a1_file) pfx = crypto.load_pkcs12(pfx, self.nfe_a1_password) cert = pfx.get_certificate() end = datetime.strptime( cert.get_notAfter().decode(), '%Y%m%d%H%M%SZ') subj = cert.get_subject() self.cert_expire_date = end if datetime.now() < end: self.cert_state = 'valid' else: self.cert_state = 'expired' self.cert_information = "%s\n%s\n%s\n%s" % ( subj.CN, subj.L, subj.O, subj.OU) except crypto.Error: self.cert_state = 'invalid_password' except: self.cert_state = 'unknown' _logger.error( u'Erro desconhecido ao consultar certificado', exc_info=True)