Пример #1
0
 def verify(self, plaintext: bytes, signature, otherkey: rsa.RSAPublicKey):
     otherkey.verify(
         signature, plaintext,
         apadding.PSS(mgf=apadding.MGF1(hashes.SHA256()),
                      salt_length=apadding.PSS.MAX_LENGTH), hashes.SHA256())
Пример #2
0
 def test_rsa_padding_supported_pss(self):
     assert backend.rsa_padding_supported(
         padding.PSS(mgf=padding.MGF1(hashes.SHA1()),
                     salt_length=0)) is True
Пример #3
0
 def __init__(self):
     padfn = padding.PSS(padding.MGF1(hashes.SHA384()),
                         hashes.SHA384.digest_size)
     super(_PS384, self).__init__(padfn, hashes.SHA384())
Пример #4
0
def main(argv=None):
    argv = parser.parse_args(argv)
    nonce = os.urandom(13)
    nonce_b64 = base64.b64encode(nonce).decode("ascii")

    privkey_key = os.urandom(32)

    action_key = os.urandom(32)
    action_key_b64 = base64.b64encode(action_key).decode("ascii")
    config_shared_key = os.urandom(32)
    if argv.algo == "rsa":
        priv_key = rsa.generate_private_key(public_exponent=65537,
                                            key_size=argv.bits)
    elif argv.algo == "dsa":
        priv_key = dsa.generate_private_key(public_exponent=65537,
                                            key_size=argv.bits)
    pub_key = priv_key.public_key()
    pub_key_bytes = pub_key.public_bytes(
        encoding=serialization.Encoding.DER,
        format=serialization.PublicFormat.SubjectPublicKeyInfo,
    )
    priv_key_bytes = priv_key.private_bytes(
        encoding=serialization.Encoding.DER,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption(),
    )

    session = requests.Session()
    body, files = transform_payload(serverConfigQuery_query, {})
    result = session.post(argv.url, data=body, files=files)
    if not result.ok and not argv.url.endswith("/graphql"):
        argv.url = "%s/graphql" % argv.url.rstrip("/")
        result = session.post(argv.url, data=body, files=files)
    if not result.ok:
        raise
    serverConfig = result.json()["data"]["secretgraphConfig"]
    hash_algos = serverConfig["hashAlgorithms"]
    hash_algo = hashlib.new(hash_algos[0])
    chosen_hash = getattr(hashes, hash_algo.name.upper())()
    prepared_cluster = {
        "publicKey": pub_key_bytes,
        "publicTags": [],
        "state": "public",
        "actions": [{
            "value": '{"action": "manage"}',
            "key": action_key_b64
        }],
    }
    if True:
        prepared_cluster["privateKey"] = AESGCM(privkey_key).encrypt(
            nonce, priv_key_bytes, None)
        encSharedKey = pub_key.encrypt(
            config_shared_key,
            padding.OAEP(
                mgf=padding.MGF1(algorithm=chosen_hash),
                algorithm=chosen_hash,
                label=None,
            ),
        )
        prepared_cluster["nonce"] = nonce_b64
        prepared_cluster["privateTags"] = [
            "key={}".format(base64.b64encode(encSharedKey)),
        ]
    body, files = transform_payload(clusterCreateMutation_mutation,
                                    prepared_cluster)
    result = session.post(argv.url, data=body, files=files)
    result.raise_for_status()
    jsob = result.json()["data"]
    certhash = hash_algo.copy()
    certhash.update(pub_key_bytes)
    certhash = certhash.digest()
    certhash_b64 = base64.b64encode(certhash).decode("ascii")
    action_key_hash = hash_algo.copy()
    action_key_hash.update(action_key)
    action_key_hash = action_key_hash.digest()
    action_key_hash = base64.b64encode(action_key_hash).decode("ascii")
    # config format by standard client
    config = {
        "certificates": {
            certhash_b64: base64.b64encode(priv_key_bytes).decode("ascii")
        },
        "tokens": {
            action_key_hash: action_key_b64
        },
        "hosts": {
            argv.url: {
                "hashAlgorithms": hash_algos,
                "clusters": {
                    jsob["updateOrCreateCluster"]["cluster"]["id"]: {
                        "hashes": {
                            action_key_hash: ["manage", "view", "update"]
                        }
                    }
                },
            }
        },
        "baseUrl": argv.url,
        "configHashes": [certhash_b64, action_key_hash],
        "configCluster": jsob["updateOrCreateCluster"]["cluster"]["id"],
    }

    nonce = os.urandom(13)
    nonce_b64 = base64.b64encode(nonce).decode("ascii")

    encrypted_content = AESGCM(config_shared_key).encrypt(
        nonce,
        json.dumps(config).encode("utf8"), None)

    encrypted_content_hash_raw = hash_algo.copy()
    encrypted_content_hash_raw.update(encrypted_content)
    encrypted_content_hash_raw = encrypted_content_hash_raw.digest()
    signature = priv_key.sign(
        encrypted_content_hash_raw,
        padding.PSS(mgf=padding.MGF1(chosen_hash),
                    salt_length=padding.PSS.MAX_LENGTH),
        utils.Prehashed(chosen_hash),
    )

    config_key = pub_key.encrypt(
        config_shared_key,
        padding.OAEP(
            mgf=padding.MGF1(algorithm=chosen_hash),
            algorithm=chosen_hash,
            label=None,
        ),
    )

    config_hash = hash_algo.copy()
    config_hash.update(b"type=Config")
    config_hash = config_hash.digest()
    config_hash = base64.b64encode(config_hash).decode("ascii")
    tags = [
        "key_hash={}".format(action_key_hash),
        "key_hash={}".format(certhash_b64),
    ]
    prepared_content = {
        "cluster":
        config["configCluster"],
        "type":
        "Config",
        "state":
        "internal",
        "tags":
        tags,
        "references": [
            {
                "group": "key",
                "target": certhash_b64,
                "extra": base64.b64encode(config_key).decode("ascii"),
            },
            {
                "group": "signature",
                "target": certhash_b64,
                "extra": base64.b64encode(signature).decode("ascii"),
            },
        ],
        "value":
        encrypted_content,
        "nonce":
        nonce_b64,
        "contentHash":
        config_hash,
        "authorization": [":".join([config["configCluster"], action_key_b64])],
    }
    body, files = transform_payload(configCreateMutation_mutation,
                                    prepared_content)

    result = session.post(argv.url, data=body, files=files)
    result.raise_for_status()
    print(config)
Пример #5
0
def sign_secure_boot_v2(args):
    """ Sign a firmware app image with an RSA private key using RSA-PSS, write output file with a
    Secure Boot V2 header appended.
    """
    SECTOR_SIZE = 4096
    SIG_BLOCK_SIZE = 1216
    SIG_BLOCK_MAX_COUNT = 3

    signature_sector = b""
    key_count = len(args.keyfile)
    contents = args.datafile.read()

    if key_count > SIG_BLOCK_MAX_COUNT:
        print(
            "WARNING: Upto %d signing keys are supported for ESP32-S2. For ESP32-ECO3 only 1 signing key is supported",
            SIG_BLOCK_MAX_COUNT)

    if len(contents) % SECTOR_SIZE != 0:
        pad_by = SECTOR_SIZE - (len(contents) % SECTOR_SIZE)
        print(
            "Padding data contents by %d bytes so signature sector aligns at sector boundary"
            % pad_by)
        contents += b'\xff' * pad_by
    elif args.append_signatures:
        sig_block_num = 0

        while sig_block_num < SIG_BLOCK_MAX_COUNT:
            sig_block = validate_signature_block(contents, sig_block_num)
            if sig_block is None:
                break
            signature_sector += sig_block  # Signature sector is populated with already valid blocks
            sig_block_num += 1

        assert len(signature_sector) % SIG_BLOCK_SIZE == 0

        if sig_block_num == 0:
            print(
                "No valid signature blocks found. Discarding --append-signature and proceeding to sign the image afresh."
            )
        else:
            print(
                "%d valid signature block(s) already present in the signature sector."
                % sig_block_num)

            empty_signature_blocks = SIG_BLOCK_MAX_COUNT - sig_block_num
            if key_count > empty_signature_blocks:
                raise esptool.FatalError(
                    "Number of keys(%d) more than the empty signature blocks.(%d)"
                    % (key_count, empty_signature_blocks))

            contents = contents[:len(
                contents
            ) - SECTOR_SIZE]  # Signature stripped off the content (the legitimate blocks are included in signature_sector)

    print("%d signing key(s) found." % key_count)
    # Calculate digest of data file
    digest = hashlib.sha256()
    digest.update(contents)
    digest = digest.digest()

    for keyfile in args.keyfile:
        private_key = _load_sbv2_rsa_signing_key(keyfile.read())
        # Sign
        signature = private_key.sign(
            digest,
            padding.PSS(
                mgf=padding.MGF1(hashes.SHA256()),
                salt_length=32,
            ), utils.Prehashed(hashes.SHA256()))

        rsa_primitives = _get_sbv2_rsa_primitives(private_key.public_key())

        # Encode in signature block format
        #
        # Note: the [::-1] is to byte swap all of the bignum
        # values (signatures, coefficients) to little endian
        # for use with the RSA peripheral, rather than big endian
        # which is conventionally used for RSA.
        signature_block = struct.pack(
            "<BBxx32s384sI384sI384s",
            0xe7,  # magic byte
            0x02,  # version
            digest,
            int_to_bytes(rsa_primitives.n)[::-1],
            rsa_primitives.e,
            int_to_bytes(rsa_primitives.rinv)[::-1],
            rsa_primitives.m & 0xFFFFFFFF,
            signature[::-1])

        signature_block += struct.pack(
            "<I",
            zlib.crc32(signature_block) & 0xffffffff)
        signature_block += b'\x00' * 16  # padding

        assert len(signature_block) == SIG_BLOCK_SIZE
        signature_sector += signature_block

    assert len(signature_sector) > 0 and len(
        signature_sector
    ) <= SIG_BLOCK_SIZE * 3 and len(signature_sector) % SIG_BLOCK_SIZE == 0
    total_sig_blocks = len(signature_sector) // SIG_BLOCK_SIZE

    # Pad signature_sector to sector
    signature_sector = signature_sector + \
        (b'\xff' * (SECTOR_SIZE - len(signature_sector)))
    assert len(signature_sector) == SECTOR_SIZE

    # Write to output file, or append to existing file
    if args.output is None:
        args.datafile.close()
        args.output = args.datafile.name
    with open(args.output, "wb") as f:
        f.write(contents + signature_sector)
    print(
        "Signed %d bytes of data from %s. Signature sector now has %d signature blocks."
        % (len(contents), args.datafile.name, total_sig_blocks))
Пример #6
0
 def sign(self, payload):
     return self.key.sign(
         payload,
         padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                     salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256())
Пример #7
0

# ENCRYPTION
def encrypt(msg, PK):
    cipher_text = PK.encrypt(
        msg,
        padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
                     algorithm=hashes.SHA256(),
                     label=None))
    return cipher_text


# SIGNING
signature = alice_private_key.sign(
    message_bytes,
    padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256())

#data = (cipher_text, signature)

# Receiving PK_alice
with open("PK_alice.pem", "rb") as key_file:
    PK_alice = serialization.load_pem_public_key(key_file.read(),
                                                 backend=default_backend())

# Verifying
try:
    PK_alice.verify(
        signature, message_bytes,
        padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                    salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256())
Пример #8
0
    def data_received(self, buffer):
        logger.debug("{} POOP recv a buffer of size {}".format(self._mode, len(buffer)))
        self.deserializer.update(buffer)
        for pkt in self.deserializer.nextPackets():
            if pkt.DEFINITION_IDENTIFIER == "crap.handshakepacket":
                if self._mode == "server":
                    if pkt.status == 0:
                        certification = x509.load_pem_x509_certificate(pkt.cert, default_backend())
                        self.cert_pubkA = certification.public_key()
                        print("222222222222222222222")
                        try:
                            self.cert_pubkA.verify(pkt.signature, pkt.pk,
                                                 padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                                                             salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256())

                        except Exception as error:
                            logger.debug("Server verify cert fail!")
                            tls_handshake_packet = HandshakePacket(status=2)
                            self.transport.write(tls_handshake_packet.__serialize__())
                            self.transport.close()

                        logger.debug("Server verify cert success!")
                        self.server_private_key = ec.generate_private_key(ec.SECP384R1(), default_backend())
                        self.server_public_key = self.server_private_key.public_key()
                        self.server_sign_pvk = rsa.generate_private_key(public_exponent=65537, key_size=2048,
                                                                        backend=default_backend())
                        self.server_sign_pbk = self.server_sign_pvk.public_key()
                        self.snonce = randrange(255)
                        self.serialized_snonce = str(self.snonce).encode('ASCII')
                        self.serialized_cnonce = str(pkt.nonce).encode('ASCII')
                        print("55555555555555555555555555")
                        data = self.server_public_key.public_bytes(Encoding.PEM, PublicFormat.SubjectPublicKeyInfo)
                        sigB = self.server_sign_pvk.sign(data,padding.PSS(mgf=padding.MGF1(hashes.SHA256()),salt_length=padding.PSS.MAX_LENGTH),hashes.SHA256())
                        print("777777777777777777777777")
                        tls_handshake_packet = HandshakePacket(status=1)
                        tls_handshake_packet.pk = data
                        tls_handshake_packet.signature = sigB
                        tls_handshake_packet.nonce = self.snonce
                        print("666666666666666666666666666666666666")
                        builder = x509.CertificateBuilder()
                        builder = builder.subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, u'team5_server'), ]))
                        builder = builder.issuer_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, u'team5_server'), ]))
                        builder = builder.not_valid_before(datetime.datetime.today() - datetime.timedelta(days=30))
                        builder = builder.not_valid_after(datetime.datetime.today() + datetime.timedelta(days=30))
                        builder = builder.serial_number(x509.random_serial_number())
                        builder = builder.public_key(self.server_sign_pbk)
                        certificate = builder.sign(private_key=self.server_sign_pvk, algorithm=hashes.SHA256(),
                                                   backend=default_backend())
                        server_cert = certificate.public_bytes(Encoding.PEM)
                        tls_handshake_packet.cert = server_cert
                        cnonceSignature = self.server_sign_pvk.sign(self.serialized_cnonce,
                                                           padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                                                                       salt_length=padding.PSS.MAX_LENGTH),
                                                           hashes.SHA256())
                        print("1231313131313131")
                        tls_handshake_packet.nonceSignature = cnonceSignature
                        self.transport.write(tls_handshake_packet.__serialize__())
                        logger.debug("Client send TLS handshake!")

                    elif pkt.status == 1:
                        try:
                            self.cert_pubkA.verify(packet.nonceSignature, self.serialized_snonce,
                                                      padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                                                                  salt_length=padding.PSS.MAX_LENGTH),
                                                      hashes.SHA256())

                        except Exception as error:
                            logger.debug("Server verify failed because wrong signature")
                            tls_handshake_packet = HandshakePacket(status=2)
                            self.transport.write(tls_handshake_packet.__serialize__())
                            self.transport.close()
                        print("TLS Handshake complete")



                elif self._mode == "client" and pkt.status == 1:
                    certification = x509.load_pem_x509_certificate(pkt.cert, default_backend())
                    self.cert_pubkB = certification.public_key()
                    try:
                        self.cert_pubkB.verify(pkt.signature, pkt.pk,
                                             padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                                                         salt_length=padding.PSS.MAX_LENGTH),
                                             hashes.SHA256())
                        self.cert_pubkB.verify(pkt.nonceSignature, self.serialized_cnonce,
                                             padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                                                         salt_length=padding.PSS.MAX_LENGTH),
                                             hashes.SHA256())

                    except Exception as error:
                        logger.debug("client verify failed because wrong signature")
                        tls_handshake_packet = HandshakePacket(status=2)
                        self.transport.write(tls_handshake_packet.__serialize__())
                        self.transport.close()

                    # Generate shared key
                    # pubkA_recv = load_pem_public_key(packet.pk, backend=default_backend())
                    # client_shared_key = privkB.exchange(ec.ECDH, pubkA_recv)

                    # Reveive nonceB
                    self.serialized_snonce = str(pkt.nonce).encode('ASCII')

                    snonceSignature = self.client_sign_pvk.sign(self.serialized_snonce,
                                                       padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                                                                   salt_length=padding.PSS.MAX_LENGTH),
                                                       hashes.SHA256())

                    tls_handshake_packet = HandshakePacket(status=1, nonceSignature=snonceSignature)
                    self.transport.write(tls_handshake_packet.__serialize__())
Пример #9
0
def sign(datau,
         key,
         cert,
         othercerts,
         hashalgo,
         attrs=True,
         signed_value=None,
         hsm=None,
         pss=False,
         timestampurl=None,
         timestampcredentials=None,
         timestamp_req_options=None):
    if signed_value is None:
        signed_value = getattr(hashlib, hashalgo)(datau).digest()
    signed_time = datetime.now(tz=util.timezone.utc)

    if hsm is not None:
        keyid, cert = hsm.certificate()
        cert = cert2asn(cert, False)
    else:
        cert = cert2asn(cert)

    certificates = []
    certificates.append(cert)
    for i in range(len(othercerts)):
        certificates.append(cert2asn(othercerts[i]))

    hashalgo = unicode(hashalgo) if sys.version[0] < '3' else hashalgo

    signer = {
        'version':
        'v1',
        'sid':
        cms.SignerIdentifier({
            'issuer_and_serial_number':
            cms.IssuerAndSerialNumber({
                'issuer': cert.issuer,
                'serial_number': cert.serial_number,
            }),
        }),
        'digest_algorithm':
        algos.DigestAlgorithm({'algorithm': hashalgo}),
        'signature':
        signed_value,
    }
    if not pss:
        signer['signature_algorithm'] = algos.SignedDigestAlgorithm(
            {'algorithm': 'rsassa_pkcs1v15'})
    else:
        if isinstance(key, keys.PrivateKeyInfo):
            salt_length = key.byte_size - hashes.SHA512.digest_size - 2
            salt_length = hashes.SHA512.digest_size
        else:
            salt_length = padding.calculate_max_pss_salt_length(
                key, hashes.SHA512)
        signer['signature_algorithm'] = algos.SignedDigestAlgorithm({
            'algorithm':
            'rsassa_pss',
            'parameters':
            algos.RSASSAPSSParams({
                'hash_algorithm':
                algos.DigestAlgorithm({'algorithm': 'sha512'}),
                'mask_gen_algorithm':
                algos.MaskGenAlgorithm({
                    'algorithm':
                    algos.MaskGenAlgorithmId('mgf1'),
                    'parameters': {
                        'algorithm': algos.DigestAlgorithmId('sha512'),
                    }
                }),
                'salt_length':
                algos.Integer(salt_length),
                'trailer_field':
                algos.TrailerField(1)
            })
        })

    if attrs:
        if attrs is True:
            signer['signed_attrs'] = [
                cms.CMSAttribute({
                    'type': cms.CMSAttributeType('content_type'),
                    'values': ('data', ),
                }),
                cms.CMSAttribute({
                    'type': cms.CMSAttributeType('message_digest'),
                    'values': (signed_value, ),
                }),
                cms.CMSAttribute({
                    'type':
                    cms.CMSAttributeType('signing_time'),
                    'values':
                    (cms.Time({'utc_time': core.UTCTime(signed_time)}), )
                }),
            ]
        else:
            signer['signed_attrs'] = attrs

    config = {
        'version':
        'v1',
        'digest_algorithms':
        cms.DigestAlgorithms((algos.DigestAlgorithm({'algorithm':
                                                     hashalgo}), )),
        'encap_content_info': {
            'content_type': 'data',
        },
        'certificates':
        certificates,
        # 'crls': [],
        'signer_infos': [
            signer,
        ],
    }
    datas = cms.ContentInfo({
        'content_type': cms.ContentType('signed_data'),
        'content': cms.SignedData(config),
    })
    if attrs:
        tosign = datas['content']['signer_infos'][0]['signed_attrs'].dump()
        tosign = b'\x31' + tosign[1:]
    else:
        tosign = datau
    if hsm is not None:
        signed_value_signature = hsm.sign(keyid, tosign, hashalgo)
    elif isinstance(key, keys.PrivateKeyInfo):
        key = asymmetric.load_private_key(key)
        if pss:
            signed_value_signature = asymmetric.rsa_pss_sign(
                key, tosign, 'sha512')
        else:
            signed_value_signature = asymmetric.rsa_pkcs1v15_sign(
                key, tosign, hashalgo.lower())
    else:
        if pss:
            hasher = hashes.Hash(hashes.SHA512(),
                                 backend=backends.default_backend())
            hasher.update(tosign)
            digest = hasher.finalize()
            signed_value_signature = key.sign(
                digest,
                padding.PSS(mgf=padding.MGF1(hashes.SHA512()),
                            salt_length=salt_length),
                utils.Prehashed(hashes.SHA512()))
        else:
            signed_value_signature = key.sign(
                tosign, padding.PKCS1v15(),
                getattr(hashes, hashalgo.upper())())

    if timestampurl is not None:
        datas['content']['signer_infos'][0]['unsigned_attrs'] = timestamp(
            signed_value_signature,
            hashalgo,
            timestampurl,
            timestampcredentials,
            timestamp_req_options,
        )

    # signed_value_signature = core.OctetString(signed_value_signature)
    datas['content']['signer_infos'][0]['signature'] = signed_value_signature

    #open('signed-content-info', 'wb').write(datas.dump())
    return datas.dump()
Пример #10
0
def sign(message, private):
    sig = private.sign(
        message,
        padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                    salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256())
    return sig
Пример #11
0
    def data_received(self, data):
        logger.debug("CRAP: {} side received a data of size {} from {}".format(self.mode, len(data), self.transport.get_extra_info("peername")))
        self.deserializer.update(data)
        if self.handshakeComplete:
            for packet in self.deserializer.nextPackets():
                if isinstance(packet, DataPacket):
                    logger.debug('CRAP: {} side received data packet. Info:\n'
                                 'data: {}\n'.format(self.mode, packet.data))

                    logger.debug('CRAP: {} side decrypting data.\n'.format(self.mode))
                    aes_gcm = AESGCM(self.higher_transport.dec_key)
                    decrypted_data = aes_gcm.decrypt(self.higher_transport.other_side_IV, packet.data, None)
                    logger.debug('CRAP: {} side decrypted data is: {}\n'.format(self.mode, decrypted_data))

                    logger.debug(
                        'CRAP: {} side incrementing other_side_IV by one from {} to {}'.format(self.mode, self.higher_transport.other_side_IV,
                                                                                         increment_large_binary(
                                                                                             self.higher_transport.other_side_IV)))
                    self.higher_transport.other_side_IV = increment_large_binary(self.higher_transport.other_side_IV)

                    logger.debug('CRAP: {} sending decrypted data to higher protocol, data: {}\n'.format(self.mode, decrypted_data))
                    self.higherProtocol().data_received(decrypted_data)

                elif isinstance(packet, ErrorPacket):
                    logger.debug('CRAP: {} side received error packet. Info:\n'
                                 'data: {}\n'.format(self.mode, packet.message))

                else:
                    logger.debug('CRAP: {} side expected data/error got something else: ignore'.format(self.mode))


        else:
            # handshake
            for packet in self.deserializer.nextPackets():
                if isinstance(packet, HandshakePacket):
                    logger.debug('CRAP: {} side received handshake packet. Info:\n'
                                 'status: {}\n'
                                 'pk: {}\n'
                                 'signature: {}\n'
                                 'cert: {}\n'
                                 'nonce: {}\n'
                                 'nonce_signature: {}\n'
                                 'cert chain: {}\n'.format(self.mode, packet.status, packet.pk, packet.signature, packet.cert, packet.nonce, packet.nonceSignature, packet.certChain))
                    if packet.status == HandshakePacket.NOT_STARTED:
                        try:
                            cert = deserialize_cert(packet.cert)
                            logger.debug('CRAP: {} side verifying certificate common_name!\n'.format(self.mode))
                            self.verify_common_name(cert)
                            logger.debug('CRAP: {} side certificate common name verified!\n'.format(self.mode))

                            logger.debug('CRAP: {} side verifying certificate chain of trust!\n'.format(self.mode))
                            self.verify_chain_of_trust(cert, packet.certChain)
                            logger.debug('CRAP: {} side chain of trust verified!\n'.format(self.mode))

                            logger.debug('CRAP: {} side verifying signature received from other side!\n'.format(self.mode))
                            verification_key = cert.public_key()
                            self.verification_key = verification_key
                            verification_key.verify(packet.signature, packet.pk, padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                                                              salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256())
                            logger.debug('CRAP: {} side signature verified!\n'.format(self.mode))

                            logger.debug('CRAP: {} side creating shared key\n'.format(self.mode))
                            self.shared_key = self.private_key.exchange(ec.ECDH(), deserialize_public(packet.pk))

                            logger.debug('CRAP: {} side signing the sent nonce with signature key\n'.format(self.mode))
                            nonce_bytes = str(packet.nonce).encode()
                            nonce_signature = self.signing_key.sign(nonce_bytes, padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                                                              salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256())

                            logger.debug('CRAP: {} side creating signature\n'.format(self.mode))
                            signature = self.signing_key.sign(self.public_key_bytes, padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                                                              salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256())

                            with open('team1csr_signed.cert', 'rb') as f:
                                signer_cert_bytes = f.read()

                            cert_chain = [signer_cert_bytes]

                            packet = HandshakePacket(status=HandshakePacket.SUCCESS, pk=self.public_key_bytes, signature=signature, cert=self.cert_bytes, nonce=self.nonce, nonceSignature=nonce_signature, certChain=cert_chain)
                            packet_bytes = packet.__serialize__()
                            logger.debug('CRAP: {} side sending handshake packet. Info:\n'
                                         'status: {}\n'
                                         'pk: {}\n'
                                         'signature: {}\n'
                                         'cert: {}\n'
                                         'nonce: {}\n'
                                         'nonce_signature: {}\n'
                                         'cert chain: {}'.format(self.mode, packet.status, packet.pk, packet.signature, packet.cert, packet.nonce, packet.nonceSignature, packet.certChain))
                            self.transport.write(packet_bytes)
                        except:
                            error = 'Verification failed!'
                            logger.debug('CRAP: {} side encountered error: {}\n'.format(self.mode, error))
                            self.handle_handshake_error()
                            packet = HandshakePacket(status=HandshakePacket.ERROR)
                            packet_bytes = packet.__serialize__()
                            logger.debug('CRAP: {} side sending handshake packet. Info:\n'
                                         'status: {}\n'
                                         'pk: {}\n'
                                         'signature: {}\n'
                                         'cert: {}\n'
                                         'nonce: {}\n'
                                         'nonce_signature: {}\n'
                                         'cert chain: {}\n'.format(self.mode, packet.status, packet.pk, packet.signature,
                                                             packet.cert, packet.nonce, packet.nonceSignature, packet.certChain))
                            self.transport.write(packet_bytes)

                            self.connection_lost()

                    elif packet.status == HandshakePacket.SUCCESS:
                        if not_set(packet.pk, packet.nonce, packet.signature) and is_set(packet.nonceSignature):
                            try:

                                if is_set(packet.cert):
                                    cert = deserialize_cert(packet.cert)
                                    verification_key = cert.public_key()
                                else:
                                    verification_key = self.verification_key
                                logger.debug('CRAP: {} side verifying nonce signature received from other side!\n'.format(self.mode))
                                verification_key.verify(packet.nonceSignature, self.nonce_bytes,
                                                        padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                                                                    salt_length=padding.PSS.MAX_LENGTH),
                                                        hashes.SHA256())
                                logger.debug('CRAP: {} side nonce signature verified!\n'.format(self.mode))
                                self.handshakeComplete = True
                                logger.debug(
                                    'CRAP: {} set handshakeComplete to True'.format(self.mode))
                                higher_transport = CrapTransport(self.transport, mode=self.mode, protocol=self)
                                higher_transport.assign_gcm_values()
                                self.higher_transport = higher_transport
                                logger.debug('Crap: {} side calling self.higherProtocol().connection_made()'.format(self.mode))
                                self.higherProtocol().connection_made(higher_transport)
                            except:
                                logger.debug(
                                    'CRAP: {} verifying nonce failed'.format(self.mode))
                                self.connection_lost()
                        elif is_set(packet.pk, packet.cert, packet.signature, packet.nonce, packet.nonceSignature):
                            try:
                                cert = deserialize_cert(packet.cert)
                                logger.debug('CRAP: {} side verifying certificate common_name!\n'.format(self.mode))
                                self.verify_common_name(cert)
                                logger.debug('CRAP: {} side certificate common name verified!\n'.format(self.mode))

                                logger.debug('CRAP: {} side verifying certificate chain of trust!\n'.format(self.mode))
                                self.verify_chain_of_trust(cert, packet.certChain)
                                logger.debug('CRAP: {} side chain of trust verified!\n'.format(self.mode))

                                logger.debug('CRAP: {} side verifying signature received from other side!\n'.format(self.mode))
                                verification_key = cert.public_key()
                                verification_key.verify(packet.signature, packet.pk,
                                                        padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                                                                    salt_length=padding.PSS.MAX_LENGTH),
                                                        hashes.SHA256())
                                logger.debug('CRAP: {} side signature verified!\n'.format(self.mode))

                                logger.debug('CRAP: {} side verifying nonce signature received from other side!\n'.format(self.mode))
                                verification_key.verify(packet.nonceSignature, self.nonce_bytes,
                                                        padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                                                                    salt_length=padding.PSS.MAX_LENGTH),
                                                        hashes.SHA256())
                                logger.debug('CRAP: {} side nonce signature verified!\n'.format(self.mode))

                                logger.debug('CRAP: {} side creating shared key\n'.format(self.mode))
                                self.shared_key = self.private_key.exchange(ec.ECDH(), deserialize_public(packet.pk))

                                logger.debug(
                                    'CRAP: {} side signing the sent nonce with signature key\n'.format(self.mode))
                                nonce_bytes = str(packet.nonce).encode()
                                nonce_signature = self.signing_key.sign(nonce_bytes, padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                                                              salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256())

                                self.handshakeComplete = True
                                logger.debug(
                                    'CRAP: {} set handshakeComplete to True'.format(self.mode))

                                packet = HandshakePacket(status=HandshakePacket.SUCCESS, nonceSignature=nonce_signature,
                                                         cert=self.cert_bytes)
                                packet_bytes = packet.__serialize__()
                                logger.debug('CRAP: {} side sending handshake packet. Info:\n'
                                             'status: {}\n'
                                             'pk: {}\n'
                                             'signature: {}\n'
                                             'cert: {}\n'
                                             'nonce: {}\n'
                                             'nonce_signature: {}\n'
                                             'cert chain: {}'.format(self.mode, packet.status, packet.pk,
                                                                     packet.signature, packet.cert, packet.nonce,
                                                                     packet.nonceSignature, packet.certChain))

                                self.transport.write(packet_bytes)

                                higher_transport = CrapTransport(self.transport, mode=self.mode, protocol=self)
                                higher_transport.assign_gcm_values()
                                self.higher_transport = higher_transport
                                logger.debug(
                                    'Crap: {} side calling self.higherProtocol().connection_made()'.format(self.mode))
                                self.higherProtocol().connection_made(higher_transport)



                            except:
                                error = 'Verification failed!'
                                logger.debug('CRAP: {} side encountered error: {}\n'.format(self.mode, error))
                                self.handle_handshake_error()
                                packet = HandshakePacket(status=HandshakePacket.ERROR)
                                packet_bytes = packet.__serialize__()
                                logger.debug('CRAP: {} side sending handshake packet. Info:\n'
                                             'status: {}\n'
                                             'pk: {}\n'
                                             'signature: {}\n'
                                             'cert: {}\n'
                                             'nonce: {}\n'
                                             'nonce_signature: {}\n'
                                             'cert chain: {}'.format(self.mode, packet.status, packet.pk, packet.signature, packet.cert, packet.nonce, packet.nonceSignature, packet.certChain))
                                self.transport.write(packet_bytes)

                                self.connection_lost()
                        else:
                            error = 'handshake fields does not match!'
                            logger.debug('CRAP: {} side encountered error: {}\n'.format(self.mode, error))
                            self.handle_handshake_error()

                            self.connection_lost()
                    elif packet.status == HandshakePacket.ERROR:
                        # Error detected on the other side
                        error = 'an error reported from the other side'
                        logger.debug('CRAP: {} side encountered error: {}\n'.format(self.mode, error))
                        self.handle_handshake_error()

                        self.connection_lost()
                    else:
                        self.handle_handshake_error()

                        self.connection_lost()

                elif isinstance(packet, ErrorPacket):
                    logger.debug('CRAP: {} side received error packet. Info:\n'
                                 'data: {}\n'.format(self.mode, packet.message))

                else:
                    error = 'Expected handshake/error packet and got s.th else!'
                    logger.debug('CRAP: {} side encountered error: {}\n'.format(self.mode, error))
                    self.handle_handshake_error()
Пример #12
0
    def __init__(self, params: Dict[int, Any]):
        super().__init__(params)

        self._key: Any = None
        self._hash: Any = None
        self._padding: Any = None
        salt_len: Any = padding.PSS.MAX_LENGTH

        # Validate kty.
        if params[1] != 3:
            raise ValueError("kty(1) should be RSA(3).")

        # Validate alg.
        if 3 not in params:
            raise ValueError("alg(3) not found.")
        if params[3] not in COSE_ALGORITHMS_RSA.values():
            raise ValueError(
                f"Unsupported or unknown alg(3) for RSA: {params[3]}.")
        if params[3] == -259 or params[3] == -39:
            self._hash = hashes.SHA512
            salt_len = 64
        elif params[3] == -258 or params[3] == -38:
            self._hash = hashes.SHA384
            salt_len = 48
        elif params[3] == -257 or params[3] == -37:
            self._hash = hashes.SHA256
            salt_len = 32
        else:
            raise ValueError(
                f"Unsupported or unknown alg(3) for RSA: {params[3]}.")
        if params[3] in [-37, -38, -39]:
            self._padding = padding.PSS(mgf=padding.MGF1(self._hash()),
                                        salt_length=salt_len)
        else:
            self._padding = padding.PKCS1v15()

        # Validate key_ops.
        if -3 not in params:  # the RSA private exponent d.
            if not self._key_ops:
                self._key_ops = RSAKey._ACCEPTABLE_PUBLIC_KEY_OPS
            else:
                prohibited = [
                    ops for ops in self._key_ops
                    if ops not in RSAKey._ACCEPTABLE_PUBLIC_KEY_OPS
                ]
                if prohibited:
                    raise ValueError(
                        f"Unknown or not permissible key_ops(4) for RSAKey: {prohibited[0]}."
                    )
        else:
            if not self._key_ops:
                self._key_ops = RSAKey._ACCEPTABLE_PRIVATE_KEY_OPS
            else:
                prohibited = [
                    ops for ops in self._key_ops
                    if ops not in RSAKey._ACCEPTABLE_PRIVATE_KEY_OPS
                ]
                if prohibited:
                    raise ValueError(
                        f"Unknown or not permissible key_ops(4) for RSAKey: {prohibited[0]}."
                    )

        # Validate RSA specific parameters.
        if -1 not in params or not isinstance(params[-1], bytes):
            raise ValueError("n(-1) should be set as bytes.")
        if -2 not in params or not isinstance(params[-2], bytes):
            raise ValueError("e(-2) should be set as bytes.")

        public_numbers = RSAPublicNumbers(
            n=int.from_bytes(params[-1], "big"),
            e=int.from_bytes(params[-2], "big"),
        )
        self._dict = params
        if -3 not in params:  # the RSA private exponent d.
            private_props = [
                p for p in params.keys() if p in [-4, -5, -6, -7, -8]
            ]
            if private_props:
                raise ValueError(
                    f"RSA public key should not have private parameter: {private_props[0]}."
                )
            self._key = public_numbers.public_key()
            return

        if -3 not in params or not isinstance(params[-3], bytes):
            raise ValueError("d(-3) should be set as bytes.")
        if -4 not in params or not isinstance(params[-4], bytes):
            raise ValueError("p(-4) should be set as bytes.")
        if -5 not in params or not isinstance(params[-5], bytes):
            raise ValueError("q(-5) should be set as bytes.")
        if -6 not in params or not isinstance(params[-6], bytes):
            raise ValueError("dP(-6) should be set as bytes.")
        if -7 not in params or not isinstance(params[-7], bytes):
            raise ValueError("dQ(-7) should be set as bytes.")
        if -8 not in params or not isinstance(params[-8], bytes):
            raise ValueError("qInv(-8) should be set as bytes.")

        private_numbers = RSAPrivateNumbers(
            d=int.from_bytes(params[-3], "big"),
            p=int.from_bytes(params[-4], "big"),
            q=int.from_bytes(params[-5], "big"),
            dmp1=int.from_bytes(params[-6], "big"),
            dmq1=int.from_bytes(params[-7], "big"),
            iqmp=int.from_bytes(params[-8], "big"),
            public_numbers=public_numbers,
        )
        self._key = private_numbers.private_key()
        return
Пример #13
0
def encrypt():

    destination_public_key_filename_opener = open(sys.argv[2])
    destination_public_key_filename = destination_public_key_filename_opener.read(
    )
    destination_public_key_filename_opener.close()

    sender_private_key_filename_opener = open(sys.argv[3])
    sender_private_key_filename = sender_private_key_filename_opener.read()
    sender_private_key_filename_opener.close()

    input_plaintext_file_opener = open(sys.argv[4])
    input_plaintext = input_plaintext_file_opener.read()
    print input_plaintext
    input_plaintext_file_opener.close()

    # open ciphertext_file, write and close later here later
    ciphertext_file = open(sys.argv[5], 'wb')

    # generating a random 128 bit key for symmetric encryption(AES)
    key = os.urandom(16)  # in bytes, 128 bits
    iv = os.urandom(16)
    print "key : ", base64.b64encode(key)
    print "iv : ", base64.b64encode(iv)

    # RSA/Asymmetric encryption of AES key here:

    # I am just writing this step for knowledge, we are going to use openssl
    # for generation of keys

    # Generate a 2048 bit private key

    # private_key = rsa.generate_private_key(
    # public_exponent=65537,
    # key_size=2048,
    # backend=default_backend())
    # # to get the public key
    # public_key = private_key.public_key()

    # getting public_key form  destination_public_key_filename
    public_key = serialization.load_der_public_key(
        destination_public_key_filename, backend=default_backend())
    # some problem here, changed hashes.SHA1 to hashes.SHA256
    # ask professor
    # encoding key and iv both to send over via RSA
    message = key + iv
    print "len of message : ", len(message)
    print base64.b64encode(message)
    ciphertext_key = public_key.encrypt(
        message,
        padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA1()),
                     algorithm=hashes.SHA1(),
                     label=None))

    print len(ciphertext_key)
    print base64.b64encode(ciphertext_key)
    ciphertext_file.write(ciphertext_key)

    # signing using sender_private_key_filename
    # # get private key
    with open(sys.argv[3], "rb") as key_file:
        private_key = serialization.load_pem_private_key(
            key_file.read(), password=None, backend=default_backend())
    public_key = private_key.public_key()

    signer = private_key.signer(
        padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                    salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256())

    signer.update(ciphertext_key)
    signature = signer.finalize()
    print "signature : "
    print len(signature)
    print base64.b64encode(signature)

    ciphertext_file.write(signature)

    # AES encryption of data here :

    #  trying CTR mode since it does not require padding, less complications

    # CTR Mode, we don't need padding in CTR mode. In transforms a block cipher into a stream cipher
    # we only need to introduce the nonce
    cipher = Cipher(algorithms.AES(key),
                    modes.CTR(iv),
                    backend=default_backend())
    encryptor = cipher.encryptor()
    # len("Network Security CS 6740") = 25, but no padding is needed
    # cipher_text = encryptor.update("Network Security CS(6740)") + encryptor.finalize()
    cipher_text = encryptor.update(input_plaintext) + encryptor.finalize()
    ciphertext_file.write(cipher_text)
    ciphertext_file.close()

    print cipher_text
    print len(cipher_text)
    print base64.b64encode(cipher_text)
    print "finished AES encryption"
Пример #14
0
def decrypt():

    destination_private_key_opener = open(sys.argv[2])
    destination_private_key_filename = destination_private_key_opener.read()
    destination_private_key_opener.close()

    sender_public_key_opener = open(sys.argv[3])
    sender_public_key_filename = sender_public_key_opener.read()
    sender_public_key_opener.close()

    ciphertext_file_opener = open(sys.argv[4])
    ciphertext_file = ciphertext_file_opener.read()
    ciphertext_file_opener.close()

    output_file_opener = open(sys.argv[5], 'w')

    # print "content : "
    # print len(ciphertext_file)
    # print base64.b64encode(ciphertext_file)
    # # verify signature here :
    message = ciphertext_file[:256]
    print "key: "
    print base64.b64encode(message)
    print "signature : "
    signature = ciphertext_file[256:512]
    print base64.b64encode(signature)

    # getting public_key form  sender_public_key_filename
    # used to verify signatures
    public_key = serialization.load_der_public_key(sender_public_key_filename,
                                                   backend=default_backend())

    verifier = public_key.verifier(
        signature,
        padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                    salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256())
    verifier.update(message)
    # raises an exception if signature is invalid, none otherwise,
    # have to confirm the none part
    verifier.verify()

    # decrypt the AES key using private key of the destination

    # get private key
    with open(sys.argv[2], "rb") as key_file:
        private_key = serialization.load_pem_private_key(
            key_file.read(), password=None, backend=default_backend())
    public_key = private_key.public_key()

    # decrypt AES key here :
    ciphertext = message
    key_iv = private_key.decrypt(
        ciphertext,
        padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA1()),
                     algorithm=hashes.SHA1(),
                     label=None))
    print len(key_iv)
    print base64.b64encode(key_iv)
    aes_key = key_iv[:16]
    iv = key_iv[16:]

    cipher = Cipher(algorithms.AES(aes_key),
                    modes.CTR(iv),
                    backend=default_backend())
    cipher_text2 = ciphertext_file[512:]
    decryptor = cipher.decryptor()
    plain_text = decryptor.update(cipher_text2) + decryptor.finalize()
    print plain_text
    output_file_opener.write(plain_text)
    output_file_opener.close()
Пример #15
0
def sign_message(message, private_key):
    print("Signing message")
    return private_key.sign(
        message,
        padding.PSS(mgf=padding.MGF1(hashes.SHA256),
                    salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256)
Пример #16
0
    def crap_handshake_recv(self, packet):
        print("shoudaole!!!!!!!!!!!!")
        if self.mode == "server":
            if packet.status == 0:
                try:
                    packet.cert.verify(
                        packet.signature, self.dataA,
                        padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                                    salt_length=padding.PSS.MAX_LENGTH),
                        hashes.SHA256())
                except Exception as error:
                    logger.debug("Sever verify failed because wrong signature")
                    new_secure_packet = HandshakePacket(status=2)
                    self.transport.write(new_secure_packet.__serialize__())
                    self.transport.close()

                privkB = ec.generate_private_key(ec.SECP384R1(),
                                                 default_backend())
                pubkB = privkB.public_key()

                publickeyB = load_pem_private_key(packet.pk,
                                                  password=None,
                                                  backend=default_backend())
                server_shared_key = privkB.exchange(ec.ECDH, publickeyB)

                signkB = rsa.generate_private_key(public_exponent=65537,
                                                  key_size=2048,
                                                  backend=default_backend())
                pubk_sigB = signkB.public_key()

                tmp_pubk_sigB = pubk_sigB.public_bytes(
                    Encoding.PEM, PublicFormat.SubjectPublicKeyInfo)
                certB = tmp_pubk_sigB

                tmpB = pubkB.public_bytes(Encoding.PEM,
                                          PublicFormat.SubjectPublicKeyInfo)
                self.dataB = tmpB

                sigB = signkB.sign(
                    self.dataB,
                    padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                                salt_length=padding.PSS.MAX_LENGTH),
                    hashes.SHA256())

                nonceSignatureB = signkB.sign(
                    packet.nonce,
                    padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                                salt_length=padding.PSS.MAX_LENGTH),
                    hashes.SHA256())

                tmp_nonceB = 4
                nonceB = bytes(tmp_nonceB)

                new_secure_packet = HandshakePacket(
                    status=1,
                    pk=self.dataB,
                    signature=sigB,
                    nonce=tmp_nonceB,
                    nonceSignature=nonceSignatureB,
                    cert=certB)

                self.transport.write(new_secure_packet.__serialize__())

            elif packet.status == 1:
                try:
                    self.pubk_sigA.verify(
                        packet.nonceSignature, self.nonceA,
                        padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                                    salt_length=padding.PSS.MAX_LENGTH),
                        hashes.SHA256())

                except Exception as error:
                    logger.debug("Sever verify failed because wrong signature")
                    new_secure_packet = HandshakePacket(status=2)
                    self.transport.write(new_secure_packet.__serialize__())
                    self.transport.close()
                print("Handshake complete")

        if self.mode == "client" and packet.status == 1:
            try:
                packet.cert.verify(
                    packet.signature, self.dataB,
                    padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                                salt_length=padding.PSS.MAX_LENGTH),
                    hashes.SHA256())
                packet.cert.verify(
                    packet.nonceSignature, self.nonceA,
                    padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                                salt_length=padding.PSS.MAX_LENGTH),
                    hashes.SHA256())

            except Exception as error:
                logger.debug("Sever verify failed because wrong signature")
                new_secure_packet = HandshakePacket(status=2)
                self.transport.write(new_secure_packet.__serialize__())
                self.transport.close()

            publickeyA = load_pem_private_key(packet.pk,
                                              password=None,
                                              backend=default_backend())
            client_shared_key = self.privkA.exchange(ec.ECDH, publickeyA)

            nonceSignatureA = self.signkA.sign(
                packet.nonce,
                padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                            salt_length=padding.PSS.MAX_LENGTH),
                hashes.SHA256())

            new_secure_packet = HandshakePacket(status=1,
                                                nonceSignature=nonceSignatureA)
            self.transport.write(new_secure_packet.__serialize__())
Пример #17
0
def verify_message(message, signature, public_key):
    print("Verifying message")
    public_key.verify(
        signature, message,
        padding.PSS(mgf=padding.MGF1(hashes.SHA256),
                    salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256)
Пример #18
0
    def connection_made(self, transport):
        logger.debug("{} Crap: connection made".format(self.mode))
        self.transport = transport
        logger.debug("sadasdasdassssssss________________________---")

        if self.mode == "client":
            # Create long term key
            self.privkA = ec.generate_private_key(ec.SECP384R1(),
                                                  default_backend())
            pubkA = self.privkA.public_key()

            # Create pk in packet (serialization)
            tmp_pubkA = pubkA.public_bytes(Encoding.PEM,
                                           PublicFormat.SubjectPublicKeyInfo)
            self.dataA = tmp_pubkA

            # Create ephemeral key for signing
            self.signkA = rsa.generate_private_key(public_exponent=65537,
                                                   key_size=2048,
                                                   backend=default_backend())
            self.pubk_sigA = self.signkA.public_key()

            # Create signature
            sigA = self.signkA.sign(
                self.dataA,
                padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                            salt_length=padding.PSS.MAX_LENGTH),
                hashes.SHA256())

            # Create nonceA
            tmp_nonceA = 1
            self.nonceA = tmp_nonceA

            # Create certificate with the help of ephemeral private key
            subject = issuer = x509.Name([
                x509.NameAttribute(NameOID.COUNTRY_NAME, u"US"),
                x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME,
                                   u"Baltimore"),
                # x509.NameAttribute(NameOID.LOCALITY_NAME, u"San Francisco"),
                x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"JHU"),
                x509.NameAttribute(NameOID.COMMON_NAME,
                                   u"20194networksecurity.com"),
            ])
            builder = x509.CertificateBuilder()
            builder = builder.subject_name(subject)
            builder = builder.issuer_name(issuer)
            builder = builder.public_key(self.pubk_sigA)
            builder = builder.serial_number(x509.random_serial_number())
            builder = builder.not_valid_before(datetime.datetime.utcnow())
            builder = builder.not_valid_after(datetime.datetime.utcnow() +
                                              datetime.timedelta(days=30))
            certificate = builder.sign(private_key=self.signkA,
                                       algorithm=hashes.SHA256(),
                                       backend=default_backend())
            # Create CertA to transmit (serialization)
            certA = certificate.public_bytes(Encoding.PEM)
            print(certA)

            new_secure_packet = HandshakePacket(status=0,
                                                pk=self.dataA,
                                                signature=sigA,
                                                nonce=self.nonceA,
                                                cert=certA)
            self.transport.write(new_secure_packet.__serialize__())
Пример #19
0
 def sign(self):
     self.signature = self.sk.sign(
         self.msg,
         padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                     salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256())
     return self.signature
Пример #20
0
def verify(signature, message, public_key):
    return public_key.verify(
        base64.b64decode(signature), message,
        padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                    salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256())
Пример #21
0
 def signature_verify(self, message, signature):
     self.signature_client_public_key.verify(
         signature, message,
         padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                     salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256())
Пример #22
0
    def handshake(self, packet):
        if self.flag:
            logger.debug("recvive a handshake packet when connect ESTABLISHED")
            return

        if self.mode == "server":
            if packet.status == 0:
                # load file
                self.loadCertFile()
                print("load success")

                certification = x509.load_pem_x509_certificate(
                    packet.cert, default_backend())
                self.client_decode_pubKey = certification.public_key()

                try:
                    print("server mode begin verify")
                    self.client_decode_pubKey.verify(
                        packet.signature, packet.pk,
                        padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                                    salt_length=padding.PSS.MAX_LENGTH),
                        hashes.SHA256())

                    # Verify the signature in cryptography module (tbs)
                    cur_cert = certification
                    for data in packet.certChain:
                        cert = x509.load_pem_x509_certificate(
                            data, default_backend())
                        cert_pubk = cert.public_key()
                        cert_pubk.verify(cur_cert.signature,
                                         cur_cert.tbs_certificate_bytes,
                                         padding.PKCS1v15(), hashes.SHA256())
                        cur_cert = cert

                    # Verify the root
                    root_pubk = self.root_cert.public_key()
                    root_pubk.verify(cur_cert.signature,
                                     cur_cert.tbs_certificate_bytes,
                                     padding.PKCS1v15(), hashes.SHA256())

                except Exception as error:
                    logger.debug("wrong signature, server 0 failed")
                    self.transport.write(
                        HandshakePacket(status=2).__serialize__())
                    self.transport.close()

                print("server mode verify success")
                # create server key, both ephemeral and long term
                self.getServerKey()

                # create pk
                self.server_pkData = self.server_pubKey_eph.public_bytes(
                    Encoding.PEM, PublicFormat.SubjectPublicKeyInfo)

                # Generate shared key
                tmp_pubk = load_pem_public_key(packet.pk,
                                               backend=default_backend())
                self.shared_key = self.privkB.exchange(ec.ECDH(), tmp_pubk)

                # create signature
                serverSignature = self.server_privKey_longTerm.sign(
                    self.server_pkData,
                    padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                                salt_length=padding.PSS.MAX_LENGTH),
                    hashes.SHA256())

                # create server nonce
                server_int_nonce = randint(0, 100000)
                self.server_nonce = str(server_int_nonce).encode('ASCII')
                client_nonce = str(packet.nonce).encode('ASCII')

                # server certificate
                server_certificate = self.createCertificate(
                    self.server_pubKey_longTerm)

                # Create certificate chain
                self.cert_chain = [self.team4_cert_fileread]

                # creating server nonceSignature
                serverNonceSignature = self.server_privKey_longTerm.sign(
                    client_nonce,
                    padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                                salt_length=padding.PSS.MAX_LENGTH),
                    hashes.SHA256())

                server_packet = HandshakePacket(
                    status=1,
                    pk=self.server_pkData,
                    signature=serverSignature,
                    nonce=server_int_nonce,
                    nonceSignature=serverNonceSignature,
                    cert=server_certificate,
                    certChain=self.cert_chain)

                self.transport.write(server_packet.__serialize__())

                print("server 0 success")

            elif packet.status == 1:
                try:
                    print("packet status=1 test")
                    self.client_decode_pubKey.verify(
                        packet.nonceSignature, self.server_nonce,
                        padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                                    salt_length=padding.PSS.MAX_LENGTH),
                        hashes.SHA256())
                except Exception as error:
                    logger.debug("wrong signature, server verify failed")
                    self.transport.write(HandshakePacket(status=2))
                    self.transport.close()

                print("packet status =1 test success")

                # Create hash 1
                digest1 = hashes.Hash(hashes.SHA256(),
                                      backend=default_backend())
                digest1.update(self.shared_key)
                hash1 = digest1.finalize()
                self.ivA = hash1[0:12]
                self.ivB = hash1[12:24]

                # Create hash2
                digest2 = hashes.Hash(hashes.SHA256(),
                                      backend=default_backend())
                digest2.update(hash1)
                hash2 = digest2.finalize()
                self.decB = hash2[0:16]

                # Create hash3
                digest3 = hashes.Hash(hashes.SHA256(),
                                      backend=default_backend())
                digest3.update(hash2)
                hash3 = digest3.finalize()
                self.encB = hash3[0:16]

                self.flag = True
                self.higherProtocol().connection_made(self.higher_transport)

        if self.mode == "client" and packet.status == 1:
            print(" client && packet status=1 test")
            self.server_decode_pubKey = x509.load_pem_x509_certificate(
                packet.cert, default_backend()).public_key()

            try:
                print(packet.pk)
                self.server_decode_pubKey.verify(
                    packet.signature, packet.pk,
                    padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                                salt_length=padding.PSS.MAX_LENGTH),
                    hashes.SHA256())

                self.server_decode_pubKey.verify(
                    packet.nonceSignature, self.client_nonce,
                    padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                                salt_length=padding.PSS.MAX_LENGTH),
                    hashes.SHA256())

                # Verify the signature in cryptography module (tbs)
                cur_cert = certification
                for data in packet.certChain:
                    cert = x509.load_pem_x509_certificate(
                        data, default_backend())
                    cert_pubk = cert.public_key()
                    cert_pubk.verify(cur_cert.signature,
                                     cur_cert.tbs_certificate_bytes,
                                     padding.PKCS1v15(), hashes.SHA256())
                    cur_cert = cert

                # Verify the root
                root_pubk = self.root_cert.public_key()
                root_pubk.verify(cur_cert.signature,
                                 cur_cert.tbs_certificate_bytes,
                                 padding.PKCS1v15(), hashes.SHA256())

            except Exception as error:
                logger.debug("client verify failed")
                self.transport.write(HandshakePacket(status=2).__serialize__())
                self.transport.close()

            print(" client && packet status=1 test   success")

            # Generate shared key
            tmp_pubk = load_pem_public_key(packet.pk,
                                           backend=default_backend())
            self.shared_key = self.privkA.exchange(ec.ECDH(), tmp_pubk)

            # server nonce
            server_nonce = str(packet.nonce).encode('ASCII')
            client_nonce = self.client_privKey_longTerm.sign(
                server_nonce,
                padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                            salt_length=padding.PSS.MAX_LENGTH),
                hashes.SHA256())

            self.transport.write(
                HandshakePacket(status=1,
                                nonceSignature=client_nonce).__serialize__())
            print("client packet status =1 test success")

            # Create hash 1
            digest1 = hashes.Hash(hashes.SHA256(), backend=default_backend())
            digest1.update(self.shared_key)
            hash1 = digest1.finalize()
            self.ivA = hash1[0:12]
            self.ivB = hash1[12:24]

            # Create hash2
            digest2 = hashes.Hash(hashes.SHA256(), backend=default_backend())
            digest2.update(hash1)
            hash2 = digest2.finalize()
            self.decB = hash2[0:16]

            # Create hash3
            digest3 = hashes.Hash(hashes.SHA256(), backend=default_backend())
            digest3.update(hash2)
            hash3 = digest3.finalize()
            self.encB = hash3[0:16]

            self.flag = True
            self.higherProtocol().connection_made(self.higher_transport)
Пример #23
0
 def sign(self, msg, key):
     return key.sign(
         msg,
         padding.PSS(mgf=padding.MGF1(self.hash_alg()),
                     salt_length=self.hash_alg.digest_size),
         self.hash_alg())
Пример #24
0
def data():
    mensaje= b"89392679556575597635196565386081702718512260749406173579320076828061414488077821523722981888265393212848183094"

    #X25519 bench
    start_time= time()
    private_key = X25519PrivateKey.generate()
    peer_public_key = X25519PrivateKey.generate().public_key()
    k255=time()-start_time
    #print("Generación llave X25519 en: " + str(k255) + " sec con tamaño: "+ str(sys.getsizeof(private_key))+" bytes")
    private_key=0

    #25519 sign
    start_time= time()
    private_key = Ed25519PrivateKey.generate()
    signature = private_key.sign(mensaje)
    s255=time()-start_time
    #print("Generación firma X25519 en: " + str(s255) + " sec")

    start_time= time()
    public_key = private_key.public_key()
    public_key.verify(signature, mensaje)
    ver255=time()-start_time
    #print("Verificación firma X25519 en: " + str(ver255) + " sec")
    private_key=0
    #448 Key Exchange
    start_time=time()
    private_key = X448PrivateKey.generate()
    peer_public_key = X448PrivateKey.generate().public_key()
    k448=time()-start_time
    #print("Generación 448 llave en: " + str(k448) + " sec con tamaño: "+ str(sys.getsizeof(private_key))+" bytes")
    private_key=0
    #448 sign

    private_key = Ed448PrivateKey.generate()
    start_time= time()
    signature = private_key.sign(mensaje)
    s448=time()-start_time
    #print("Generación 448 firma en: " + str(s448) + " sec")
    start_time=time()
    public_key = private_key.public_key()
    public_key.verify(signature, mensaje)
    ver448=time()-start_time
    #print("Verificación 448 firma en: " + str(ver448) + " sec")
    private_key=0

    #RSA GENERATION
    start_time=time()
    private_key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=2048,
    )
    krsa=time()-start_time
    #print("Generación RSA llave en: " + str(krsa) + " sec con tamaño: "+ str(sys.getsizeof(private_key))+" bytes")

    #RSA SINGING
    start_time=time()
    signature = private_key.sign(
        mensaje,
        padding.PSS(
            mgf=padding.MGF1(hashes.SHA256()),
            salt_length=padding.PSS.MAX_LENGTH
        ),
        hashes.SHA256()
    )
    srsa=time()-start_time
    #print("Generación RSA firma en: " + str(srsa) + " sec")
    private_key=0
    #DSA SINGING
    start_time=time()
    private_key = dsa.generate_private_key(
        key_size=1024,
    )
    kdsa=time()-start_time
    #print("Generación DSA llave en: " + str(kdsa) + " sec con tamaño: "+ str(sys.getsizeof(private_key))+" bytes")
    start_time =time()
    signature = private_key.sign(
        mensaje,
        hashes.SHA256()
    )
    sdsa=time()-start_time
    #print("Generación DSA firma en: " + str(sdsa) + " sec")


    return [k255,s255,ver255,k448,s448,ver448,krsa,srsa,kdsa,sdsa]
Пример #25
0
 def test_rsa_padding_unsupported_pss_mgf1_hash(self):
     assert backend.rsa_padding_supported(
         padding.PSS(mgf=padding.MGF1(DummyHashAlgorithm()),
                     salt_length=0)) is False
Пример #26
0
def RSA_sign(data, priv_key):
    return data + priv_key.sign(
        data,
        padding.PSS(mgf=padding.MGF1(hashes.SHA1()),
                    salt_length=padding.PSS.MAX_LENGTH), hashes.SHA1())
Пример #27
0
 def __init__(self):
     padfn = padding.PSS(padding.MGF1(hashes.SHA256()),
                         hashes.SHA256.digest_size)
     super(_PS256, self).__init__(padfn, hashes.SHA256())
Пример #28
0
from __future__ import absolute_import, division, unicode_literals

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicNumbers

from mo_dots import Data, wrap
from mo_json import value2json, json2value
from mo_math import bytes2base64, base642bytes, int2base64, base642int


SHA256 = hashes.SHA256()
PSS  = padding.PSS(
    mgf=padding.MGF1(SHA256), salt_length=padding.PSS.MAX_LENGTH
)
PADDING = {
    "PSS": PSS
}
ALGORITHM = {
    "SHA256": SHA256
}

BACKEND = default_backend()


def generate_key(bits=512):
    private_key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=bits,
Пример #29
0
 def __init__(self):
     padfn = padding.PSS(padding.MGF1(hashes.SHA512()),
                         hashes.SHA512.digest_size)
     super(_PS512, self).__init__(padfn, hashes.SHA512())
def signRSA(priv_key, message):
    signature = priv_key.sign(
        message,
        padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                    salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256())
    return signature