def encode(ecdsa_key: object, **kwargs):
        alg_id = SequenceOf()
        alg_id.setComponentByPosition(
            0, ObjectIdentifier([1, 2, 840, 10045, 2, 1]))
        alg_id.setComponentByPosition(
            1,
            ObjectIdentifier(
                ber_decoder.decode(b'\x06' +
                                   bytes([len(ecdsa_key.G.curve.oid)]) +
                                   ecdsa_key.G.curve.oid)[0].asTuple()))

        zero_fill = math.ceil(ecdsa_key.G.curve.q.bit_length() / 8)

        params_seq = Sequence()
        params_seq.setComponentByPosition(0, Integer(1))
        params_seq.setComponentByPosition(
            1, OctetString(Bytes(ecdsa_key.d).zfill(zero_fill)))
        params_seq.setComponentByPosition(
            2, PublicPoint(ecdsa_key.format_public_point()))

        param_oct = OctetString(encoder.encode(params_seq))

        top_seq = Sequence()
        top_seq.setComponentByPosition(0, Integer(0))
        top_seq.setComponentByPosition(1, alg_id)
        top_seq.setComponentByPosition(2, param_oct)

        encoded = encoder.encode(top_seq)
        encoded = PKCS8ECDSAPrivateKey.transport_encode(encoded, **kwargs)
        return encoded
Example #2
0
    def pkcs7_sign_msg(self, msg):
        '''WIP: PKCS#7 sign with certificate
        '''

        signed = self.sign(msg)

        owner_cert_pub = self.pub_cert

        # signedData (PKCS #7)
        oi_pkcs7_signed = ObjectIdentifier((1, 2, 840, 113549, 1, 7, 2))
        oi_pkcs7_data = ObjectIdentifier((1, 2, 840, 113549, 1, 7, 1))
        oi_sha256 = ObjectIdentifier((2, 16, 840, 1, 101, 3, 4, 2, 1))
        oi_pkcs7_rsa_enc = ObjectIdentifier((1, 2, 840, 113549, 1, 1, 1))

        der = Sequence().setComponentByPosition(0, oi_pkcs7_signed)

        data = Sequence()
        data = data.setComponentByPosition(0, Integer(1))
        data = data.setComponentByPosition(1, Set().setComponentByPosition(0, Sequence().setComponentByPosition(0, oi_sha256).setComponentByPosition(1, Null(''))))
        data = data.setComponentByPosition(2, Sequence().setComponentByPosition(0, oi_pkcs7_data).setComponentByPosition(1, Sequence().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0)).setComponentByPosition(0, OctetString(hexValue=msg.encode('hex')))))
        data = data.setComponentByPosition(3, Sequence().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0)).setComponentByPosition(0, owner_cert_pub))

        data4001 = Sequence().setComponentByPosition(0, owner_cert_pub[0][3])
        data4001 = data4001.setComponentByPosition(1, owner_cert_pub[0][1])
        data4002 = Sequence().setComponentByPosition(0, oi_sha256).setComponentByPosition(1, Null(''))
        data4003 = Sequence().setComponentByPosition(0, oi_pkcs7_rsa_enc).setComponentByPosition(1, Null(''))
        data4004 = OctetString(hexValue=signed.encode('hex'))

        data = data.setComponentByPosition(4, Set().setComponentByPosition(0, Sequence().setComponentByPosition(0, Integer(1)).setComponentByPosition(1, data4001).setComponentByPosition(2, data4002).setComponentByPosition(3, data4003).setComponentByPosition(4, data4004)))

        der = der.setComponentByPosition(1, Sequence().subtype(implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 0)).setComponentByPosition(0, data))

        return der_encoder.encode(der)
Example #3
0
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()
Example #4
0
    def encode(rsa_key: object, **kwargs):
        seq = Sequence()
        seq.setComponentByPosition(
            0, ObjectIdentifier([1, 2, 840, 113549, 1, 1, 1]))
        seq.setComponentByPosition(1, Null())

        param_bs = X509RSASubjectPublicKey.encode(rsa_key)

        top_seq = Sequence()
        top_seq.setComponentByPosition(0, seq)
        top_seq.setComponentByPosition(1, param_bs)

        encoded = encoder.encode(top_seq)
        return X509RSAPublicKey.transport_encode(encoded, **kwargs)
Example #5
0
    def encode(rsa_key: object, **kwargs):
        alg_id = Sequence()
        alg_id.setComponentByPosition(0, ObjectIdentifier([1, 2, 840, 113549, 1, 1, 1]))
        alg_id.setComponentByPosition(1, Null())

        param_oct = OctetString(PKCS1RSAPrivateKey.encode(rsa_key, encode_pem=False))

        top_seq = Sequence()
        top_seq.setComponentByPosition(0, Integer(0))
        top_seq.setComponentByPosition(1, alg_id)
        top_seq.setComponentByPosition(2, param_oct)

        encoded = encoder.encode(top_seq)
        encoded = PKCS8RSAPrivateKey.transport_encode(encoded, **kwargs)
        return encoded
Example #6
0
    def __sig__(self):
        # return the signature data into an ASN.1 sequence of integers in DER format
        seq = Sequence(componentType=NamedTypes(*[NamedType(n, Integer()) for n in self.__mpis__]))
        for n in self.__mpis__:
            seq.setComponentByName(n, getattr(self, n))

        return encoder.encode(seq)
Example #7
0
    def __sig__(self):
        # return the signature data into an ASN.1 sequence of integers in DER format
        seq = Sequence()
        for i in self:
            seq.setComponentByPosition(len(seq), Integer(i))

        return encoder.encode(seq)
Example #8
0
def export_der(items: list, item_types: list = None) -> bytes:
    """
    Converts items (in order) to DER-encoded bytes.

    Parameters:
        items (list): Items to be encoded.
    
    Returns:
        bytes: DER-encoded sequence bytes.
    """
    seq = Sequence()

    if not item_types:
        item_types = [Integer] * len(items)

    seq_len = 0
    for val, item_type in zip(items, item_types):
        if item_type == SequenceOf:
            item = item_type()
            item.extend(val)
        else:
            item = item_type(val)

        seq.setComponentByPosition(seq_len, item)
        seq_len += 1

    return encoder.encode(seq)
Example #9
0
    def encode(dsa_key: object, **kwargs):
        dsa_params = X509DSAParams.encode(dsa_key)

        seq = Sequence()
        seq.setComponentByPosition(0,
                                   ObjectIdentifier([1, 2, 840, 10040, 4, 1]))
        seq.setComponentByPosition(1, dsa_params)

        y_bits = X509DSASubjectPublicKey.encode(dsa_key)

        top_seq = Sequence()
        top_seq.setComponentByPosition(0, seq)
        top_seq.setComponentByPosition(1, y_bits)

        encoded = encoder.encode(top_seq)
        return X509DSAPublicKey.transport_encode(encoded, **kwargs)
Example #10
0
def is_ev_cert(ee_cert):
    '''Return True if ee_cert is an extended validation certificate, else False.

    Args:
        ee_cert (EndEntityCert)
    '''
    oids = []
    oid_certificate_policies = ObjectIdentifier('2.5.29.32')

    all_extensions = ee_cert.tbscert.pyasn1['extensions']
    if all_extensions is not None:
        policy_extensions = [
            ext for ext in all_extensions
            if ext['extnID'] == oid_certificate_policies
        ]
        if len(policy_extensions) > 0:
            policy_extension = policy_extensions[0]
            sequence_der = policy_extension['extnValue']  # type: Sequence()
            try:
                sequence, _ = der_decoder(sequence_der, Sequence())
            except pyasn1.error.PyAsn1Error:
                sequence = []  # invalid encoded certificate policy extension

            for idx in range(len(sequence)):
                inner_sequence = sequence.getComponentByPosition(idx)
                oid = inner_sequence.getComponentByPosition(0)
                oids.append(str(oid))

    intersection = list(set(oids) & set(EV_OIDs))
    return intersection != []
Example #11
0
def scts_from_ocsp_resp(ocsp_resp_der):
    '''Return list of SCTs of the OCSP status response.

    Args:
        ocsp_resp_der(bytes): DER encoded OCSP status response

    Return:
        [<ctutlz.rfc6962.SignedCertificateTimestamp>, ...]
    '''
    if ocsp_resp_der:
        ocsp_resp, _ = der_decoder(
            ocsp_resp_der, asn1Spec=pyasn1_modules.rfc2560.OCSPResponse())

        response_bytes = ocsp_resp.getComponentByName('responseBytes')
        if response_bytes is not None:
            # os: octet string
            response_os = response_bytes.getComponentByName('response')

            der_decoder.defaultErrorState = ber.decoder.stDumpRawValue
            response, _ = der_decoder(response_os, Sequence())

            sctlist_os_hex = sctlist_hex_from_ocsp_pretty_print(
                response.prettyPrint())

            if sctlist_os_hex:
                sctlist_os_der = binascii.unhexlify(sctlist_os_hex)
                sctlist_os, _ = der_decoder(sctlist_os_der, OctetString())
                sctlist_hex = sctlist_os.prettyPrint().split('0x')[-1]
                sctlist_der = binascii.unhexlify(sctlist_hex)

                sctlist = SignedCertificateTimestampList(sctlist_der)
                return [SignedCertificateTimestamp(entry.sct_der)
                        for entry
                        in sctlist.sct_list]
    return []
    def encode(dh_key: object, **kwargs):
        dh_params = X509DiffieHellmanParams.encode(dh_key)

        seq = Sequence()
        seq.setComponentByPosition(
            0, ObjectIdentifier([1, 2, 840, 113549, 1, 3, 1]))
        seq.setComponentByPosition(1, dh_params)

        y_bits = X509DiffieHellmanSubjectPublicKey.encode(dh_key)

        top_seq = Sequence()
        top_seq.setComponentByPosition(0, seq)
        top_seq.setComponentByPosition(1, y_bits)

        encoded = encoder.encode(top_seq)
        return X509DiffieHellmanPublicKey.transport_encode(encoded, **kwargs)
    def encode(dh_key: object, **kwargs):
        dh_params = SequenceOf()
        dh_params.setComponentByPosition(0, Integer(dh_key.p))
        dh_params.setComponentByPosition(1, Integer(dh_key.g))

        alg_id = Sequence()
        alg_id.setComponentByPosition(0, ObjectIdentifier([1, 2, 840, 113549, 1, 3, 1]))
        alg_id.setComponentByPosition(1, dh_params)

        param_oct = OctetString(encoder.encode(Integer(dh_key.key)))

        top_seq = Sequence()
        top_seq.setComponentByPosition(0, Integer(0))
        top_seq.setComponentByPosition(1, alg_id)
        top_seq.setComponentByPosition(2, param_oct)

        encoded = encoder.encode(top_seq)
        encoded = PKCS8DiffieHellmanPrivateKey.transport_encode(encoded, **kwargs)
        return encoded
    def encode(eddsa_key: object, **kwargs):
        alg_id = SequenceOf()
        alg_id.setComponentByPosition(0, ObjectIdentifier(eddsa_key.curve.oid))

        seq = Sequence()
        seq.setComponentByPosition(0, alg_id)
        seq.setComponentByPosition(1,
                                   X509EdDSASubjectPublicKey.encode(eddsa_key))

        encoded = encoder.encode(seq)
        return X509EdDSAPublicKey.transport_encode(encoded, **kwargs)
    def encode(dsa_key: object, **kwargs):
        dss_params = SequenceOf()
        dss_params.setComponentByPosition(0, Integer(dsa_key.p))
        dss_params.setComponentByPosition(1, Integer(dsa_key.q))
        dss_params.setComponentByPosition(2, Integer(dsa_key.g))

        alg_id = Sequence()
        alg_id.setComponentByPosition(
            0, ObjectIdentifier([1, 2, 840, 10040, 4, 1]))
        alg_id.setComponentByPosition(1, dss_params)

        param_oct = OctetString(encoder.encode(Integer(dsa_key.x)))

        top_seq = Sequence()
        top_seq.setComponentByPosition(0, Integer(0))
        top_seq.setComponentByPosition(1, alg_id)
        top_seq.setComponentByPosition(2, param_oct)

        encoded = encoder.encode(top_seq)
        encoded = PKCS8DSAPrivateKey.transport_encode(encoded, **kwargs)
        return encoded
Example #16
0
 def verify(self, msg, sig):
     # Convert byte array strings back into their longs
     if len(sig) % 2:
         raise JWKError("Invalid signature value used.")
     split = len(sig) / 2
     r = Integer(base64_to_long(base64.urlsafe_b64encode(sig[:split])))
     s = Integer(base64_to_long(base64.urlsafe_b64encode(sig[split:])))
     ss = Sequence(tagSet=[tag.Tag(0, 32, 16)])
     ss.setComponentByPosition(0, r)
     ss.setComponentByPosition(1, s)
     sig_asn = encoder.encode(ss)
     ver = self.prepared_key.verify(sig_asn, msg)
     return ver
Example #17
0
    def to_der(self):
        """
        Return parameters as OpenSSL compatible DER encoded key
        """
        seq = Sequence()

        for idx, x in enumerate([
                0, self.n, self.e, self.d, self.p, self.q, self.dP, self.dQ,
                self.qInv
        ]):
            seq.setComponentByPosition(idx, Integer(x))

        return encoder.encode(seq)
Example #18
0
    def sign(self, plaintext: bytes) -> Bytes:
        """
        Signs the `plaintext`.

        Parameters:
            plaintext (bytes): Plaintext to sign.
        
        Returns:
            Bytes: Signature.
        """
        alg_id = Sequence()
        alg_id.setComponentByPosition(0, HASH_OID_LOOKUP[type(self.hash_obj)])
        alg_id.setComponentByPosition(1, Null())

        top_seq = Sequence()
        top_seq.setComponentByPosition(0, alg_id)
        top_seq.setComponentByPosition(
            1, OctetString(self.hash_obj.hash(plaintext)))

        der_encoded = encoder.encode(top_seq)
        return self.rsa.decrypt(self.padder.pad(der_encoded)).zfill(
            (self.rsa.n.bit_length() + 7) // 8)
Example #19
0
 def setComponentByPosition(self, idx, value=None, *rest, **kw):
     if isinstance(value, base.Asn1Item):
         ftags = self._componentType.getTypeByPosition(idx).getTagSet()
         vtags = value.getTagSet()
         if (ftags[-1][0] == tagClassContext
                 and (vtags == ftags[:-1] or vtags[:-1] == ftags[:-1])):
             # The value matches the field except for the context
             # tag (implicit or explicit).  Clone the value with
             # the field's tag set to make the assignment work.
             if isinstance(value, base.AbstractConstructedAsn1Item):
                 value = value.clone(tagSet=ftags, cloneValueFlag=True)
             else:
                 value = value.clone(tagSet=ftags)
     return Sequence.setComponentByPosition(self, idx, value, *rest, **kw)
Example #20
0
 def setComponentByPosition(self, idx, value=None, *rest, **kw):
     if isinstance(value, base.Asn1Item):
         ftags = self._componentType.getTypeByPosition(idx).getTagSet()
         vtags = value.getTagSet()
         if (ftags[-1][0] == tagClassContext and
             (vtags == ftags[:-1] or vtags[:-1] == ftags[:-1])):
             # The value matches the field except for the context
             # tag (implicit or explicit).  Clone the value with
             # the field's tag set to make the assignment work.
             if isinstance(value, base.AbstractConstructedAsn1Item):
                 value = value.clone(tagSet=ftags, cloneValueFlag=True)
             else:
                 value = value.clone(tagSet=ftags)
     return Sequence.setComponentByPosition(self, idx, value, *rest, **kw)
Example #21
0
    def pkcs7_enveloped_msg(self, msg, data, iv="0123456789012345"):
        """WIP: PKCS#7 envelop msg, data with cert"""
        oi_pkcs7_rsa_enc = ObjectIdentifier((1, 2, 840, 113549, 1, 1, 1))
        oi_pkcs7_data = ObjectIdentifier((1, 2, 840, 113549, 1, 7, 1))
        oi_seed_cbc = ObjectIdentifier(id_seed_cbc)

        der = Sequence().setComponentByPosition(
            0, ObjectIdentifier(id_pkcs7_enveloped_data))

        data_set = Sequence().setComponentByPosition(0, Integer(0))
        data_set = data_set.setComponentByPosition(
            1,
            Sequence().setComponentByPosition(
                0, self.pub_cert[0][3]).setComponentByPosition(
                    1, self.pub_cert[0][1]))
        data_set = data_set.setComponentByPosition(
            2,
            Sequence().setComponentByPosition(
                0, oi_pkcs7_rsa_enc).setComponentByPosition(1, Null('')))
        data_set = data_set.setComponentByPosition(
            3, OctetString(hexValue=msg.encode('hex')))

        data_seq = Sequence().setComponentByPosition(0, oi_pkcs7_data)
        data_seq = data_seq.setComponentByPosition(
            1,
            Sequence().setComponentByPosition(
                0, oi_seed_cbc).setComponentByPosition(
                    1, OctetString(hexValue=iv.encode('hex'))))
        data_seq = data_seq.setComponentByPosition(
            2,
            OctetString(
                hexValue=data.encode('hex')).subtype(implicitTag=tag.Tag(
                    tag.tagClassContext, tag.tagFormatSimple, 0)))

        data = Sequence().setComponentByPosition(0, Integer(0))
        data = data.setComponentByPosition(
            1,
            Set().setComponentByPosition(0, data_set))
        data = data.setComponentByPosition(2, data_seq)

        der = der.setComponentByPosition(
            1,
            Sequence().subtype(
                implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple,
                                    0)).setComponentByPosition(0, data))
        return der_encoder.encode(der)
    def encode(ecdsa_key: object, **kwargs):
        curve_seq = [
            ObjectIdentifier([1, 2, 840, 10045, 2, 1]),
            X509ECDSAParams.encode(ecdsa_key)
        ]

        encoded = SequenceOf()
        encoded.extend(curve_seq)

        top_seq = Sequence()
        top_seq.setComponentByPosition(0, encoded)
        top_seq.setComponentByPosition(
            1, X509ECDSASubjectPublicKey.encode(ecdsa_key))

        encoded = encoder.encode(top_seq)
        return X509ECDSAPublicKey.transport_encode(encoded, **kwargs)
Example #23
0
 def setComponentByPosition(self,
                            idx,
                            value=None,
                            verifyConstraints=True,
                            exactTypes=False,
                            matchTags=True,
                            matchConstraints=True):
     if idx == 0:  # controlType
         try:
             cls = KNOWN_CONTROLS[value]
             if self.__class__ != cls:
                 self.__class__ = cls
         except KeyError:
             pass
     return Sequence.setComponentByPosition(self, idx, value,
                                            verifyConstraints, exactTypes,
                                            matchTags, matchConstraints)
Example #24
0
 def setComponentByPosition(self, idx, value=None,
                            verifyConstraints=True,
                            exactTypes=False,
                            matchTags=True,
                            matchConstraints=True):
     if idx == 0:  # controlType
         try:
             cls = KNOWN_CONTROLS[value]
             if self.__class__ != cls:
                 self.__class__ = cls
         except KeyError:
             pass
     return Sequence.setComponentByPosition(self, idx, value,
                                            verifyConstraints,
                                            exactTypes,
                                            matchTags,
                                            matchConstraints)
Example #25
0
    def encode(eddsa_key: object, **kwargs):
        alg_id = SequenceOf()
        alg_id.setComponentByPosition(0, ObjectIdentifier(eddsa_key.curve.oid))

        zero_fill = math.ceil(eddsa_key.d.int().bit_length() / 8)
        priv_key = OctetString(
            encoder.encode(
                OctetString(Bytes.wrap(eddsa_key.d).zfill(zero_fill))))

        top_seq = Sequence()
        top_seq.setComponentByPosition(0, Integer(0))
        top_seq.setComponentByPosition(1, alg_id)
        top_seq.setComponentByPosition(2, priv_key)

        encoded = encoder.encode(top_seq)
        encoded = PKCS8EdDSAPrivateKey.transport_encode(encoded, **kwargs)
        return encoded
Example #26
0
class LastReq(SequenceOf):
    componentType = Sequence(
        componentType=NamedTypes(_mfield('lr-type', 0, Integer()),
                                 _mfield('lr-value', 1, GeneralizedTime())))
Example #27
0
class AuthorizationData(SequenceOf):
    componentType = Sequence(
        componentType=NamedTypes(NamedType('ad-type', _c(0, Integer())),
                                 NamedType('ad-data', _c(1, OctetString()))))
Example #28
0
class LastReq(SequenceOf):
    componentType = Sequence(
        componentType=NamedTypes(NamedType('lr-type', _c(0, Integer())),
                                 NamedType('lr-value', _c(1, KerberosTime()))))
Example #29
0
from base64 import encodebytes

c = int.from_bytes(b"Hello! Can you give me the flag, please? I would really appreciate it!", "big")
m = int.from_bytes(b"Quack! Quack!", "big")

p = 11 # just pick some arbitrary prime here and change it until something works

for i in range(1, 10000):
    q = i * 2**559 + 1
    if not isprime(q):
        continue
    try:
        n = p*q
        d = discrete_log(n, c, m)
        e = mod_inverse(d,(p-1)*(q-1))
        if pow(m,d,n)!=c: raise
        if pow(c,e,n)!=m: raise
    except:
        print(f'i={i} failed')
        continue

    # Success! Let's construct the PEM file
    print(f'i={i} succeeded')
    print(f'd={d}')
    seq = Sequence()
    for i,x in enumerate([0, n, e, d, p, q, d%(p-1), d%(q-1), mod_inverse(q,p)]):
        seq.setComponentByPosition(i, Integer(x))
    b64 = encodebytes(encode(seq)).decode('ascii')
    print(f'-----BEGIN RSA PRIVATE KEY-----\n{b64}-----END RSA PRIVATE KEY-----')
    break
Example #30
0
class AuthorizationData(SequenceOf):
    componentType = Sequence(
        componentType=NamedTypes(_mfield('ad-type', 0, Integer()),
                                 _mfield('ad-data', 1, GeneralizedTime())))