本文整理汇总了Python中pyasn1.codec.der.decoder.decode函数的典型用法代码示例。如果您正苦于以下问题:Python decode函数的具体用法?Python decode怎么用?Python decode使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了decode函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
示例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()
示例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()
示例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
示例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)
示例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')
示例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
示例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
示例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")
示例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
示例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)
示例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.")
示例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)
示例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
示例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