本文整理汇总了Python中pyasn1.codec.der.decoder.decode函数的典型用法代码示例。如果您正苦于以下问题:Python decode函数的具体用法?Python decode怎么用?Python decode使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了decode函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: get_cert_from_adobe
def get_cert_from_adobe(adobe_cert):
f = open(adobe_cert, 'r')
buf = f.read()
buffer_base = base64.b64encode(buf)
f.close()
f = open(adobe_cert + '.pem', 'w')
f.write('-----BEGIN PKCS7-----\n')
f.write(buffer_base)
f.write('\n-----END PKCS7-----\n')
f.close()
f = open(adobe_cert + '.pem', 'r')
_, substrate = pem.readPemBlocksFromFile(f, ('-----BEGIN PKCS7-----', '-----END PKCS7-----') )
f.close()
os.remove(adobe_cert + '.pem')
assert substrate, 'bad PKCS7 data on input'
contentInfo, rest = decoder.decode(substrate, asn1Spec=rfc2315.ContentInfo())
if rest:
substrate = substrate[:-len(rest)]
assert encoder.encode(contentInfo, defMode=False) == substrate or \
encoder.encode(contentInfo, defMode=True) == substrate, \
're-encode fails'
contentType = contentInfo.getComponentByName('contentType')
content, _ = decoder.decode(
contentInfo.getComponentByName('content'),
asn1Spec=contentInfoMap[contentType]
)
return content.getComponentByName('certificates').getComponentByPosition(0)
开发者ID:HolyDays,项目名称:Android_FakeID_Exploit,代码行数:35,代码来源:work.py
示例2: print_cert
def print_cert(cert_file):
f = open(cert_file, 'r')
buf = f.read()
buffer_base = base64.b64encode(buf)
f.close()
f = open(cert_file + '.pem', 'w')
f.write('-----BEGIN PKCS7-----\n')
f.write(buffer_base)
f.write('\n-----END PKCS7-----\n')
f.close()
f = open(cert_file + '.pem', 'r')
_, substrate = pem.readPemBlocksFromFile(f, ('-----BEGIN PKCS7-----', '-----END PKCS7-----'))
f.close()
os.remove(cert_file + '.pem')
assert substrate, 'bad PKCS7 data on input'
contentInfo, rest = decoder.decode(substrate, asn1Spec=rfc2315.ContentInfo())
if rest: substrate = substrate[:-len(rest)]
buf = contentInfo.getComponentByName('content')
contentType = contentInfo.getComponentByName('contentType')
content, _ = decoder.decode(
contentInfo.getComponentByName('content'),
asn1Spec=contentInfoMap[contentType]
)
print content.prettyPrint()
开发者ID:HolyDays,项目名称:Android_FakeID_Exploit,代码行数:34,代码来源:work.py
示例3: getSignatureFromApk
def getSignatureFromApk(apkPath):
signature = ''
try:
cert = None
with zipfile.ZipFile(apkPath, 'r') as apk:
certs = [n for n in apk.namelist() if APKSigner.cert_path_regex.match(n)]
if len(certs) < 1:
logging.error(u"[getCertMd5FileFromApk] Found no signing certificates on %s" % apkPath)
return ''
if len(certs) > 1:
logging.error(u"[getCertMd5FileFromApk] Found multiple signing certificates on %s" % apkPath)
return ''
cert = apk.read(certs[0])
content = decoder.decode(cert, asn1Spec=rfc2315.ContentInfo())[0]
if content.getComponentByName('contentType') != rfc2315.signedData:
logging.error(u"[genCertMd5FileFromRsa] 不支持的签名格式")
return signature
content = decoder.decode(content.getComponentByName('content'),
asn1Spec=rfc2315.SignedData())[0]
try:
certificates = content.getComponentByName('certificates')
except Exception, e:
logging.error(u"[genCertMd5FileFromRsa] Certificates 没有找到,原因:%s", e)
return signature
cert_encoded = encoder.encode(certificates)[4:]
signature = hashlib.md5(cert_encoded).hexdigest()
开发者ID:pythonstar,项目名称:star,代码行数:30,代码来源:APKSigner.py
示例4: get_subject_alt_names
def get_subject_alt_names(x509_der):
alt_names_list = []
(x509, spec) = decoder.decode(x509_der, asn1Spec=rfc2459.Certificate())
tbs_crt = x509.getComponentByName("tbsCertificate")
exts = tbs_crt.getComponentByName("extensions")
for ext in exts:
ext_id = ext.getComponentByName("extnID")
critical = ext.getComponentByName("critical")
ext_val = ext.getComponentByName("extnValue")
if ext_id == rfc2459.id_ce_subjectAltName:
(octets, spec) = decoder.decode(ext_val, asn1Spec=OctetString())
(general_names, spec) = decoder.decode(
octets, asn1Spec=rfc2459.GeneralNames())
#Where only looking for dNSNames or the cn
# fields of a directoryName
for general_name in general_names:
name_type = general_name.getName()
if name_type == "dNSName":
octets = general_name.getComponent().asOctets()
dns_name = bytes_to_str(octets)
alt_names_list.append((name_type, dns_name))
if name_type == "directoryName":
dir_name = general_name.getComponent()
for cn in get_cn_from_name(dir_name):
alt_names_list.append(("cn", cn))
return alt_names_list
开发者ID:crc32a,项目名称:ssl_exp,代码行数:26,代码来源:x509.py
示例5: fromTGS
def fromTGS(self, tgs, oldSessionKey, sessionKey):
self.headers = []
header = Header()
header['tag'] = 1
header['taglen'] = 8
header['tagdata'] = '\xff\xff\xff\xff\x00\x00\x00\x00'
self.headers.append(header)
decodedTGS = decoder.decode(tgs, asn1Spec = TGS_REP())[0]
tmpPrincipal = types.Principal()
tmpPrincipal.from_asn1(decodedTGS, 'crealm', 'cname')
self.principal = Principal()
self.principal.fromPrincipal(tmpPrincipal)
# Now let's add the credential
cipherText = decodedTGS['enc-part']['cipher']
cipher = crypto._enctype_table[decodedTGS['enc-part']['etype']]
# Key Usage 8
# TGS-REP encrypted part (includes application session
# key), encrypted with the TGS session key (Section 5.4.2)
plainText = cipher.decrypt(oldSessionKey, 8, str(cipherText))
encTGSRepPart = decoder.decode(plainText, asn1Spec = EncTGSRepPart())[0]
credential = Credential()
server = types.Principal()
server.from_asn1(encTGSRepPart, 'srealm', 'sname')
tmpServer = Principal()
tmpServer.fromPrincipal(server)
credential['client'] = self.principal
credential['server'] = tmpServer
credential['is_skey'] = 0
credential['key'] = KeyBlock()
credential['key']['keytype'] = int(encTGSRepPart['key']['keytype'])
credential['key']['keyvalue'] = str(encTGSRepPart['key']['keyvalue'])
credential['key']['keylen'] = len(credential['key']['keyvalue'])
credential['time'] = Times()
credential['time']['authtime'] = self.toTimeStamp(types.KerberosTime.from_asn1(encTGSRepPart['authtime']))
credential['time']['starttime'] = self.toTimeStamp(types.KerberosTime.from_asn1(encTGSRepPart['starttime']))
credential['time']['endtime'] = self.toTimeStamp(types.KerberosTime.from_asn1(encTGSRepPart['endtime']))
credential['time']['renew_till'] = self.toTimeStamp(types.KerberosTime.from_asn1(encTGSRepPart['renew-till']))
flags = self.reverseFlags(encTGSRepPart['flags'])
credential['tktflags'] = flags
credential['num_address'] = 0
credential.ticket = CountedOctetString()
credential.ticket['data'] = encoder.encode(decodedTGS['ticket'].clone(tagSet=Ticket.tagSet, cloneValueFlag=True))
credential.ticket['length'] = len(credential.ticket['data'])
credential.secondTicket = CountedOctetString()
credential.secondTicket['data'] = ''
credential.secondTicket['length'] = 0
self.credentials.append(credential)
开发者ID:MajorD4m4ge,项目名称:impacket,代码行数:60,代码来源:ccache.py
示例6: test_https_cert_invalid
def test_https_cert_invalid(self):
"""Verify vikidia SSL certificate is invalid."""
try:
from pyasn1_modules import pem, rfc2459
from pyasn1.codec.der import decoder
except ImportError:
raise unittest.SkipTest('pyasn1 and pyasn1_modules not available.')
import ssl
import io
cert = ssl.get_server_certificate(addr=('en.vikidia.org', 443))
s = io.StringIO(unicode(cert))
substrate = pem.readPemFromFile(s)
cert = decoder.decode(substrate, asn1Spec=rfc2459.Certificate())[0]
tbs_cert = cert.getComponentByName('tbsCertificate')
issuer = tbs_cert.getComponentByName('issuer')
organisation = None
for rdn in issuer.getComponent():
for attr in rdn:
attr_type = attr.getComponentByName('type')
if attr_type == rfc2459.id_at_organizationName:
value, _ = decoder.decode(attr.getComponentByName('value'),
asn1Spec=rfc2459.X520name())
organisation = str(value.getComponent())
break
self.assertEqual(organisation, 'TuxFamily.org non-profit organization')
开发者ID:skamithi,项目名称:pywikibot-core,代码行数:28,代码来源:http_tests.py
示例7: testDerCodec
def testDerCodec(self):
substrate = pem.readBase64fromText(self.pem_text)
asn1Object, rest = der_decoder.decode(substrate, asn1Spec=self.asn1Spec)
assert not rest
assert asn1Object.prettyPrint()
assert der_encoder.encode(asn1Object) == substrate
for extn in asn1Object['tbsCertificate']['extensions']:
if extn['extnID'] == rfc3779.id_pe_ipAddrBlocks:
s = extn['extnValue']
addr_blocks, rest = der_decoder.decode(s, rfc3779.IPAddrBlocks())
assert not rest
assert addr_blocks.prettyPrint()
assert der_encoder.encode(addr_blocks) == s
if extn['extnID'] == rfc3779.id_pe_autonomousSysIds:
s = extn['extnValue']
as_ids, rest = der_decoder.decode(s, rfc3779.ASIdentifiers())
assert not rest
assert as_ids.prettyPrint()
assert der_encoder.encode(as_ids) == s
开发者ID:etingof,项目名称:pyasn1-modules,代码行数:25,代码来源:test_rfc3779.py
示例8: extractSecretKey
def extractSecretKey(self, globalSalt, masterPassword, entrySalt):
(globalSalt, masterPassword, entrySalt) = self.is_masterpassword_correct(masterPassword)
if unhexlify('f8000000000000000000000000000001') not in self.key3:
return None
privKeyEntry = self.key3[ unhexlify('f8000000000000000000000000000001') ]
saltLen = ord( privKeyEntry[1] )
nameLen = ord( privKeyEntry[2] )
privKeyEntryASN1 = decoder.decode( privKeyEntry[3+saltLen+nameLen:] )
data = privKeyEntry[3+saltLen+nameLen:]
self.printASN1(data, len(data), 0)
#see https://github.com/philsmd/pswRecovery4Moz/blob/master/pswRecovery4Moz.txt
entrySalt = privKeyEntryASN1[0][0][1][0].asOctets()
privKeyData = privKeyEntryASN1[0][1].asOctets()
privKey = self.decrypt3DES( globalSalt, masterPassword, entrySalt, privKeyData )
self.printASN1(privKey, len(privKey), 0)
privKeyASN1 = decoder.decode( privKey )
prKey= privKeyASN1[0][2].asOctets()
self.printASN1(prKey, len(prKey), 0)
prKeyASN1 = decoder.decode( prKey )
id = prKeyASN1[0][1]
key = long_to_bytes( prKeyASN1[0][3] )
print_debug('DEBUG', 'key: %s' % repr(key))
return key
开发者ID:0ps,项目名称:LaZagne,代码行数:28,代码来源:mozilla.py
示例9: asn1_to_ssh
def asn1_to_ssh(self, pubkey):
lines = pubkey.split("\n")
lines = [x for x in lines if not x.startswith("----")]
base64_encoded = "".join(lines)
try:
# TODO remove pyasn1 dependency
from pyasn1.codec.der import decoder as der_decoder
der_encoded = base64.b64decode(base64_encoded)
der_encoded = der_decoder.decode(der_encoded)[0][1]
key = der_decoder.decode(self.bits_to_bytes(der_encoded))[0]
n = key[0]
e = key[1]
keydata = bytearray()
keydata.extend(struct.pack(">I", len("ssh-rsa")))
keydata.extend(b"ssh-rsa")
keydata.extend(struct.pack(">I", len(self.num_to_bytes(e))))
keydata.extend(self.num_to_bytes(e))
keydata.extend(struct.pack(">I", len(self.num_to_bytes(n)) + 1))
keydata.extend(b"\0")
keydata.extend(self.num_to_bytes(n))
keydata_base64 = base64.b64encode(bytebuffer(keydata))
return ustr(b"ssh-rsa " + keydata_base64 + b"\n", encoding="utf-8")
except ImportError as e:
raise CryptError("Failed to load pyasn1.codec.der")
开发者ID:Azure,项目名称:WALinuxAgent,代码行数:25,代码来源:cryptutil.py
示例10: _decrypt_rep
def _decrypt_rep(data, key, spec, enc_spec, msg_type):
rep = decode(data, asn1Spec=spec)[0]
rep_enc = str(rep['enc-part']['cipher'])
rep_enc = decrypt(key[0], key[1], msg_type, rep_enc)
rep_enc = decode(rep_enc, asn1Spec=enc_spec)[0]
return rep, rep_enc
开发者ID:BwRy,项目名称:pykek,代码行数:7,代码来源:krb5.py
示例11: _get_certs_from_pkcs7_substrate
def _get_certs_from_pkcs7_substrate(substrate):
"""Extracts DER-encoded X509 certificates from a PKCS7 ASN1 DER substrate
:param substrate: The substrate to be processed
:returns: A list of DER-encoded X509 certificates
"""
try:
contentInfo, _ = der_decoder.decode(substrate,
asn1Spec=rfc2315.ContentInfo())
contentType = contentInfo.getComponentByName('contentType')
except Exception:
LOG.exception('Unreadable Certificate.')
raise exceptions.UnreadableCert
if contentType != rfc2315.signedData:
LOG.exception('Unreadable Certificate.')
raise exceptions.UnreadableCert
try:
content, _ = der_decoder.decode(
contentInfo.getComponentByName('content'),
asn1Spec=rfc2315.SignedData())
except Exception:
LOG.exception('Unreadable Certificate.')
raise exceptions.UnreadableCert
for cert in content.getComponentByName('certificates'):
yield der_encoder.encode(cert)
开发者ID:openstack,项目名称:octavia,代码行数:27,代码来源:cert_parser.py
示例12: parse
def parse(cls, data):
(req, err) = decoder.decode(data, asn1Spec=asn1.ProxyMessage())
if err:
raise ParsingError("Invalid request.")
request = req.getComponentByName('message').asOctets()
realm = req.getComponentByName('realm').asOctets()
try: # Python 3.x
realm = str(realm, "UTF8")
except TypeError: # Python 2.x
realm = str(realm)
# Check the length of the whole request message.
(length, ) = struct.unpack("!I", request[0:4])
if length + 4 != len(request):
raise ParsingError("Invalid request length.")
for subcls in cls.__subclasses__():
try:
(req, err) = decoder.decode(request[subcls.OFFSET:],
asn1Spec=subcls.TYPE())
return subcls(realm, request, err)
except error.PyAsn1Error:
pass
raise ParsingError("Invalid request.")
开发者ID:nalind,项目名称:kdcproxy,代码行数:26,代码来源:codec.py
示例13: _decode_alt_names
def _decode_alt_names(self, alt_names):
"""Load SubjectAltName from a ASN.1 GeneralNames value.
:Values:
- `alt_names`: the SubjectAltNama extension value
:Types:
- `alt_name`: `GeneralNames`
"""
for alt_name in alt_names:
tname = alt_name.getName()
comp = alt_name.getComponent()
if tname == "dNSName":
key = "DNS"
value = _decode_asn1_string(comp)
elif tname == "uniformResourceIdentifier":
key = "URI"
value = _decode_asn1_string(comp)
elif tname == "otherName":
oid = comp.getComponentByName("type-id")
value = comp.getComponentByName("value")
if oid == XMPPADDR_OID:
key = "XmppAddr"
value = der_decoder.decode(value, asn1Spec=UTF8String())[0]
value = _decode_asn1_string(value)
elif oid == SRVNAME_OID:
key = "SRVName"
value = der_decoder.decode(value, asn1Spec=IA5String())[0]
value = _decode_asn1_string(value)
else:
logger.debug("Unknown other name: {0}".format(oid))
continue
else:
logger.debug("Unsupported general name: {0}".format(tname))
continue
self.alt_names[key].append(value)
开发者ID:kulikov,项目名称:python-tools,代码行数:35,代码来源:cert.py
示例14: __init__
def __init__(self, realm, request, err):
# Check the length count in the password change request, assuming it
# actually is a password change request. It should be the length of
# the rest of the request, including itself.
(length, ) = struct.unpack("!H", request[4:6])
if length != len(request) - 4:
raise ParsingError("Parsing the KPASSWD request length failed.")
# Check the version number in the password change request, assuming it
# actually is a password change request. Officially we support version
# 1, but 0xff80 is used for set-password, so try to accept that, too.
(version, ) = struct.unpack("!H", request[6:8])
if version != 0x0001 and version != 0xff80:
raise ParsingError("The KPASSWD request is an incorrect version.")
# Read the length of the AP-REQ part of the change request. There
# should be at least that may bytes following this length, since the
# rest of the request is the KRB-PRIV message.
(length, ) = struct.unpack("!H", request[8:10])
if length > len(request) - 10:
raise ParsingError("The KPASSWD request appears to be truncated.")
# See if the tag looks like an AP request, which would look like the
# start of a password change request. The rest of it should be a
# KRB-PRIV message.
(apreq, err) = decoder.decode(request[10:length + 10], asn1Spec=asn1.APREQ())
(krbpriv, err) = decoder.decode(request[length + 10:], asn1Spec=asn1.KRBPriv())
super(KPASSWDProxyRequest, self).__init__(realm, request, err)
self.version = version
开发者ID:nalind,项目名称:kdcproxy,代码行数:30,代码来源:codec.py
示例15: ParsePkcs8
def ParsePkcs8(pkcs8):
seq = ParseASN1Sequence(decoder.decode(Base64WSDecode(pkcs8))[0])
if len(seq) != 3: # need three fields in PrivateKeyInfo
raise errors.KeyczarError("Illegal PKCS8 String.")
version = int(seq[0])
if version != 0:
raise errors.KeyczarError("Unrecognized PKCS8 Version")
[oid, alg_params] = ParseASN1Sequence(seq[1])
key = decoder.decode(seq[2])[0]
# Component 2 is an OCTET STRING which is further decoded
params = {}
if oid == RSA_OID:
key = ParseASN1Sequence(key)
version = int(key[0])
if version != 0:
raise errors.KeyczarError("Unrecognized RSA Private Key Version")
for i in range(len(RSA_PARAMS)):
params[RSA_PARAMS[i]] = long(key[i+1])
elif oid == DSA_OID:
alg_params = ParseASN1Sequence(alg_params)
for i in range(len(DSA_PARAMS)):
params[DSA_PARAMS[i]] = long(alg_params[i])
params['x'] = long(key)
else:
raise errors.KeyczarError("Unrecognized AlgorithmIdentifier: not RSA/DSA")
return params
开发者ID:Jimboukfk,项目名称:tools,代码行数:26,代码来源:util.py
示例16: extractModAndExp
def extractModAndExp(self,certDER=None):
if not certDER:
self.extractCertificate()
DERdata = self.serverCertificate
else: DERdata = certDER
assert (self.serverCertificate or certDER), "No server certificate, cannot extract pubkey"
rv = decoder.decode(DERdata, asn1Spec=univ.Sequence())
bitstring = rv[0].getComponentByPosition(0).getComponentByPosition(6).getComponentByPosition(1)
#bitstring is a list of ints, like [01110001010101000...]
#convert it into into a string '01110001010101000...'
stringOfBits = ''
for bit in bitstring:
bit_as_str = str(bit)
stringOfBits += bit_as_str
#treat every 8 chars as an int and pack the ints into a bytearray
ba = bytearray()
for i in range(0, len(stringOfBits)/8):
onebyte = stringOfBits[i*8 : (i+1)*8]
oneint = int(onebyte, base=2)
ba.append(oneint)
#decoding the nested sequence
rv = decoder.decode(str(ba), asn1Spec=univ.Sequence())
exponent = rv[0].getComponentByPosition(1)
modulus = rv[0].getComponentByPosition(0)
self.serverModulus = int(modulus)
self.serverExponent = int(exponent)
n = bi2ba(self.serverModulus)
e = bi2ba(self.serverExponent)
modulus_len_int = len(n)
self.serverModLength = bi2ba(modulus_len_int)
if len(self.serverModLength) == 1: self.serverModLength.insert(0,0) #zero-pad to 2 bytes
return (self.serverModulus,self.serverExponent)
开发者ID:miohtama,项目名称:tlsnotary,代码行数:33,代码来源:tlsn_crypto.py
示例17: testDerCodec
def testDerCodec(self):
substrate = pem.readBase64fromText(self.pem_text_unordered)
asn1Object, rest = der_decoder.decode(substrate, asn1Spec=self.asn1Spec)
assert not rest
assert asn1Object.prettyPrint()
assert der_encoder.encode(asn1Object) == substrate
contentType = asn1Object['contentType']
substrate = asn1Object['content']
contentInfoMap = {
(1, 2, 840, 113549, 1, 7, 1): rfc2315.Data(),
(1, 2, 840, 113549, 1, 7, 2): rfc2315.SignedData(),
(1, 2, 840, 113549, 1, 7, 3): rfc2315.EnvelopedData(),
(1, 2, 840, 113549, 1, 7, 4): rfc2315.SignedAndEnvelopedData(),
(1, 2, 840, 113549, 1, 7, 5): rfc2315.DigestedData(),
(1, 2, 840, 113549, 1, 7, 6): rfc2315.EncryptedData()
}
innerAsn1Object, rest = der_decoder.decode(
substrate, asn1Spec=contentInfoMap[contentType]
)
asn1Object['content'] = der_encoder.encode(innerAsn1Object)
substrate = pem.readBase64fromText(self.pem_text_reordered)
assert not rest
assert asn1Object.prettyPrint()
assert der_encoder.encode(asn1Object) == substrate
开发者ID:luke-chang,项目名称:gecko-1,代码行数:33,代码来源:test_rfc2315.py
示例18: parse
def parse(data):
"""Return elements from parsed X509 certificate data.
Args:
data: str of X509 certificate file contents
Returns:
{str: value} of notable certificate elements s.t.:
['modulus'] = int of included RSA public key
['publicExponent'] = int of included RSA public key
['subject'] = str of compiled subject in rfc2253 format
['body'] = str of X509 DER binary in base64
['type'] = str of "X509 PRIVATE"
"""
# initialize empty return dictionary
dict = {}
lines = []
for s in data.splitlines():
if '-----' == s[:5] and "BEGIN" in s:
if not "CERTIFICATE" in s:
raise NotImplementedError(\
"Only PEM Certificates are supported. Header: %s", s)
else:
# include this b64 data for decoding
lines.append(s.strip())
body = ''.join(lines)
raw_data = body.decode("base64")
cert = decoder.decode(raw_data, asn1Spec=Certificate())[0]
# dump parsed PEM data to text
text = cert.prettyPrint()
# GET RSA KEY
# ===========
if not (RSA_ID in text):
raise NotImplementedError("Only RSA X509 certificates are supported.")
# rip out RSA public key binary
key_bits = RX_PUBLIC_KEY.search(text).group(1)
key_binhex = hex(int(key_bits, 2))[2:-1]
key_bin = key_binhex.decode("hex")
# reparse RSA Public Key PEM binary
key = decoder.decode(key_bin, asn1Spec=RSAPublicKey())[0]
# add RSA key elements to return dictionary
dict.update(key.dict())
# GET CERTIFICATE SUBJECT
# =======================
subject_text = RX_SUBJECT.search(text).group(0)
attrs = RX_SUBJECT_ATTR.findall(subject_text)
dict['subject'] = rfc2253_name(attrs)
# add base64 encoding and type to return dictionary
dict['body'] = body
dict['type'] = "X509 CERTIFICATE"
return dict
开发者ID:andrewdyates,项目名称:rsa_x509_pem,代码行数:59,代码来源:x509_pem.py
示例19: get_ext_by_oid
def get_ext_by_oid(cert, oid):
from pyasn1.codec.der import decoder
from pyasn1_modules import rfc2459
cert, _ = decoder.decode(cert.as_der(), asn1Spec=rfc2459.Certificate())
for ext in cert['tbsCertificate']['extensions']:
if ext['extnID'].prettyPrint() == oid:
return decoder.decode(ext['extnValue'])[0].asOctets()
return None
开发者ID:pb-pravin,项目名称:python-u2flib-server,代码行数:8,代码来源:matchers.py
示例20: check_ca
def check_ca(self):
for extension in self.extensions:
oid = extension.getComponentByName('extnID')
if oid != id_ce_basicConstraints:
continue
value = decoder.decode(extension.getComponentByName('extnValue'), asn1Spec=OctetString())[0]
constraints = decoder.decode(value, asn1Spec=BasicConstraints())[0]
return bool(constraints[0])
开发者ID:Joori,项目名称:pandacoin-electrum,代码行数:8,代码来源:x509.py
注:本文中的pyasn1.codec.der.decoder.decode函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论