本文整理汇总了Python中pyasn1.codec.der.encoder.encode函数的典型用法代码示例。如果您正苦于以下问题:Python encode函数的具体用法?Python encode怎么用?Python encode使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了encode函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: getRSAPublicKey
def getRSAPublicKey(self):
""" Gets an ASN.1-encoded form of this RSA key's public key. """
# Get a RSAPublicKey structure
pkinfo = univ.Sequence()
rsakey = self.getRSAKey()
pkinfo.setComponentByPosition(0, univ.Integer(rsakey.n))
pkinfo.setComponentByPosition(1, univ.Integer(rsakey.e))
# Encode the public key info as a bit string
pklong = long(encoder.encode(pkinfo).encode('hex'), 16)
pkbitstring = univ.BitString("'00%s'B" % self.toBitString_(pklong))
# Get the rsaEncryption identifier:
idrsaencryption = univ.ObjectIdentifier('1.2.840.113549.1.1.1')
# Get the AlgorithmIdentifier for rsaEncryption
idinfo = univ.Sequence()
idinfo.setComponentByPosition(0, idrsaencryption)
idinfo.setComponentByPosition(1, univ.Null(''))
# Get the SubjectPublicKeyInfo structure
publickeyinfo = univ.Sequence()
publickeyinfo.setComponentByPosition(0, idinfo)
publickeyinfo.setComponentByPosition(1, pkbitstring)
# Encode the public key structure
publickey = encoder.encode(publickeyinfo)
return publickey
示例2: getChainFingerprint
def getChainFingerprint(certChain):
fingerprint = hashlib.sha1()
secret = hashlib.sha1()
for cert in certChain:
fingerprint.update(der_encoder.encode(cert))
secret.update(der_encoder.encode(cert[0][0]['serialNumber']))
return fingerprint.hexdigest(), base64.b64encode(secret.digest())
示例3: to_pem
def to_pem(self, pem_format='PKCS8'):
if isinstance(self._prepared_key, pyrsa.PrivateKey):
der = self._prepared_key.save_pkcs1(format='DER')
if pem_format == 'PKCS8':
pem = pyrsa_pem.save_pem(PKCS8_RSA_HEADER + der, pem_marker='PRIVATE KEY')
elif pem_format == 'PKCS1':
pem = pyrsa_pem.save_pem(der, pem_marker='RSA PRIVATE KEY')
else:
raise ValueError("Invalid pem format specified: %r" % (pem_format,))
else:
if pem_format == 'PKCS8':
asn_key = AsnPubKey()
asn_key.setComponentByName('modulus', self._prepared_key.n)
asn_key.setComponentByName('publicExponent', self._prepared_key.e)
der = encoder.encode(asn_key)
header = PubKeyHeader()
header['oid'] = univ.ObjectIdentifier('1.2.840.113549.1.1.1')
pub_key = OpenSSLPubKey()
pub_key['header'] = header
pub_key['key'] = univ.BitString.fromOctetString(der)
der = encoder.encode(pub_key)
pem = pyrsa_pem.save_pem(der, pem_marker='PUBLIC KEY')
elif pem_format == 'PKCS1':
der = self._prepared_key.save_pkcs1(format='DER')
pem = pyrsa_pem.save_pem(der, pem_marker='RSA PUBLIC KEY')
else:
raise ValueError("Invalid pem format specified: %r" % (pem_format,))
return pem
示例4: ExportRsaX509
def ExportRsaX509(params):
oid = ASN1Sequence(RSA_OID, univ.Null())
key = ASN1Sequence(univ.Integer(params['n']), univ.Integer(params['e']))
binkey = BytesToBin(encoder.encode(key))
pubkey = univ.BitString("'%s'B" % binkey) # needs to be a BIT STRING
seq = ASN1Sequence(oid, pubkey)
return Base64WSEncode(encoder.encode(seq))
示例5: toDER
def toDER(self):
tbsCertificate = rfc2459.TBSCertificate()
tbsCertificate.setComponentByName('version', self.getVersion())
tbsCertificate.setComponentByName('serialNumber', self.getSerialNumber())
tbsCertificate.setComponentByName('signature', self.getSignature())
tbsCertificate.setComponentByName('issuer', self.getIssuer())
tbsCertificate.setComponentByName('validity', self.getValidity())
tbsCertificate.setComponentByName('subject', self.getSubject())
tbsCertificate.setComponentByName('subjectPublicKeyInfo', self.getSubjectPublicKeyInfo())
if self.extensions:
extensions = rfc2459.Extensions().subtype(
explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 3))
count = 0
for extension in self.extensions:
extensions.setComponentByPosition(count, extension)
count += 1
tbsCertificate.setComponentByName('extensions', extensions)
tbsDER = encoder.encode(tbsCertificate)
rsaPrivateKey = rsa.PrivateKey(self.issuerRSA_N, self.issuerRSA_E, self.issuerRSA_D,
self.issuerRSA_P, self.issuerRSA_Q)
signature = rsa.sign(tbsDER, rsaPrivateKey, 'SHA-256')
certificate = rfc2459.Certificate()
certificate.setComponentByName('tbsCertificate', tbsCertificate)
certificate.setComponentByName('signatureAlgorithm', self.getSignatureAlgorithm())
certificate.setComponentByName('signatureValue', byteStringToHexifiedBitString(signature))
return encoder.encode(certificate)
示例6: getRevokedSerials
def getRevokedSerials(crl):
serials = []
if None != crl[0]['tbsCertList'] and None != crl[0]['tbsCertList']['revokedCertificates']:
print b64encode(encoder.encode(crl[0]['tbsCertList']['issuer']))
for cert in crl[0]['tbsCertList']['revokedCertificates']:
serials.append(b64encode(encoder.encode(cert['userCertificate'])))
return serials
示例7: _parseauthattrs
def _parseauthattrs(auth_attrs, required):
results = dict.fromkeys(required)
for attr in auth_attrs:
if (attr['type'] in oids.OID_TO_CLASS and
oids.OID_TO_CLASS.get(attr['type']) in required):
# There are more than those I require, but I don't know what they are,
# and what to do with them. The spec does not talk about them.
# One example:
# 1.3.6.1.4.1.311.2.1.11 contains as value 1.3.6.1.4.1.311.2.1.21
# SPC_STATEMENT_TYPE_OBJID SPC_INDIVIDUAL_SP_KEY_PURPOSE_OBJID
results[oids.OID_TO_CLASS.get(attr['type'])] = attr['values']
if None in iter(results.values()):
raise Asn1Error('Missing mandatory field(s) in auth_attrs.')
# making sure that the auth_attrs were processed in correct order
# they need to be sorted in ascending order in the SET, when DER encoded
# This also makes sure that the tag on Attributes is correct.
a = [der_encoder.encode(i) for i in auth_attrs]
a.sort()
attrs_for_hash = pkcs7.Attributes()
for i in range(len(auth_attrs)):
d, _ = decoder.decode(a[i], asn1Spec=pkcs7.Attribute())
attrs_for_hash.setComponentByPosition(i, d)
encoded_attrs = der_encoder.encode(attrs_for_hash)
return results, encoded_attrs
示例8: 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
示例9: api_sign_certificate
def api_sign_certificate():
if request.headers['Content-Type'] == 'application/json':
certificate = b64decode(str(request.json.get("certificate")))
bitcoin_address = str(request.json.get("bitcoin_address"))
# Get the ACA secret key
f = open(ACA_KEY, "r")
sk_string = f.read()
f.close()
sk = RSA.importKey(sk_string)
# Get the certificate hash and the asn1 representation of the certificate
certificate_hash = certificate_hashing(certificate)
signature = sk.sign(certificate_hash, 1)[0]
asn1_cert = decoder.decode(certificate, asn1Spec=Certificate())[0]
# Attach the signature to the certificate
bin_signature = Signature("'%s'H" % ''.join("%02X" % ord(c) for c in long_to_bytes(signature)))
asn1_cert.setComponentByName("signatureValue", bin_signature)
# Store the certificate
der_cert = encoder.encode(asn1_cert)
store_certificate(encoder.encode(asn1_cert), bitcoin_address)
return b64encode(der_cert)
示例10: validatecertificatesignature
def validatecertificatesignature(self, signed_cert, signing_cert):
"""Given a cert signed by another cert, validates the signature."""
# First the naive way -- note this does not check expiry / use etc.
cert_signing = x509.load_pem_x509_certificate(ssl.DER_cert_to_PEM_cert(der_encoder.encode(signing_cert)).encode(), default_backend())
public_key = cert_signing.public_key()
der_cert = der_encoder.encode(signed_cert)
cert_signed = x509.load_pem_x509_certificate(ssl.DER_cert_to_PEM_cert(der_cert).encode(), default_backend())
data = cert_signed.tbs_certificate_bytes
signature = cert_signed.signature
new_api = hasattr(public_key, "verify")
if not new_api:
verifier = public_key.verifier(signature, padding.PKCS1v15(), cert_signed.signature_hash_algorithm)
try:
verifier.update(data)
verifier.verify()
except:
raise Asn1Error('1: Validation of cert signature failed.')
else:
try:
verifier = public_key.verify(signature, data, padding.PKCS1v15(), cert_signed.signature_hash_algorithm)
# verifier.update(data)
# verifier.verify()
except:
raise Asn1Error('1: Validation of cert signature failed.')
示例11: _write
def _write(self, file, header, principal, sessions):
self._pack_write(file, '!H', self._FVNO_4)
self._write_header_tags(file, header)
self._write_principal(file, principal)
for s in sessions:
self._write_principal(file, s.client)
self._write_principal(file, s.service)
self._write_key(file, s.key)
self._write_time(file, s.auth_time)
self._write_time(file, s.start_time)
self._write_time(file, s.end_time)
self._write_time(file, s.renew_until)
self._pack_write(file, 'B', 0 if s.u2u_ticket is None else 1)
self._write_ticket_flags(file, s.ticket_flags or 0)
self._write_addresses(file, s.addresses or [])
self._write_authdata(file, [])
ticket = asn1.Ticket()
s.ticket.to_asn1(ticket)
self._write_data(file, encoder.encode(ticket))
if s.u2u_ticket is not None:
u2u_ticket = asn1.Ticket()
s.u2u_ticket.to_asn1(u2u_ticket)
self._write_data(file, encoder.encode(u2u_ticket))
else:
self._write_data(file, "")
示例12: 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)
示例13: make_ap_req_bytes
def make_ap_req_bytes(self, auth_key_usage,
subkey=None, checksum=None):
now = datetime.datetime.utcnow()
authenticator = asn1.Authenticator()
authenticator.setComponentByName('authenticator-vno', 5)
authenticator.setComponentByName('crealm', self.client.realm)
asn1.seq_set(authenticator, 'cname',
self.client.components_to_asn1)
if checksum is not None:
asn1.seq_set_dict(authenticator, 'cksum', checksum)
authenticator.setComponentByName('cusec', now.microsecond)
authenticator.setComponentByName('ctime',
types.KerberosTime.to_asn1(now))
if subkey is not None:
asn1.seq_set_dict(authenticator, 'subkey', subkey.to_asn1())
encoder.encode(authenticator)
ap_req = asn1.APReq()
ap_req.setComponentByName('pvno', 5)
ap_req.setComponentByName('msg-type', int(constants.Asn1Tags.ap_req))
asn1.seq_set_flags(ap_req, 'ap-options', constants.APOptions())
asn1.seq_set(ap_req, 'ticket', self.ticket.to_asn1)
asn1.seq_set_dict(ap_req, 'authenticator',
self.key.encrypted_data(
auth_key_usage, encoder.encode(authenticator)))
return encoder.encode(ap_req)
示例14: 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
示例15: getTGT
def getTGT(self, userName, requestPAC=True):
clientName = Principal(userName, type=constants.PrincipalNameType.NT_PRINCIPAL.value)
asReq = AS_REQ()
domain = self.__domain.upper()
serverName = Principal('krbtgt/%s' % domain, type=constants.PrincipalNameType.NT_PRINCIPAL.value)
pacRequest = KERB_PA_PAC_REQUEST()
pacRequest['include-pac'] = requestPAC
encodedPacRequest = encoder.encode(pacRequest)
asReq['pvno'] = 5
asReq['msg-type'] = int(constants.ApplicationTagNumbers.AS_REQ.value)
asReq['padata'] = noValue
asReq['padata'][0] = noValue
asReq['padata'][0]['padata-type'] = int(constants.PreAuthenticationDataTypes.PA_PAC_REQUEST.value)
asReq['padata'][0]['padata-value'] = encodedPacRequest
reqBody = seq_set(asReq, 'req-body')
opts = list()
opts.append(constants.KDCOptions.forwardable.value)
opts.append(constants.KDCOptions.renewable.value)
opts.append(constants.KDCOptions.proxiable.value)
reqBody['kdc-options'] = constants.encodeFlags(opts)
seq_set(reqBody, 'sname', serverName.components_to_asn1)
seq_set(reqBody, 'cname', clientName.components_to_asn1)
if domain == '':
raise Exception('Empty Domain not allowed in Kerberos')
reqBody['realm'] = domain
now = datetime.datetime.utcnow() + datetime.timedelta(days=1)
reqBody['till'] = KerberosTime.to_asn1(now)
reqBody['rtime'] = KerberosTime.to_asn1(now)
reqBody['nonce'] = random.getrandbits(31)
supportedCiphers = (int(constants.EncryptionTypes.rc4_hmac.value),)
seq_set_iter(reqBody, 'etype', supportedCiphers)
message = encoder.encode(asReq)
try:
r = sendReceive(message, domain, self.__kdcHost)
except KerberosError, e:
if e.getErrorCode() == constants.ErrorCodes.KDC_ERR_ETYPE_NOSUPP.value:
# RC4 not available, OK, let's ask for newer types
supportedCiphers = (int(constants.EncryptionTypes.aes256_cts_hmac_sha1_96.value),
int(constants.EncryptionTypes.aes128_cts_hmac_sha1_96.value),)
seq_set_iter(reqBody, 'etype', supportedCiphers)
message = encoder.encode(asReq)
r = sendReceive(message, domain, self.__kdcHost)
else:
raise e