本文整理汇总了Python中pyasn1_modules.rfc2459.Certificate方法的典型用法代码示例。如果您正苦于以下问题:Python rfc2459.Certificate方法的具体用法?Python rfc2459.Certificate怎么用?Python rfc2459.Certificate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyasn1_modules.rfc2459
的用法示例。
在下文中一共展示了rfc2459.Certificate方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: parse_cert
# 需要导入模块: from pyasn1_modules import rfc2459 [as 别名]
# 或者: from pyasn1_modules.rfc2459 import Certificate [as 别名]
def parse_cert(raw_bytes):
result = CertInfo()
certType = rfc2459.Certificate();
cert, rest = decoder.decode(raw_bytes, asn1Spec=certType)
subj_pub_key_bytes = frombits(cert.getComponentByName('tbsCertificate').getComponentByName('subjectPublicKeyInfo').getComponentByName('subjectPublicKey'))
SUBJECT = cert.getComponentByName('tbsCertificate').getComponentByName('subject')
for rdn in SUBJECT[0]:
for nv in rdn:
name = nv.getComponentByName('type')
value = nv.getComponentByName('value')
# could pick up regular OUs too
if name == rfc2459.id_at_organizationalUnitName:
#print 'name: %s' % name
#print 'value: [%s] (%s)' % (str(value).strip(), type(value))
result.control_fields.append(str(value).strip())
rsaType = rfc2437.RSAPublicKey();
rsadata,rsadata_rest = decoder.decode(subj_pub_key_bytes, asn1Spec=rsaType)
mod = rsadata.getComponentByName("modulus")
pub_exp = rsadata.getComponentByName("publicExponent")
result.pub_key = rsa.PublicKey(long(mod), long(pub_exp))
return result
示例2: value
# 需要导入模块: from pyasn1_modules import rfc2459 [as 别名]
# 或者: from pyasn1_modules.rfc2459 import Certificate [as 别名]
def value(self):
val = b""
for k in self.field.keys():
ln = b""
dim = b""
if (len(self.field[k])):
ln += k.encode('utf-8') + b";DNS:"
for v in self.field[k]:
ln += dim + v.encode('utf-8')
dim = b"," + k.encode('utf-8') + b";DNS:"
val += (b"" if val == b"" else b",") + ln
return val
# Certificate modifier class that holds callback functions that alter the behavior
# of the certificate generation logic at different stages
示例3: setUp
# 需要导入模块: from pyasn1_modules import rfc2459 [as 别名]
# 或者: from pyasn1_modules.rfc2459 import Certificate [as 别名]
def setUp(self):
self.asn1Spec = rfc2459.Certificate()
示例4: from_string
# 需要导入模块: from pyasn1_modules import rfc2459 [as 别名]
# 或者: from pyasn1_modules.rfc2459 import Certificate [as 别名]
def from_string(cls, public_key):
"""Construct an Verifier instance from a public key or public
certificate string.
Args:
public_key (Union[str, bytes]): The public key in PEM format or the
x509 public key certificate.
Returns:
Verifier: The constructed verifier.
Raises:
ValueError: If the public_key can't be parsed.
"""
public_key = _helpers.to_bytes(public_key)
is_x509_cert = _CERTIFICATE_MARKER in public_key
# If this is a certificate, extract the public key info.
if is_x509_cert:
der = rsa.pem.load_pem(public_key, "CERTIFICATE")
asn1_cert, remaining = decoder.decode(der, asn1Spec=Certificate())
if remaining != b"":
raise ValueError("Unused bytes", remaining)
cert_info = asn1_cert["tbsCertificate"]["subjectPublicKeyInfo"]
key_bytes = _bit_list_to_bytes(cert_info["subjectPublicKey"])
pubkey = rsa.PublicKey.load_pkcs1(key_bytes, "DER")
else:
pubkey = rsa.PublicKey.load_pkcs1(public_key, "PEM")
return cls(pubkey)
示例5: from_string
# 需要导入模块: from pyasn1_modules import rfc2459 [as 别名]
# 或者: from pyasn1_modules.rfc2459 import Certificate [as 别名]
def from_string(cls, key_pem, is_x509_cert):
"""Construct an RsaVerifier 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:
RsaVerifier instance.
Raises:
ValueError: if the key_pem can't be parsed. In either case, error
will begin with 'No PEM start marker'. If
``is_x509_cert`` is True, will fail to find the
"-----BEGIN CERTIFICATE-----" error, otherwise fails
to find "-----BEGIN RSA PUBLIC KEY-----".
"""
key_pem = _to_bytes(key_pem)
if is_x509_cert:
der = rsa.pem.load_pem(key_pem, 'CERTIFICATE')
asn1_cert, remaining = decoder.decode(der, asn1Spec=Certificate())
if remaining != b'':
raise ValueError('Unused bytes', remaining)
cert_info = asn1_cert['tbsCertificate']['subjectPublicKeyInfo']
key_bytes = _bit_list_to_bytes(cert_info['subjectPublicKey'])
pubkey = rsa.PublicKey.load_pkcs1(key_bytes, 'DER')
else:
pubkey = rsa.PublicKey.load_pkcs1(key_pem, 'PEM')
return cls(pubkey)
示例6: from_string
# 需要导入模块: from pyasn1_modules import rfc2459 [as 别名]
# 或者: from pyasn1_modules.rfc2459 import Certificate [as 别名]
def from_string(cls, key_pem, is_x509_cert):
"""Construct an RsaVerifier 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:
RsaVerifier instance.
Raises:
ValueError: if the key_pem can't be parsed. In either case, error
will begin with 'No PEM start marker'. If
``is_x509_cert`` is True, will fail to find the
"-----BEGIN CERTIFICATE-----" error, otherwise fails
to find "-----BEGIN RSA PUBLIC KEY-----".
"""
key_pem = _helpers._to_bytes(key_pem)
if is_x509_cert:
der = rsa.pem.load_pem(key_pem, 'CERTIFICATE')
asn1_cert, remaining = decoder.decode(der, asn1Spec=Certificate())
if remaining != b'':
raise ValueError('Unused bytes', remaining)
cert_info = asn1_cert['tbsCertificate']['subjectPublicKeyInfo']
key_bytes = _bit_list_to_bytes(cert_info['subjectPublicKey'])
pubkey = rsa.PublicKey.load_pkcs1(key_bytes, 'DER')
else:
pubkey = rsa.PublicKey.load_pkcs1(key_pem, 'PEM')
return cls(pubkey)
示例7: from_string
# 需要导入模块: from pyasn1_modules import rfc2459 [as 别名]
# 或者: from pyasn1_modules.rfc2459 import Certificate [as 别名]
def from_string(cls, public_key):
"""Construct an Verifier instance from a public key or public
certificate string.
Args:
public_key (Union[str, bytes]): The public key in PEM format or the
x509 public key certificate.
Returns:
Verifier: The constructed verifier.
Raises:
ValueError: If the public_key can't be parsed.
"""
public_key = _helpers.to_bytes(public_key)
is_x509_cert = _CERTIFICATE_MARKER in public_key
# If this is a certificate, extract the public key info.
if is_x509_cert:
der = rsa.pem.load_pem(public_key, 'CERTIFICATE')
asn1_cert, remaining = decoder.decode(der, asn1Spec=Certificate())
if remaining != b'':
raise ValueError('Unused bytes', remaining)
cert_info = asn1_cert['tbsCertificate']['subjectPublicKeyInfo']
key_bytes = _bit_list_to_bytes(cert_info['subjectPublicKey'])
pubkey = rsa.PublicKey.load_pkcs1(key_bytes, 'DER')
else:
pubkey = rsa.PublicKey.load_pkcs1(public_key, 'PEM')
return cls(pubkey)
示例8: _PopulateX509
# 需要导入模块: from pyasn1_modules import rfc2459 [as 别名]
# 或者: from pyasn1_modules.rfc2459 import Certificate [as 别名]
def _PopulateX509(self):
with self._x509_init_lock:
if self._x509 is None:
url = ('https://www.googleapis.com/service_accounts/v1/metadata/x509/%s'
% urllib.unquote_plus(self._credentials.service_account_email))
response = urlfetch.fetch(
url=url,
validate_certificate=True,
method=urlfetch.GET)
if response.status_code != 200:
raise apiproxy_errors.ApplicationError(
app_identity_service_pb.AppIdentityServiceError.UNKNOWN_ERROR,
'Unable to load X509 cert: %s Response code: %i, Content: %s' % (
url, response.status_code, response.content))
message = 'dummy'
_, signature = self._credentials.sign_blob(message)
for signing_key, x509 in json.loads(response.content).items():
der = rsa.pem.load_pem(x509, 'CERTIFICATE')
asn1_cert, _ = decoder.decode(der, asn1Spec=Certificate())
key_bitstring = (
asn1_cert['tbsCertificate']
['subjectPublicKeyInfo']
['subjectPublicKey'])
key_bytearray = BitStringToByteString(key_bitstring)
public_key = rsa.PublicKey.load_pkcs1(key_bytearray, 'DER')
try:
if rsa.pkcs1.verify(message, signature, public_key):
self._x509 = x509
self._signing_key = signing_key
return
except rsa.pkcs1.VerificationError:
pass
raise apiproxy_errors.ApplicationError(
app_identity_service_pb.AppIdentityServiceError.UNKNOWN_ERROR,
'Unable to find matching X509 cert for private key: %s' % url)
开发者ID:GoogleCloudPlatform,项目名称:python-compat-runtime,代码行数:43,代码来源:app_identity_defaultcredentialsbased_stub.py
示例9: getSubject
# 需要导入模块: from pyasn1_modules import rfc2459 [as 别名]
# 或者: from pyasn1_modules.rfc2459 import Certificate [as 别名]
def getSubject(self):
subj = crypto.X509().get_subject()
subj.C = self.country
subj.ST = self.state
subj.L = self.city
subj.O = self.org
subj.OU = self.unit
subj.CN = self.commonName
subj.emailAddress = self.email
return subj
# Certificate key class that represents the public/private key pair.
示例10: build
# 需要导入模块: from pyasn1_modules import rfc2459 [as 别名]
# 或者: from pyasn1_modules.rfc2459 import Certificate [as 别名]
def build(self):
if (not self.key):
self.key = crypto.PKey()
self.key.generate_key(self.kType, self.kSize)
return self
# Certificate security class that holds the subject public key and
# other miscellaneous information.
示例11: postWrite
# 需要导入模块: from pyasn1_modules import rfc2459 [as 别名]
# 或者: from pyasn1_modules.rfc2459 import Certificate [as 别名]
def postWrite(self, cert, certPathPrefix):
return None
# Certificate class that represents a X509 certificate
示例12: validate_certificate
# 需要导入模块: from pyasn1_modules import rfc2459 [as 别名]
# 或者: from pyasn1_modules.rfc2459 import Certificate [as 别名]
def validate_certificate(host, port, certpath, certext):
hostname = re.sub('[:.]', '_', host)
cert_file = '%s%s%s' % (certpath, hostname, certext)
try:
with open(cert_file, 'r') as f:
# Retrieve previously trusted certificate
trusted_cert = ssl.PEM_cert_to_DER_cert(f.read())
except Exception:
# found no trusted certificate
return False
# Read current certificate from host
conn = None
try:
# workaround for http://bugs.python.org/issue11811
# should go back to using get_server_certificate when fixed
# (Issue is resolved as of python 3.3. Workaround still needed for
# python 2.7 support.)
# rawcert = ssl.get_server_certificate((host, port))
# current_cert = ssl.PEM_cert_to_DER_cert(rawcert)
conn = socket.create_connection((host, port))
sock = ssl.wrap_socket(conn)
current_cert = sock.getpeercert(True)
except Exception:
# couldn't get certificate from host
return False
finally:
if conn is not None:
conn.shutdown(socket.SHUT_RDWR)
conn.close()
# Verify certificate finger prints are the same
if not (hashlib.sha1(trusted_cert).digest() ==
hashlib.sha1(current_cert).digest()):
return False
# check certificate expiration
try:
cert = der_decoder.decode(current_cert,
asn1Spec=rfc2459.Certificate())[0]
tbs = cert.getComponentByName('tbsCertificate')
validity = tbs.getComponentByName('validity')
not_after = validity.getComponentByName('notAfter').getComponent()
not_after = dt.datetime.strptime(str(not_after), '%y%m%d%H%M%SZ')
if dt.datetime.utcnow() >= not_after:
LOG.warning(_('Certificate has expired.'))
return False
except Exception:
LOG.exception('error parsing cert for expiration check')
return False
return True
示例13: _PopulateX509
# 需要导入模块: from pyasn1_modules import rfc2459 [as 别名]
# 或者: from pyasn1_modules.rfc2459 import Certificate [as 别名]
def _PopulateX509(self):
with self.__x509_init_lock:
if not self.__x509:
url = ('https://www.googleapis.com/service_accounts/v1/metadata/x509/%s'
% urllib.unquote_plus(self.__email_address))
resp = urlfetch.fetch(
url=url,
validate_certificate=True,
method=urlfetch.GET)
if resp.status_code != 200:
raise apiproxy_errors.ApplicationError(
app_identity_service_pb.AppIdentityServiceError.UNKNOWN_ERROR,
'Unable to load X509 cert: %s Response code: %i, Content: %s' % (
url, resp.status_code, resp.content))
msg = 'test'
sig = rsa.pkcs1.sign(msg, self.__private_key, 'SHA-256')
for signing_key, x509 in json.loads(resp.content).items():
der = rsa.pem.load_pem(x509, 'CERTIFICATE')
asn1_cert, _ = decoder.decode(der, asn1Spec=Certificate())
key_bitstring = (
asn1_cert['tbsCertificate']
['subjectPublicKeyInfo']
['subjectPublicKey'])
key_bytearray = BitStringToByteString(key_bitstring)
pub = rsa.PublicKey.load_pkcs1(key_bytearray, 'DER')
try:
if rsa.pkcs1.verify(msg, sig, pub):
self.__x509 = x509
self.__signing_key = signing_key
return
except rsa.pkcs1.VerificationError:
pass
raise apiproxy_errors.ApplicationError(
app_identity_service_pb.AppIdentityServiceError.UNKNOWN_ERROR,
'Unable to find matching X509 cert for private key: %s' % url)