def _as_asn1(self, key): asn1_crl = Sequence() asn1_inner = Sequence() asn1_crl.setComponentByPosition(0, asn1_inner) id = Sequence() id.setComponentByPosition(0, ObjectIdentifier(self.crl_oid)) id.setComponentByPosition(1, Null()) asn1_inner.setComponentByPosition(0, id) asn1_crl.setComponentByPosition(1, id) asn1_inner.setComponentByPosition(1, self.asn1_subject) asn1_inner.setComponentByPosition(2, self.last_update) asn1_inner.setComponentByPosition(3, self.next_update) seq = Sequence() for n, (serial, date) in enumerate(self.crl): entry = Sequence() entry.setComponentByPosition(0, Integer(serial)) d = strftime(self.time_fmt, gmtime(date)) entry.setComponentByPosition(1, UTCTime(d)) seq.setComponentByPosition(n, entry) asn1_inner.setComponentByPosition(4, seq) der_inner = der_encode(asn1_inner) key.reset_context(md="md5") key.sign_init() key.sign_update(der_inner) sig = key.sign_final() sig = BitString("'%s'H" % "".join("%02X" % ord(c) for c in sig)) asn1_crl.setComponentByPosition(2, sig) return asn1_crl
def testDerCodec(self): substrate = pem.readBase64fromText(self.alg_id_3_pem_text) asn1Object, rest = der_decode(substrate, asn1Spec=self.asn1Spec) assert not rest assert asn1Object.prettyPrint() assert asn1Object['algorithm'] == rfc8419.id_sha512 assert not asn1Object['parameters'].isValue assert der_encode(asn1Object) == substrate
def testDerCodec(self): substrate = pem.readBase64fromText(self.rfc3211_ex1_pem_text) asn1Object, rest = der_decode(substrate, asn1Spec=self.asn1Spec) assert not rest assert asn1Object.prettyPrint() assert der_encode(asn1Object) == substrate alg_oid = asn1Object['pwri']['keyDerivationAlgorithm']['algorithm'] assert alg_oid == rfc8018.id_PBKDF2
def testDerCodec(self): substrate = pem.readBase64fromText(self.attr_set_pem_text) asn1Object, rest = der_decode (substrate, asn1Spec=self.asn1Spec) assert not rest assert asn1Object.prettyPrint() assert der_encode(asn1Object) == substrate for attr in asn1Object: assert attr['type'] in rfc5652.cmsAttributesMap.keys() av, rest = der_decode(attr['values'][0], asn1Spec=rfc5652.cmsAttributesMap[attr['type']]) assert not rest assert av.prettyPrint() assert der_encode(av) == attr['values'][0] if attr['type'] == rfc7906.id_aa_KP_contentDecryptKeyID: assert av == univ.OctetString(hexValue='7906')
def testDerCodec(self): substrate = pem.readBase64fromText(self.private_key_pem_text) asn1Object, rest = der_decode(substrate, asn1Spec=self.asn1Spec) assert not rest assert asn1Object.prettyPrint() assert der_encode(asn1Object) == substrate assert asn1Object['parameters']['namedCurve'] == rfc5480.secp384r1
def encode_data(self): ack = asn1.SkrAcknowledgement(tagSet=(tag.initTagSet( tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 1)))) ack.setComponentByName('successful', self.successful) if self.broken_record is not None: ack.setComponentByName('broken-record', self.broken_record) if self.error_description is not None: ack.setComponentByName('error-description', self.error_description) return der_encode(ack)
def testDerCodec(self): substrate = pem.readBase64fromText(self.extns_pem_text) asn1Object, rest = der_decode(substrate, asn1Spec=self.asn1Spec) assert not rest assert asn1Object.prettyPrint() assert der_encode(asn1Object) == substrate oids = [ ] for extn in asn1Object: oids.append(extn['extnID']) extn_value, rest = der_decode(extn['extnValue'], rfc5280.certificateExtensionsMap[extn['extnID']]) assert not rest assert extn_value.prettyPrint() assert der_encode(extn_value) == extn['extnValue'] assert rfc8360.id_pe_ipAddrBlocks_v2 in oids assert rfc8360.id_pe_autonomousSysIds_v2 in oids
def testDerCodec(self): substrate = pem.readBase64fromText(self.pem_text) asn1Object, rest = der_decode(substrate, asn1Spec=self.asn1Spec) assert not rest assert asn1Object.prettyPrint() assert der_encode(asn1Object) == substrate
def testDerCodec(self): substrate = pem.readBase64fromText(self.otp_pem_text) asn1Object, rest = der_decode(substrate, asn1Spec=self.asn1Spec) assert not rest assert asn1Object.prettyPrint() assert der_encode(asn1Object) == substrate assert asn1Object['certificationRequestInfo']['version'] == 0 for attr in asn1Object['certificationRequestInfo']['attributes']: assert attr['attrType'] in rfc6402.cmcControlAttributesMap.keys() av, rest = der_decode(attr['attrValues'][0], rfc6402.cmcControlAttributesMap[attr['attrType']]) assert not rest assert der_encode(av) == attr['attrValues'][0] if attr['attrType'] == rfc7894.id_aa_otpChallenge: assert av['printableString'] == '90503846'
def encode_data(self): reqs = asn1.SkrTrap(tagSet=(tag.initTagSet( tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 0)))) reqs['trap-type'] = self.type if self.trap_message is not None: reqs['trap-message'] = self.trap_message if self.reference_message is not None: reqs['reference-message'] = self.reference_message return der_encode(reqs)
def testDerCodec(self): substrate = pem.readBase64fromText(self.pem_text) asn1Object, rest = der_decode(substrate, asn1Spec=self.asn1Spec) assert not rest assert asn1Object.prettyPrint() assert der_encode(asn1Object) == substrate hex1 = univ.OctetString(hexValue='00000001') assert asn1Object['keyInfo']['counter'] == hex1
def testDerCodec(self): substrate = pem.readBase64fromText(self.dh_cert_pem_text) asn1Object, rest = der_decode(substrate, asn1Spec=self.asn1Spec) assert not rest assert asn1Object.prettyPrint() assert der_encode(asn1Object) == substrate spki_a = asn1Object['tbsCertificate']['subjectPublicKeyInfo'][ 'algorithm'] assert spki_a['algorithm'] == rfc3279.dhpublicnumber spki_a_p, rest = der_decode(spki_a['parameters'], asn1Spec=rfc3279.DomainParameters()) assert not rest assert spki_a_p.prettyPrint() assert der_encode(spki_a_p) == spki_a['parameters'] q_value = 65838278260281264030127352144753816831178774189428428256716126077244217603537 assert spki_a_p['q'] == q_value
def testDerCodec(self): substrate = pem.readBase64fromText(self.rfc8591_pem_pext) asn1Object, rest = der_decode(substrate, asn1Spec=self.asn1Spec) assert not rest assert asn1Object.prettyPrint() assert der_encode(asn1Object) == substrate assert asn1Object['contentType'] == rfc5083.id_ct_authEnvelopedData aed, rest = der_decode(asn1Object['content'], asn1Spec=rfc5083.AuthEnvelopedData(), decodeOpenTypes=True) assert not rest assert aed.prettyPrint() assert der_encode(aed) == asn1Object['content'] assert aed['version'] == 0 cea = aed['authEncryptedContentInfo']['contentEncryptionAlgorithm'] assert cea['algorithm'] == rfc5084.id_aes128_GCM assert cea['parameters']['aes-ICVlen'] == 16
def encode_data(self): reqs = asn1.SkrDataLoadRequest( value=self.task_id, tagSet=( tag.initTagSet( tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 2) ) ) ) return der_encode(reqs)
def encode_data(self): reqs = asn1.SkrDataInterruptRequest( value=(self.task_id), tagSet=( tag.initTagSet( tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 6) ) ) ) return der_encode(reqs)
def testOpenTypes(self): substrate = pem.readBase64fromText(self.alg_id_5_pem_text) asn1Object, rest = der_decode(substrate, asn1Spec=self.asn1Spec, decodeOpenTypes=True) assert not rest assert asn1Object.prettyPrint() assert asn1Object['algorithm'] == rfc8419.id_shake256_len assert asn1Object['parameters'] == 512 assert der_encode(asn1Object) == substrate
async def make_authenticode_signeddata( cert, signer, authenticode_digest, digest_algo, timestamp=None, opus_info=None, opus_url=None, ): """Creates a SignedData object containing the signature for a PE file. Arguments: cert (X509): public certificate used for signing signer (function): signing function authenticode_digest (bytes): Authenticode digest of PE file to sign NB. This is not simply the hash of the file! digest_algo (str): digest algorithm to use. e.g. 'sha256' timestamp (UTCTime): optional. timestamp to include in the signature. If not provided, the current time is used. opus_info (string): Additional information to include in the signature opus_url (string): URL to include in the signature Returns: A ContentInfo ASN1 object """ if not timestamp: timestamp = useful.UTCTime.fromDateTime(datetime.now()) asn_digest_algo = ASN_DIGEST_ALGO_MAP[digest_algo] spc = make_spc(digest_algo, authenticode_digest) encoded_spc = der_encode(spc) pkcs7_cert = x509_to_pkcs7(cert) signer_info = make_signer_info(pkcs7_cert, digest_algo, timestamp, calc_spc_digest(encoded_spc, digest_algo)) signer_digest = calc_signerinfo_digest(signer_info, digest_algo) signer_info["encryptedDigest"] = await signer(signer_digest, digest_algo) sig = SignedData() sig["version"] = 1 sig["digestAlgorithms"][0] = asn_digest_algo sig["certificates"][0]["certificate"] = pkcs7_cert sig["contentInfo"]["contentType"] = id_spcIndirectDataContext sig["contentInfo"]["content"] = encoded_spc sig["signerInfos"][0] = signer_info ci = ContentInfo() ci["contentType"] = id_signedData ci["content"] = sig return ci
def testDerCodec(self): substrate = pem.readBase64fromText(self.pem_text) asn1Object, rest = der_decode(substrate, asn1Spec=self.asn1Spec) assert not rest assert asn1Object.prettyPrint() assert der_encode(asn1Object) == substrate assert asn1Object['compressionAlgorithm']['algorithmID-ShortForm'] == 0 cci = asn1Object['compressedContentInfo'] assert cci['unnamed']['contentType-ShortForm'] == 25 assert cci['compressedContent'].prettyPrint()[:12] == '0x789c6d8fd1'
def testDerCodec(self): substrate = pem.readBase64fromText(self.smime_capabilities_pem_text) asn1Object, rest = der_decode(substrate, asn1Spec=self.asn1Spec) assert not rest assert asn1Object.prettyPrint() assert der_encode(asn1Object) == substrate count = 0 for cap in asn1Object: if cap['capabilityID'] in rfc5751.smimeCapabilityMap.keys(): substrate = cap['parameters'] cap_p, rest = der_decode( substrate, asn1Spec=rfc5751.smimeCapabilityMap[cap['capabilityID']]) assert not rest assert cap_p.prettyPrint() assert der_encode(cap_p) == substrate count += 1 assert count == 8
def testDerCodec(self): substrate = pem.readBase64fromText(self.priv_key_pem_text) asn1Object, rest = der_decode(substrate, asn1Spec=self.asn1Spec) assert not rest assert asn1Object.prettyPrint() assert asn1Object['privateKeyAlgorithm']['algorithm'] == rfc8410.id_Ed25519 assert asn1Object['privateKey'].isValue assert asn1Object['privateKey'].prettyPrint()[0:10] == "0x0420d4ee" assert asn1Object['publicKey'].isValue assert asn1Object['publicKey'].prettyPrint()[0:10] == "1164575857" assert der_encode(asn1Object) == substrate
def testDerCodec(self): substrate = pem.readBase64fromText(self.cert_pem_text) asn1Object, rest = der_decode(substrate, asn1Spec=self.asn1Spec) assert not rest assert asn1Object.prettyPrint() assert der_encode(asn1Object) == substrate found_kp_sipDomain = False for extn in asn1Object['tbsCertificate']['extensions']: if extn['extnID'] == rfc5280.id_ce_extKeyUsage: assert extn['extnID'] in rfc5280.certificateExtensionsMap.keys() ev, rest = der_decode(extn['extnValue'], asn1Spec=rfc5280.certificateExtensionsMap[extn['extnID']]) assert not rest assert ev.prettyPrint() assert der_encode(ev) == extn['extnValue'] assert rfc5924.id_kp_sipDomain in ev found_kp_sipDomain = True assert found_kp_sipDomain
def testOpenTypes(self): substrate = pem.readBase64fromText(self.digicert_ec_cert_pem_text) asn1Object, rest = der_decode(substrate, asn1Spec=self.asn1Spec, decodeOpenTypes=True) assert not rest assert asn1Object.prettyPrint() assert der_encode(asn1Object) == substrate spki_alg = asn1Object['tbsCertificate']['subjectPublicKeyInfo']['algorithm'] assert spki_alg['algorithm'] == rfc5480.id_ecPublicKey assert spki_alg['parameters']['namedCurve'] == rfc5480.secp384r1
def testOpenTypes(self): substrate = pem.readBase64fromText(self.rfc3211_ex1_pem_text) asn1Object, rest = der_decode(substrate, asn1Spec=self.asn1Spec, decodeOpenTypes=True) assert not rest assert asn1Object.prettyPrint() assert der_encode(asn1Object) == substrate icount = asn1Object['pwri']['keyDerivationAlgorithm']['parameters'][ 'iterationCount'] assert icount == 5
def verify_signature_x5u(data, signature, x5u): """ Verify a signature, given the x5u of the public key. If the signature is valid, returns True. If the signature is invalid, raise an exception explaining why. """ cert = verify_x5u(x5u) encoded = der_encode(cert["tbsCertificate"]["subjectPublicKeyInfo"]) cert_b64 = base64.b64encode(encoded).decode() return verify_signature_pubkey(data, signature, cert_b64)
def encodeLoginData(key, data): iv = secrets.token_bytes(8) des = DES3.new(key, DES3.MODE_CBC, iv) ciphertext = des.encrypt(PKCS7pad(data.encode())) asn1data = Sequence() asn1data[0] = OctetString(MAGIC1) asn1data[1] = Sequence() asn1data[1][0] = ObjectIdentifier(MAGIC2) asn1data[1][1] = OctetString(iv) asn1data[2] = OctetString(ciphertext) return b64encode(der_encode(asn1data)).decode()
def testDerCodec(self): substrate = pem.readBase64fromText(self.pem_text) asn1Object, rest = der_decode(substrate, asn1Spec=self.asn1Spec) assert not rest assert asn1Object.prettyPrint() assert der_encode(asn1Object) == substrate spki_a = asn1Object['certificationRequestInfo']['subjectPublicKeyInfo']['algorithm'] assert spki_a['algorithm'] == rfc5480.dhpublicnumber assert spki_a['algorithm'] in rfc5280.algorithmIdentifierMap.keys() params, rest = der_decode(spki_a['parameters'], asn1Spec=rfc6955.DomainParameters()) assert not rest assert params.prettyPrint() assert der_encode(params) == spki_a['parameters'] assert params['validationParms']['pgenCounter'] == 55 sig_a = asn1Object['signatureAlgorithm'] assert sig_a['algorithm'] == rfc6955.id_dhPop_static_sha1_hmac_sha1 assert sig_a['algorithm'] in rfc5280.algorithmIdentifierMap.keys() assert sig_a['parameters'] == der_encode(univ.Null(""))
def test_layer(substrate, content_type): asn1Object, rest = der_decode(substrate, asn1Spec=layers[content_type]) assert not rest assert asn1Object.prettyPrint() assert der_encode(asn1Object) == substrate if content_type == rfc4073.id_ct_contentWithAttrs: for attr in asn1Object['attrs']: assert attr['attrType'] in rfc5652.cmsAttributesMap.keys() return asn1Object
def testDerCodec(self): substrate = pem.readBase64fromText(self.key_pkg_pem_text) asn1Object, rest = der_decode(substrate, asn1Spec=self.asn1Spec) assert not rest assert asn1Object.prettyPrint() assert der_encode(asn1Object) == substrate assert asn1Object['contentType'] in rfc5652.cmsContentTypesMap asn1Spec = rfc5652.cmsContentTypesMap[asn1Object['contentType']] skp, rest = der_decode(asn1Object['content'], asn1Spec=asn1Spec) assert not rest assert skp.prettyPrint() assert der_encode(skp) == asn1Object['content'] for attr in skp['sKeyPkgAttrs']: assert attr['attrType'] in rfc6031.sKeyPkgAttributesMap.keys() for osk in skp['sKeys']: for attr in osk['sKeyAttrs']: assert attr['attrType'] in rfc6031.sKeyAttributesMap.keys()
def testDerCodec(self): substrate = pem.readBase64fromText(self.cert_pem_text) asn1Object, rest = der_decode(substrate, asn1Spec=self.asn1Spec) assert not rest assert asn1Object.prettyPrint() assert der_encode(asn1Object) == substrate extn_list = [] for extn in asn1Object['tbsCertificate']['extensions']: extn_list.append(extn['extnID']) if extn['extnID'] in rfc5280.certificateExtensionsMap.keys(): extnValue, rest = der_decode( extn['extnValue'], asn1Spec=rfc5280.certificateExtensionsMap[extn['extnID']]) assert der_encode(extnValue) == extn['extnValue'] if extn['extnID'] == rfc5280.id_ce_extKeyUsage: assert rfc8209.id_kp_bgpsec_router in extnValue assert rfc5280.id_ce_extKeyUsage in extn_list
def testDerCodec(self): substrate = pem.readBase64fromText(self.pem_text) asn1Object, rest = der_decode(substrate, asn1Spec=self.asn1Spec) assert not rest assert asn1Object.prettyPrint() assert der_encode(asn1Object) == substrate assert asn1Object['acinfo']['version'] == 1 count = 0 for attr in asn1Object['acinfo']['attributes']: assert attr['type'] in rfc5280.certificateAttributesMap.keys() av, rest = der_decode( attr['values'][0], asn1Spec=rfc5280.certificateAttributesMap[attr['type']]) assert not rest assert av.prettyPrint() assert der_encode(av) == attr['values'][0] count += 1 assert count == 5
def testOpenTypes(self): substrate = pem.readBase64fromText(self.pem_text) asn1Object, rest = der_decode(substrate, asn1Spec=self.asn1Spec, decodeOpenTypes=True) assert not rest assert asn1Object.prettyPrint() assert der_encode(asn1Object) == substrate assert asn1Object['attrType'] in rfc5652.cmsAttributesMap.keys() assert asn1Object['attrValues'][0] == 0x5cbf8654
def testDerCodec(self): substrate = pem.readBase64fromText(self.pem_text) asn1Object, rest = der_decode(substrate, asn1Spec=self.asn1Spec) assert not rest assert asn1Object.prettyPrint() assert der_encode(asn1Object) == substrate assert asn1Object['attrType'] == rfc6019.id_aa_binarySigningTime bintime, rest = der_decode(asn1Object['attrValues'][0], asn1Spec=rfc6019.BinaryTime()) assert bintime == 0x5cbf8654
def _as_pem (self, asn1val, header = None) : """ Create base64 encoded version of asn1val and wrap in in appropriate BEGIN/END lines for pem format. The BEGIN/END text differs for different asn1 values, so we specify this as "header". This is necessary since most constructors in M2Crypto don't seem to have a version that directly accepts ASN.1, so we generate the pem version here. """ # Derived class might want to have default pem_header if header is None : header = self.pem_header if isinstance (asn1val, Asn1Item) : asn1val = der_encode (asn1val) v = b64encode (asn1val) return '-----BEGIN %s-----\n%s-----END %s-----\n' \ % (header, v, header)
def fingerprint_contents(self): """Produce the contents of the condition hash. This function is called internally by the `getCondition` method. Returns: bytes: Encoded contents of fingerprint hash. """ if self.modulus is None: raise MissingDataError('Requires modulus') asn1_obj = nat_decode({'modulus': self.modulus}, asn1Spec=RsaFingerprintContents()) asn1_der = der_encode(asn1_obj) return asn1_der
def fingerprint_contents(self): """ .. todo:: docs """ subconditions = [ c.to_asn1_dict() for c in sorted( map(lambda c: c['body'] if isinstance(c['body'], Condition) else c['body'].condition, self.subconditions)) ] asn1_fingerprint_obj = nat_decode( {'threshold': self.threshold, 'subconditions': subconditions}, asn1Spec=ThresholdFingerprintContents(), ) return der_encode(asn1_fingerprint_obj)
def testDerCodec(self): substrate = pem.readBase64fromText(self.pem_text) asn1Object, rest = der_decode(substrate, asn1Spec=self.asn1Spec) assert not rest assert asn1Object.prettyPrint() assert der_encode(asn1Object) == substrate assert asn1Object['contentType'] == rfc5652.id_signedData inner, rest = der_decode(asn1Object['content'], asn1Spec=rfc5652.SignedData()) assert inner['encapContentInfo']['eContentType'] == rfc4108.id_ct_firmwarePackage assert inner['encapContentInfo']['eContent'] found_target_hardware_identifier_attribute = False for attr in inner['signerInfos'][0]['signedAttrs']: if attr['attrType'] == rfc4108.id_aa_targetHardwareIDs: found_target_hardware_identifier_attribute = True assert found_target_hardware_identifier_attribute
def serialize_binary(self): """ Serialize condition to a buffer. Encodes the condition as a string of bytes. This is used internally for encoding subconditions, but can also be used to passing around conditions in a binary protocol for instance. CONDITION = VARUINT TYPE_BITMASK VARBYTES HASH VARUINT MAX_COST Return: Serialized condition """ asn1_dict = self.to_asn1_dict() asn1_condition = nat_decode(asn1_dict, asn1Spec=Asn1Condition()) binary_condition = der_encode(asn1_condition) return binary_condition
def fingerprint_contents(self): """Produce the contents of the condition hash. This function is called internally by the ``condition`` method/property. Returns: bytes: Encoded contents of fingerprint hash. """ if not self.subcondition: raise MissingDataError('Requires subcondition') try: subcondition_asn1_dict = self.subcondition.condition.to_asn1_dict() except AttributeError: subcondition_asn1_dict = self.subcondition.to_asn1_dict() return der_encode(nat_decode({ 'prefix': self.prefix, 'maxMessageLength': self.max_message_length, 'subcondition': subcondition_asn1_dict, }, asn1Spec=PrefixFingerprintContents()))
def serialize_binary(self): """ Serialize fulfillment to bytes. Encodes the fulfillment as a string of bytes. This is used internally for encoding subfulfillments, but can also be used to passing around fulfillments in a binary protocol for instance. Returns: bytes: Serialized fulfillment (DER encoded). """ asn1_dict = {self.TYPE_ASN1: self.asn1_dict_payload} try: asn1 = nat_decode(asn1_dict, asn1Spec=Asn1Fulfillment()) except TypeError as exc: raise ASN1DecodeError( 'Internal error! Failed to transform dict "{}" ' 'into pyasn1 schema object.'.format(asn1_dict) ) from exc try: bin_obj = der_encode(asn1) except PyAsn1Error as exc: raise ASN1EncodeError('Failed to encode fulfillment.') from exc return bin_obj
def fingerprint_contents(self): asn1_fingerprint_obj = nat_decode( {'publicKey': self.public_key}, asn1Spec=Ed25519FingerprintContents(), ) return der_encode(asn1_fingerprint_obj)
def as_der(self, key): """ Serialize CRL in DER format. """ x = self._as_asn1(key) return der_encode(x)