Пример #1
0
def verify_data(public_key,plain_text,signature):
    """ Verify the message and signature
    
    Parameters
    ----------
    public_key : 
        public key
    plain_text : 
        message
    signature : 
        signed message
    
    Returns
    -------
        result of verification
    """
    try:
        public_key.verify(
            signature=signature,
            data=plain_text.encode('utf-8'),
            padding=padding.PSS(
                mgf=padding.MGF1(hashes.MD5()),
                salt_length=padding.PSS.MAX_LENGTH
            ),
            algorithm=hashes.MD5()
        )
        is_signature_correct = True
    except InvalidSignature:
        is_signature_correct = False
    return is_signature_correct
Пример #2
0
    def test_rsa(self):
        backend = MultiBackend([DummyRSABackend()])

        backend.generate_rsa_private_key(key_size=1024, public_exponent=65537)

        backend.create_rsa_signature_ctx("private_key", padding.PKCS1v15(),
                                         hashes.MD5())

        backend.create_rsa_verification_ctx("public_key", "sig",
                                            padding.PKCS1v15(), hashes.MD5())

        backend = MultiBackend([])
        with raises_unsupported_algorithm(
                _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM):
            backend.generate_rsa_private_key(key_size=1024, public_exponent=3)

        with raises_unsupported_algorithm(
                _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM):
            backend.create_rsa_signature_ctx("private_key", padding.PKCS1v15(),
                                             hashes.MD5())

        with raises_unsupported_algorithm(
                _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM):
            backend.create_rsa_verification_ctx("public_key", "sig",
                                                padding.PKCS1v15(),
                                                hashes.MD5())
Пример #3
0
def send_to_server(host, port, size, question):
    s = None
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((host, port))
    # except socket.error, (value,message):
    except socket.error as message:
        if s:  # see if s is None or not
            s.close()
        print("Unable to open the socket: " + str(message))
        return

    # question = b'Who was the first president of the United States?'
    print("[INFO] Encrypting Question")

    # TODO: encrypt the question here
    key = Fernet.generate_key()
    f = Fernet(key)
    token = f.encrypt(question)
    md5Hash = hashes.Hash(hashes.MD5(), backend=default_backend())
    md5Hash.update(token)
    md5_hash_result = md5Hash.finalize()

    print("[Key] " + str(key))
    print("[Token] " + str(token))
    print("[MD5 Hash] " + str(md5_hash_result))

    # TODO: serialize the question with pickle
    message = pickle.dumps((key, token, md5_hash_result))
    print("[Message] " + str(message))

    # TODO: Send the question to the server
    s.send(message)

    # TODO: Decode the echoed message from the server
    response = s.recv(size)
    
    (encrypted_response, md5Hash_response) = pickle.loads(response)
    
    # TODO: Create a checksum on the response
    md5ResponseHash = hashes.Hash(hashes.MD5(), backend=default_backend())
    md5ResponseHash.update(encrypted_response)
    md5_response_hash = md5Hash.finalize()
    
    result = False
    
    # TODO: if the hashes match, print the message and use Watson API
    if md5_response_hash == md5Hash_response:
		decrypted_response = f.decrypt(encrypted_response)
		print('[RESPONSE] ' + str(decrypted_response))
		# TODO: Convert the response to a speech file and play the file
		watson_speech(decrypted_response)
		result = True
	else:
		print('[ERROR] Message from server corrupted.')
    
    # Close the server connection and return
    s.close()
    return result
    def test_pbkdf2(self):
        backend = MultiBackend([DummyPBKDF2HMACBackend([hashes.MD5])])
        assert backend.pbkdf2_hmac_supported(hashes.MD5())

        backend.derive_pbkdf2_hmac(hashes.MD5(), 10, b"", 10, b"")

        with pytest.raises(UnsupportedAlgorithm):
            backend.derive_pbkdf2_hmac(hashes.SHA1(), 10, b"", 10, b"")
Пример #5
0
    def test_hmac(self):
        backend = MultiBackend([DummyHMACBackend([hashes.MD5])])
        assert backend.hmac_supported(hashes.MD5())

        hmac.HMAC(b"", hashes.MD5(), backend=backend)

        with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_HASH):
            hmac.HMAC(b"", hashes.SHA1(), backend=backend)
Пример #6
0
def sign_data(private_key, plain_text):
    # SIGN DATA/STRING
    signature = private_key.sign(data=plain_text.encode('utf-8'),
                                 padding=padding.PSS(
                                     mgf=padding.MGF1(hashes.MD5()),
                                     salt_length=padding.PSS.MAX_LENGTH),
                                 algorithm=hashes.MD5())
    return signature
Пример #7
0
    def test_pbkdf2(self):
        backend = MultiBackend([DummyPBKDF2HMACBackend([hashes.MD5])])
        assert backend.pbkdf2_hmac_supported(hashes.MD5())

        backend.derive_pbkdf2_hmac(hashes.MD5(), 10, b"", 10, b"")

        with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_HASH):
            backend.derive_pbkdf2_hmac(hashes.SHA1(), 10, b"", 10, b"")
Пример #8
0
 def test_unsupported_mgf1_hash_algorithm_md5_decrypt(self):
     private_key = RSA_KEY_512.private_key(backend)
     with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_PADDING):
         private_key.decrypt(
             b"0" * 64,
             padding.OAEP(mgf=padding.MGF1(algorithm=hashes.MD5()),
                          algorithm=hashes.MD5(),
                          label=None))
Пример #9
0
    def test_hashes(self):
        backend = MultiBackend([DummyHashBackend([hashes.MD5])])
        assert backend.hash_supported(hashes.MD5())

        hashes.Hash(hashes.MD5(), backend=backend)

        with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_HASH):
            hashes.Hash(hashes.SHA1(), backend=backend)
Пример #10
0
    def test_hmac(self):
        backend = MultiBackend([DummyHMACBackend([hashes.MD5])])
        assert backend.hmac_supported(hashes.MD5())

        hmac.HMAC(b"", hashes.MD5(), backend=backend)

        with pytest.raises(UnsupportedAlgorithm):
            hmac.HMAC(b"", hashes.SHA1(), backend=backend)
Пример #11
0
    def test_hashes(self):
        backend = MultiBackend([DummyHashBackend([hashes.MD5])])
        assert backend.hash_supported(hashes.MD5())

        hashes.Hash(hashes.MD5(), backend=backend)

        with pytest.raises(UnsupportedAlgorithm):
            hashes.Hash(hashes.SHA1(), backend=backend)
Пример #12
0
def verify_data(public_key, plain_text, signature):
    try:
        public_key.verify(signature=signature,
                          data=plain_text.encode('utf-8'),
                          padding=padding.PSS(
                              mgf=padding.MGF1(hashes.MD5()),
                              salt_length=padding.PSS.MAX_LENGTH),
                          algorithm=hashes.MD5())
        is_signature_correct = True
    except InvalidSignature:
        is_signature_correct = False
    return is_signature_correct
Пример #13
0
def md5_str(original):
    if not original and not isinstance(original, str):
        return None
    digest = hashes.Hash(hashes.MD5(), backend=default_backend())
    digest.update(original.encode())
    md5_str = digest.finalize()
    return md5_str.hex().upper()
Пример #14
0
    def verify(self, packet):
        """ Pass a message to verify with this key, or a key (OpenPGP, _RSAobj, or _DSAobj)
            to check this message with
            Second optional parameter to specify which signature to verify (if there is more than one)
        """
        m = None
        packet = self._parse_packet(packet)
        if not self._message:
            m = packet
            verifier = self.verifier
        else:
            m = self._message
            verifier = self.__class__(packet).verifier

        byhash = {
            'MD5':       lambda m, s: verifier(hashes.MD5(), m, s),
            'RIPEMD160': lambda m, s: verifier(hashes.RIPEMD(), m, s),
            'SHA1':      lambda m, s: verifier(hashes.SHA1(), m, s),
            'SHA224':    lambda m, s: verifier(hashes.SHA224(), m, s),
            'SHA256':    lambda m, s: verifier(hashes.SHA256(), m, s),
            'SHA384':    lambda m, s: verifier(hashes.SHA384(), m, s),
            'SHA512':    lambda m, s: verifier(hashes.SHA512(), m, s)
        }

        return m.verified_signatures({'RSA': byhash, 'DSA': byhash})
Пример #15
0
    def _GetLSAKey(self, registry, boot_key):
        """Retrieves the LSA key.

    Args:
      registry (dfwinreg.WinRegistry): Windows Registry.
      boot_key (bytes): boot key.

    Returns:
      bytes: LSA key or None if not found.
    """
        policy_encryption_key = registry.GetKeyByPath(
            self._POLICY_ENCRYPTION_KEY_PATH)
        if not policy_encryption_key:
            return None

        policy_encryption_value = policy_encryption_key.GetValueByName('')
        if not policy_encryption_value:
            return None

        value_data = policy_encryption_value.data

        algorithm = hashes.MD5()
        backend = backends.default_backend()
        digest_context = hashes.Hash(algorithm, backend=backend)

        digest_context.update(boot_key)

        iteration = 0
        while iteration < 1000:
            digest_context.update(value_data[60:76])
            iteration += 1

        rc4_key = digest_context.finalize()
        decrypted_data = self._DecryptARC4(rc4_key, value_data[12:60])
        return decrypted_data[16:32]
Пример #16
0
def challenge(ioin, ioout):
    ioout.write(b"hello\n")
    key = secrets.token_bytes(nbytes=None)
    salt = secrets.token_bytes(nbytes=16)
    aesgcm = AESGCM(key)
    attempted_nonces = list()
    for attempt in range(len(PLAINTEXTS)):
        nonce = ioin.readline().strip()
        if (len(nonce) < 10 or len(nonce) > 100 or nonce in attempted_nonces
                or not all([c in string.printable.encode() for c in nonce])):
            ioout.write(b"no\n")
            return
        attempted_nonces.append(nonce)
        ioout.write(
            aesgcm.encrypt(
                PBKDF2HMAC(
                    algorithm=hashes.MD5(),
                    length=32,
                    salt=salt,
                    iterations=100000,
                    backend=default_backend(),
                ).derive(nonce),
                secrets.choice(PLAINTEXTS),
                None,
            ).hex().encode() + b"\n")
Пример #17
0
def AES_decrypt(key, enc_data):
    # key: aes_key || hmac_key
    aes_key = key[:24]
    hmac_key = key[24:]
    # enc_data: iv || cipher || mac
    iv, cipher, mac = enc_data[:16], enc_data[16:-16], enc_data[-16:]

    aes = Cipher(algorithms.AES(aes_key), modes.CBC(iv))
    decryptor = aes.decryptor()
    data = decryptor.update(cipher) + decryptor.finalize()

    # check padding
    data = unpad(data)
    if not data:
        return None, "padding error"

    # check hmac
    cal_mac = iv + cipher
    for _ in range(7777):  # enhanced secure
        h = hmac.HMAC(hmac_key, hashes.MD5())
        h.update(cal_mac)
        cal_mac = h.finalize()
    if cal_mac != mac:
        return None, "hmac error"

    return data, None
Пример #18
0
def cal_password_hash(password):
    hash = password.encode() + SALT
    for _ in range(7777):  # enhanced secure
        digest = hashes.Hash(hashes.MD5())
        digest.update(hash)
        hash = digest.finalize()
    return hash
Пример #19
0
def scan_authorities():
    """
    Search proper directory for certificates, load them and store metadata.

    :return: list of CertificateAuthority objects
    :rtype: list
    """
    logger.debug("Crts", "Scanning for certificate authorities")
    storage.certificate_authorities.clear()
    ca_cert_dir = config.get("certificates", "ca_cert_dir")
    ca_key_dir = config.get("certificates", "ca_key_dir")
    if not os.path.exists(ca_cert_dir):
        os.makedirs(ca_cert_dir)
    if not os.path.exists(ca_key_dir):
        os.makedirs(ca_key_dir)
    for x in glob.glob(os.path.join(ca_cert_dir, "*.pem")):
        id = os.path.splitext(os.path.split(x)[1])[0]
        with open(x, "rb") as f:
            cert = x509.load_pem_x509_certificate(f.read(), default_backend())
        key_path = os.path.join(ca_key_dir, "{0}.key".format(id))
        with open(key_path, "rb") as f:
            with open(key_path, "rb") as f:
                key = serialization.load_pem_private_key(
                    f.read(),
                    password=None,
                    backend=default_backend()
                )
        sha1 = binascii.hexlify(cert.fingerprint(hashes.SHA1())).decode()
        md5 = binascii.hexlify(cert.fingerprint(hashes.MD5())).decode()
        kt = "RSA" if isinstance(key.public_key(), rsa.RSAPublicKey) else "DSA"
        ca = CertificateAuthority(id, x, key_path, cert.not_valid_after,
                                  kt, key.key_size, sha1, md5)
        storage.certificate_authorities[id] = ca
    return storage.certificate_authorities
Пример #20
0
def make_cert(netid,
              pubkey,
              ca_key=ECE422_CA_KEY,
              serial=x509.random_serial_number()):
    builder = x509.CertificateBuilder()
    builder = builder.not_valid_before(datetime.datetime(2017, 9, 6))
    builder = builder.not_valid_after(datetime.datetime(2017, 9, 20))
    builder = builder.subject_name(
        x509.Name([
            x509.NameAttribute(NameOID.COMMON_NAME, unicode(netid)),
            x509.NameAttribute(
                NameOID.PSEUDONYM,
                u'abcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcd'
            ),
            x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'),
            x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u'Illinois'),
        ]))
    builder = builder.issuer_name(
        x509.Name([
            x509.NameAttribute(NameOID.COMMON_NAME, u'ece422'),
        ]))
    builder = builder.serial_number(serial)
    builder = builder.public_key(pubkey)
    cert = builder.sign(private_key=ECE422_CA_KEY,
                        algorithm=hashes.MD5(),
                        backend=default_backend())
    return cert
Пример #21
0
    def encrypt(self, password, data):
        """Encrypt given data using md5 + salt + aes-128-cbc."""
        # IrssiNotifier requires null at the end
        databytes = data.encode() + bytes(1)
        padder = padding.PKCS7(128).padder()
        padded_data = padder.update(databytes) + padder.finalize()
        salt = os.urandom(8)
        key = None
        iv = None

        for n in range(2):
            # this following logic is similar to EVP_BytesToKey() from openssl
            md5hash = hashes.Hash(hashes.MD5())
            if key is not None:
                md5hash.update(key)
            md5hash.update(password.encode())
            md5hash.update(salt)
            md5 = md5hash.finalize()
            if key is None:
                key = md5
                continue
            if iv is None:
                iv = md5

        aes256cbc = ciphers.Cipher(ciphers.algorithms.AES(key),
                                   ciphers.modes.CBC(iv))
        encryptor = aes256cbc.encryptor()
        edata = encryptor.update(padded_data) + encryptor.finalize()
        edata = 'Salted__'.encode() + salt + edata
        edata = base64.b64encode(edata, b'-_')
        edata = edata.replace(b'=', b'')
        return edata
def digestMD5(data, arg_list=None):
    digest = hashes.Hash(hashes.MD5(), backend=default_backend())
    digest.update(data)
    if (arg_list):
        for arg in arg_list:
            digest.update(arg)
    return digest.finalize()
Пример #23
0
def set_certificate_attrs(entry_attrs):
    """
    Set individual attributes from some values from a certificate.

    entry_attrs is a dict of an entry

    returns nothing
    """
    if not 'usercertificate' in entry_attrs:
        return
    if type(entry_attrs['usercertificate']) in (list, tuple):
        cert = entry_attrs['usercertificate'][0]
    else:
        cert = entry_attrs['usercertificate']
    cert = x509.normalize_certificate(cert)
    cert = x509.load_certificate(cert, datatype=x509.DER)
    entry_attrs['subject'] = unicode(DN(cert.subject))
    entry_attrs['serial_number'] = unicode(cert.serial_number)
    entry_attrs['serial_number_hex'] = u'0x%X' % cert.serial_number
    entry_attrs['issuer'] = unicode(DN(cert.issuer))
    entry_attrs['valid_not_before'] = x509.format_datetime(
        cert.not_valid_before)
    entry_attrs['valid_not_after'] = x509.format_datetime(cert.not_valid_after)
    entry_attrs['md5_fingerprint'] = x509.to_hex_with_colons(
        cert.fingerprint(hashes.MD5()))
    entry_attrs['sha1_fingerprint'] = x509.to_hex_with_colons(
        cert.fingerprint(hashes.SHA1()))
class TestMD5(object):
    test_md5 = generate_hash_test(
        load_hash_vectors,
        os.path.join("hashes", "MD5"),
        ["rfc-1321.txt"],
        hashes.MD5(),
    )
    def __init__(self, app, pipeline, id=None, config=None):
        super().__init__(app, pipeline, id, config)

        self.Backend = default_backend()

        algorithm = self.Config['algorithm'].upper()

        if algorithm == "SHA224":
            self.Algorithm = hashes.SHA224()
        elif algorithm == "SHA256":
            self.Algorithm = hashes.SHA256()
        elif algorithm == "SHA384":
            self.Algorithm = hashes.SHA384()
        elif algorithm == "SHA512":
            self.Algorithm = hashes.SHA512()
        elif algorithm == "SHA1":
            self.Algorithm = hashes.SHA1()
        elif algorithm == "MD5":
            self.Algorithm = hashes.MD5()
        elif algorithm == "BLAKE2B":
            digest_size = int(self.Config['digest_size'])
            self.Algorithm = hashes.BLAKE2b(digest_size)
        elif algorithm == "BLAKE2S":
            digest_size = int(self.Config['digest_size'])
            self.Algorithm = hashes.BLAKE2s(digest_size)
        else:
            L.error("Unknown hashing algorithm '{}'".format(
                self.Config['algorithm']))
            raise RuntimeError("Unknown hashing algorithm '{}'".format(
                self.Config['algorithm']))
Пример #26
0
def make_cert(netid,
              pubkey,
              ca_key=ECE422_CA_KEY,
              serial=x509.random_serial_number()):
    serial = 619896898465676799222673698197894680027116984392
    builder = x509.CertificateBuilder()
    builder = builder.not_valid_before(datetime.datetime(2017, 3, 1))
    builder = builder.not_valid_after(datetime.datetime(2017, 3, 27))
    builder = builder.subject_name(
        x509.Name([
            x509.NameAttribute(NameOID.COMMON_NAME, str(netid)),
            x509.NameAttribute(
                NameOID.PSEUDONYM,
                u'unused012345678901234567890123456789012345678901234567890123456'
            ),
            x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'),
            x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u'Illinois'),
        ]))
    builder = builder.issuer_name(
        x509.Name([
            x509.NameAttribute(NameOID.COMMON_NAME, u'ece422'),
        ]))
    print("Serial : ", serial)
    builder = builder.serial_number(serial)
    builder = builder.public_key(pubkey)
    cert = builder.sign(private_key=ECE422_CA_KEY,
                        algorithm=hashes.MD5(),
                        backend=default_backend())
    return cert
Пример #27
0
 def decript(self, ct, mac):
     backend = default_backend()
     cipher = None
     block_size = 0
     # Algoritmo
     if self.algoritmo == 'AES':
         alg = algorithms.AES(self.key)
         block_size = alg.block_size
     elif self.algoritmo == 'CAST5':
         alg = algorithms.CAST5(self.key)
         block_size = alg.block_size
     # Modo de encriptografar
     if self.modo == 'ECB':
         mod = modes.ECB()
     elif self.modo == 'CBC':
         mod = modes.CBC(self.iv)
     cipher = Cipher(alg, mod, backend=default_backend())
     # Sintese
     if self.sintese == 'SHA-256':
         sints = hashes.SHA256()
     elif self.sintese == 'MD5':
         sints = hashes.MD5()
     # Decryptor
     decryptor = cipher.decryptor()
     # Padder
     unpadder = padding.PKCS7(block_size).unpadder()
     # Hmac
     h = hmac.HMAC(self.key, sints, backend=default_backend())
     # VERIFICAR SE O HMAC CONTINUA O MESMO
     h.update(ct)
     h.verify(mac)
     padded_data = decryptor.update(ct) + decryptor.finalize()
     data = unpadder.update(padded_data) + unpadder.finalize()
     clean_data = base64.b64decode(data)
     return clean_data
Пример #28
0
    def symmetric_key_gen(self):

        if (self.digest == "SHA256"):
            alg = hashes.SHA256()
        elif (self.digest == "SHA384"):
            alg = hashes.SHA384()
        elif (self.digest == "MD5"):
            alg = hashes.MD5()
        elif (self.digest == "SHA512"):
            alg = hashes.SHA512()
        elif (self.digest == "BLAKE2"):
            alg = hashes.BLAKE2b(64)

        kdf = HKDF(algorithm=alg,
                   length=32,
                   salt=None,
                   info=b'handshake data',
                   backend=default_backend())

        key = kdf.derive(self.shared_key)

        if self.symmetric_cipher == 'AES':
            self.symmetric_key = key[:16]
        elif self.symmetric_cipher == '3DES':
            self.symmetric_key = key[:8]
        elif self.symmetric_cipher == 'ChaCha20':
            self.symmetric_key = key[:32]
Пример #29
0
    def compute_message_authenticator(
            radius_packet,
            packed_req_authenticator,
            shared_secret
    ):
        """
        Computes the "Message-Authenticator" of a given RADIUS packet.
        """

        if not conf.crypto_valid:
            g_log_loading.info(_crypto_loading_failure_message)
            return None

        packed_hdr = struct.pack("!B", radius_packet.code)
        packed_hdr += struct.pack("!B", radius_packet.id)
        packed_hdr += struct.pack("!H", radius_packet.len)
        packed_attrs = ''
        for index in range(0, len(radius_packet.attributes)):
            packed_attrs = packed_attrs + str(radius_packet.attributes[index])

        hmac_ = hmac.HMAC(
            shared_secret,
            hashes.MD5(),
            backend=default_backend()
        )
        packed_data = packed_hdr + packed_req_authenticator + packed_attrs
        hmac_.update(packed_data)
        return hmac_.finalize()
Пример #30
0
 def encript(self, txt):
     backend = default_backend()
     cipher = None
     block_size = 0
     # Algoritmo
     if self.algoritmo == 'AES':
         alg = algorithms.AES(self.key)
         block_size = alg.block_size
     elif self.algoritmo == 'CAST5':
         alg = algorithms.CAST5(self.key)
         block_size = alg.block_size
     # Modo de encriptografar
     if self.modo == 'ECB':
         mod = modes.ECB()
     elif self.modo == 'CBC':
         mod = modes.CBC(self.iv)
     cipher = Cipher(alg, mod, backend=default_backend())
     # Sintese
     if self.sintese == 'SHA-256':
         sints = hashes.SHA256()
     elif self.sintese == 'MD5':
         sints = hashes.MD5()
     encryptor = cipher.encryptor()
     # Text
     msg = base64.b64encode(txt)
     padder = padding.PKCS7(block_size).padder()
     padded_data = padder.update(msg) + padder.finalize()
     # Encrypted text
     ct = encryptor.update(padded_data) + encryptor.finalize()
     # HMAC
     h = hmac.HMAC(self.key, sints, backend=default_backend())
     h.update(ct)
     mac = h.finalize()
     return ct, mac