Ejemplo n.º 1
0
    def unpack_pb(self, b, key = None):
	"""Decrypt the blob, decrypt any private data, return a protocol buffer."""

	s = b
	if key is None:
	    key = self.table_key
	if key is not None:
	    try:
		s = decrypt(key, b)
	    except:
		raise ValueError, "decrypt() failed. Bad key or bad ciphertext."

	pb = self.pbc()
	pb.MergeFromString(s)

	# Decrypt any private data. It's not an error if there's no .user_key,
	# or the key is wrong, it just doesn't decrypt.

	if pb.HasField("private_bytes") and self.user_key is not None:
	    try:
		s = decrypt(self.user_key, pb.private_bytes)
		pb.private.MergeFromString(s)
		pb.ClearField("private_bytes")
	    except:
		pass
	return pb
Ejemplo n.º 2
0
def test_protocol():
    start_time = time.time()
    Alice = DiffieHellman()
    q = Alice.get_generator()
    p = Alice.get_prime()
    Bob = DiffieHellman(generator=q, prime=p)
    # Compute respective public keys
    PU_A = Alice.get_public_key()
    PU_B = Bob.get_public_key()
    # Compute shared session key
    K_A = Alice.get_session_key(PU_B)
    K_B = Bob.get_session_key(PU_A)
    assert K_A == K_B

    #CSPRNG
    bbs = BlumBlumShub(q=383, p=503)
    Alice_secret_key = bbs.generate(seed=K_A, key_len=128)
    Bob_secret_key = bbs.generate(seed=K_B, key_len=128)
    assert Alice_secret_key == Bob_secret_key
    assert len(Alice_secret_key) == 128
    # From Alice to Bob
    message = "Hi Bob, this is a message that should be encrypted properly"
    enc_message = encrypt(message, Alice_secret_key)
    dec_message = decrypt(enc_message, Bob_secret_key)
    assert message in dec_message

    # From Bob to Alice
    message = "Hi Alice, this is also a message that should be encrypted properly"
    enc_message = encrypt(message, Bob_secret_key)
    dec_message = decrypt(enc_message, Alice_secret_key)
    assert message in dec_message
    total_time = (time.time() - start_time)
    print(f'##########\nPassed protocol test in {total_time}s\n##########')
Ejemplo n.º 3
0
    def test_header(self):
        from cipher import cipher
        HEADER = cipher.HEADER
        cipher.HEADER = b"foo"

        secret = encrypt(self.passwd, self.txt)
        with self.assertRaises(Exception) as ctx:
            decrypt(self.passwd, secret)
        self.assertEqual(type(ctx.exception), RuntimeError)
        self.assertEqual(str(ctx.exception), "Missing header, cannot decrypt")

        cipher.HEADER = HEADER
        secret = encrypt(self.passwd, self.txt)
        self.assertEqual(decrypt(self.passwd, secret), self.txt)
Ejemplo n.º 4
0
def consultEntry(activeUser):
	os.system("clear")
	print("################################################################################")
	print("############################## ENTRIES BY DATE #################################")
	print("################################################################################")
	print "\n\n"

	date = raw_input("	Digite a data (YYYY-MM-DD): ")
	connection = connectDatabase()
	cursor = connection.cursor()

	query= 'SELECT title,text,date(creation_date),time(creation_date) ' \
		   'FROM entry where date(creation_date) = %s and user = %s'
	query2= 'SELECT count(*) FROM entry where date(creation_date) = %s and user = %s'
	cursor.execute(query2, (date,activeUser))
	for i in cursor:
		print "\nForam encontrados "+str(i[0])+" registros nessa data!"
	if(i[0] != 0):
		b = raw_input("Aperte uma tecla para ver as entradas: ")
		cursor.execute(query, (date,activeUser))
		for title, text, date, time in cursor:
			os.system("clear")
			print("################################################################################")
			print("################################ ALL ENTRIES ###################################")
			print("################################################################################")
			print "\n\n"
			print(title + ", as " + str(time) + ", em " + str(date) + ".")
			text = cipher.decrypt(activeUser, text)
			print "	"+text
			b = raw_input("\n\nAperte uma tecla para ir para a proxima entrada: ")
	c = raw_input("Fim das entradas, aperte uma tecla para voltar ao menu: ")

	cursor.close()
	connection.close()
Ejemplo n.º 5
0
    def handle_tcp(self, remote):
        sock = self.request
        sock_list = [sock, remote]
        while 1:
            read_list, _, _ = select(sock_list, [], [])
            if remote in read_list:
                data = remote.recv(8192)
                if not data:
                    break
                enc = cipher.encrypt(data)
                length = len(enc)
                logging.debug('send data to client: {}'.format(length))
                sock.send(u16_to_bytes(length))
                if (sock.send(enc) <= 0):
                    break
            if sock in read_list:
                data = safe_recv(sock, 2)
                if data is None:
                    break
                length = bytes_to_int(data)
                logging.debug('fetching data from client: {}'.format(length))

                data = safe_recv(sock, length)
                if data is None:
                    break
                dec = cipher.decrypt(data)
                logging.debug('send data to server: {}'.format(len(dec)))
                if (remote.send(dec) <= 0):
                    logging.debug('send to server error')
                    break
Ejemplo n.º 6
0
def decryption_button(request):
    if request.method == "POST":
        data = json.loads(request.body)
        decryptedData = decrypt(data['text'], int(data['key1']),
                                int(data['key2']))
        responseJson = json.dumps({'text': decryptedData}, ensure_ascii=False)
        return HttpResponse(responseJson, content_type='application/json')
Ejemplo n.º 7
0
    def handle_tcp(self, remote):
        sock = self.request
        sock_list = [sock, remote]
        while 1:
            read_list, _, _ = select(sock_list, [], [])
            if remote in read_list:
                data = remote.recv(8192)
                if not data:
                    break
                enc = cipher.encrypt(data)
                length = len(enc)
                logging.debug('send data to client: {}'.format(length))
                sock.send(u16_to_bytes(length))
                if (sock.send(enc) <= 0):
                    break
            if sock in read_list:
                data = safe_recv(sock, 2)
                if data is None:
                    break
                length = bytes_to_int(data)
                logging.debug('fetching data from client: {}'.format(length))

                data = safe_recv(sock, length)
                if data is None:
                    break
                dec = cipher.decrypt(data)
                logging.debug('send data to server: {}'.format(len(dec)))
                if (remote.send(dec) <= 0):
                    logging.debug('send to server error')
                    break
Ejemplo n.º 8
0
    def handle_tcp(self, remote):
        sock = self.request
        sock_list = [sock, remote]
        while True:
            read_list, _, _ = select(sock_list, [], [])
            if remote in read_list:
                data = safe_recv(remote, 2)
                if data is None:
                    break
                length = bytes_to_int(data)
                logging.debug('receiving data from remote: {}'.format(length))
                data = safe_recv(remote, length)
                if not data:
                    break
                dec = cipher.decrypt(data)
                if (sock.send(dec) <= 0):
                    break

            if sock in read_list:
                data = sock.recv(8192)
                if not data:
                    break
                enc = cipher.encrypt(data)
                length = len(enc)
                remote.send(u16_to_bytes(length))
                logging.debug('send data to server: {}'.format(length))
                if (remote.send(enc) <= 0):
                    break
Ejemplo n.º 9
0
    def __generateParcialHashes(self,finger=None):

        pk = None
        while pk == None:
            try:
                pk = self.__getPrivateKey()
            except ValueError:
                pass
        
        ivs = []
        my_file = Path(self.pathIvs)
        if my_file.is_file():
            with open(my_file,'rb') as f:
                for i in range(self.numSalt):
                    iv = f.read(16)
                    ivs.append(iv)
        else:
            raise IOError('Ivs\'s file not found.')
        
        salt = self.contract.functions.getSalt().call()  #lo devuelve directamente en binario!        
        salt = cipher.decrypt(salt,pk,ivs)
        
        if finger == None:
            fp = FingerPrinter()
            finger = fp.getFingerprinting()
            
        hashes = []
        for i in range(self.numSalt):
            k = keccak.new(digest_bits=256)
            k.update(salt[i])
            k.update(finger[i].encode())
            hashes.append(k.digest()) 
            
        return hashes
Ejemplo n.º 10
0
def test_AES():
    start_time = time.time()
    key = '11100101010001100001110100011111100101000010010011000010011111101101001110010110101101010101011101101101110010000111101001000111'
    enc = encrypt('Hello World!', key)
    dec = decrypt(enc, key)
    assert 'Hello World!' in dec
    total_time = (time.time() - start_time)
    print(f'##########\nPassed AES test in {total_time}s\n##########')
Ejemplo n.º 11
0
def evaluate_keys(analyzer, ciphertext, keys):
    import cipher
    fitness = []
    for key in keys:
        text = cipher.decrypt(ciphertext, key)
        score = analyzer.text_fitness(text)

        fitness.append((key, score, text))

    fitness.sort(reverse=True, key=sort_score)
    return fitness[:5]
Ejemplo n.º 12
0
def decrypt(to_proc, key, is_file, out=None):
    if is_file:
        txt = cipher.read(to_proc, key)
    else:
        txt = cipher.decrypt(key, to_proc)

    if out:
        with open(out, "w") as fd:
            fd.write(txt)
    else:
        sys.stdout.write(txt)
Ejemplo n.º 13
0
def get_msg():
    """Receives and decrypts the encrypted message"""
    if request.method == 'POST':
        data = request.get_json(force=True)
        msg = base64.decodebytes(data['msg'].encode())  #Bring it back to bytes
        session['messages'].append({
            'decrypted':
            decrypt(ciphertext=msg, key=session['secret_key']),
            'encrypted':
            msg
        })
    return ''
Ejemplo n.º 14
0
    def handle(self):
        try:
            data = self.request.recv(1)
        except ConnectionResetError:
            logging.error('ConnectionResetError')
            return
        except Exception as e:
            logging.error('Error: {}'.format(e))
            return
        if not data:
            return
        logging.info('client connected [{}]'.format(D['C']))

        addr_length = data[0]
        data_addr = safe_recv(self.request, addr_length)
        if data_addr is None:
            return

        try:
            addr = cipher.decrypt(data_addr).decode()
        except:
            logging.error('cannot decode: {}'.format(data_addr))
            return

        data_port = safe_recv(self.request, 2)
        if data_port is None:
            return
        port = bytes_to_int(data_port)
        logging.info("connecting to {}:{}".format(addr, port))
        remote = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            remote.connect((addr, port))
        except:
            logging.error('cannot connect to {}:{}'.format(addr, port))
            return

        D['C'] += 1
        logging.info("waiting for {}:{}".format(addr, port))
        try:
            self.handle_tcp(remote)
        except ConnectionResetError:
            logging.error('ConnectionResetError [{}]'.format(D['C']))
        except TimeoutError:
            logging.error('TimeoutError [{}]'.format(D['C']))
        except Exception as e:
            logging.exception('Error in handle_tcp(): {} [{}]'.format(
                e, D['C']))
        finally:
            remote.close()
        D['C'] -= 1
        logging.info('client closed [{}]'.format(D['C']))
Ejemplo n.º 15
0
    def handle(self):
        try:
            data = self.request.recv(1)
        except ConnectionResetError:
            logging.error('ConnectionResetError')
            return
        except Exception as e:
            logging.error('Error: {}'.format(e))
            return
        if not data:
            return
        logging.info('client connected [{}]'.format(D['C']))

        addr_length = data[0]
        data_addr = safe_recv(self.request, addr_length)
        if data_addr is None:
            return

        try:
            addr = cipher.decrypt(data_addr).decode()
        except:
            logging.error('cannot decode: {}'.format(data_addr))
            return

        data_port = safe_recv(self.request, 2)
        if data_port is None:
            return
        port = bytes_to_int(data_port)
        logging.info("connecting to {}:{}".format(addr, port))
        remote = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            remote.connect((addr, port))
        except:
            logging.error('cannot connect to {}:{}'.format(addr, port))
            return

        D['C'] += 1
        logging.info("waiting for {}:{}".format(addr, port))
        try:
            self.handle_tcp(remote)
        except ConnectionResetError:
            logging.error('ConnectionResetError [{}]'.format(D['C']))
        except TimeoutError:
            logging.error('TimeoutError [{}]'.format(D['C']))
        except Exception as e:
            logging.exception('Error in handle_tcp(): {} [{}]'.format(e, D['C']))
        finally:
            remote.close()
        D['C'] -= 1
        logging.info('client closed [{}]'.format(D['C']))
Ejemplo n.º 16
0
def get_encrypted_cookie(cookie_file):
    with open(cookie_file, 'rb') as f:
        data = f.read()
    cookie = None
    pw = None
    while True:
        pw = getpass.getpass(prompt='Enter password: ')
        try:
            decrypted = decrypt(data, pw)
            cookie = pickle.loads(decrypted)
            break
        except:
            print("Wrong password!")
    return cookie
Ejemplo n.º 17
0
def main():
	loop = True
	while loop == True:
		inputtext = input("Please enter a string: (q to Quit) ")
		if inputtext == "q":
			print("Goodbye!")
			loop = False
			break
		encrypted = cipher.encrypt(inputtext)
		decryptinput = input("Would you like to decrypt your message?: (y/n)")
		if decryptinput == "y":
			decrypted = cipher.decrypt(encrypted[0], encrypted[1])
			decryptloop = False
		elif decryptinput == "n":
			decryptloop = False
Ejemplo n.º 18
0
def main():
    print("***Everything is case sensitive***")
    message = ''
    while message != 'q':
        message = input("What is your message? To quit enter 'q': ")
        if message == 'q':  # solely used for the first iteration, if input is q then end loop
            break
        encryption = cipher.encrypt(message)
        print('Encrypted message:\n', encryption[0], "\nCipher Dictionary:\n",
              encryption[1])
        response = input("Would you like to decrypt? y/n: ")
        if response == 'y':  # Asks if user wants to decrypt
            decryption = cipher.decrypt(encryption[0], encryption[1])
            print("Decrypted message:", decryption)
    print("'q' detected! Terminating sequence.")
Ejemplo n.º 19
0
def handle_client(client):  # Takes client socket as argument.
    name = client.recv(BUFSIZ).decode("utf8")
    welcome = 'Welcome %s! If you ever want to quit, type {quit} to exit.' % name
    client.send(bytes(welcome, "utf8"))
    clients[client] = name
    while True:
        msg = client.recv(BUFSIZ)
        if msg != bytes("{quit}", "utf8"):
            print("Message received")
            print(msg)
            nonce = str(msg).split("###")[1]
            msg = str(msg).split("###")[0]

            # Decoding using key
            r = post('http://127.0.0.1:5000/qkuser/B', json={"receiver": "A"})
            print(r.json())
            data = r.json()
            print("Symmetric key retrieved for A: " + data['status'])
            qkey = data['status']

            nonce = base64.decodebytes(bytes(nonce[:-3],encoding='utf-8'))

            print("Nonce")
            print(nonce)
            print("Ciphertext")
            msg = msg.replace("\\\\","\\")
            msg = msg[2:]
            print(msg)

            print("Qkey")
            print(qkey)

            # TODO: No termino de hacer que funcione el descifrar
            # por el tipo de dato y el nonce

            msg = cipher.decrypt(msg, qkey, nonce)

            # Sending encrypted confirmation
            client.send(bytes(msg.decode("utf8"), "utf8"))
        else:
            client.send(bytes("{quit}", "utf8"))
            client.close()
            del clients[client]
            print("quit")
            break
Ejemplo n.º 20
0
def seeAllEntries(activeUser):
	connection = connectDatabase()
	cursor = connection.cursor()

	query = ('SELECT title, text, date(creation_date), time(creation_date) FROM entry')

	cursor.execute(query)
	for title, text, date, time in cursor:
		os.system("clear")
		print("################################################################################")
		print("################################ ALL ENTRIES ###################################")
		print("################################################################################")
		print "\n\n"
		print(title + ", as " + str(time) + ", em " + str(date) + ".")
		text = cipher.decrypt(activeUser, text)
		print "	"+text
		b = raw_input("\n\nAperte uma tecla para ir para a proxima entrada: ")
	c = raw_input("Fim das entradas, aperte uma tecla para voltar ao menu: ")

	cursor.close()
	connection.close()
Ejemplo n.º 21
0
    def _recv_frame(self, istream, frame=False):
        try:
            ciphertext_len = istream.read_bin_int(keep_in_stream=True)
            ciphertext = istream.read_bin(4 + ciphertext_len)
        except tcp_event.ResourceError:
            return None

        ciphertext = ciphertext[4:]
        plaintext = cipher.decrypt(self._config["key"], ciphertext)
        if plaintext is None:
            raise ValueError("MAC fail, data corrupted")

        if frame:
            frame_type, conn_id = struct.unpack("!BI", plaintext[:5])
            data = plaintext[5:]

            self._record("recv", conn_id, data)
            # self._log.debug("recv frame, type=%d, id=%d" % (frame_type, conn_id))
            return frame_type, conn_id, data
        else:
            return plaintext
Ejemplo n.º 22
0
 def test_simple_cases_negative_shift(self):
     self.assertEqual('ccc', decrypt('bbb', -1))
     self.assertEqual('klm', decrypt('abc', -10))
Ejemplo n.º 23
0
def test_decrypt_encrypt_letters_and_spaces_large_negative_success():
    raw_string = "ALPHABETLEAHGEAIHGETT E RS"
    rotation_amount = -23849
    encrypted_word = cipher.encrypt(raw_string, rotation_amount)
    decrypted_word = cipher.decrypt(encrypted_word, rotation_amount)
    assert decrypted_word == raw_string
Ejemplo n.º 24
0
def test_decrypt_encrypt_output_success():
    raw_string = "ALPHABETLETTERS"
    rotation_amount = 1
    encrypted_word = cipher.encrypt(raw_string, rotation_amount)
    decrypted_word = cipher.decrypt(encrypted_word, rotation_amount)
    assert decrypted_word == raw_string
Ejemplo n.º 25
0
def test_decrypt_success():
    assert cipher.decrypt("BCD", 1) == "ABC"
    assert cipher.decrypt("BCD", 0) == "BCD"
    assert cipher.decrypt("ZAB", -1) == "ABC"
Ejemplo n.º 26
0
 def test_restarts_if_reaches_the_end_of_the_alphabet(self):
     self.assertEqual('xyz', decrypt('yza', 1))
     self.assertEqual('xYz', decrypt('aBc', 3))
     self.assertEqual('XYZ', decrypt('YZA', 1))
     self.assertEqual('XYz', decrypt('ABc', 3))
Ejemplo n.º 27
0
from cipher import decrypt
from convert_to import convert_to_ascii

n = input("Please enter the first key of the private key pair: ")
#n = input("Please enter n, the modulus for both the public and private keys. This is the first key in the key pairs for both the public and private keys: ")
d = input("Please enter the second key of the private key pair: ")
c = input("Finally, please enter the ciphertext: ")

print("The decrypted message is: ")
#decrypt cipher, then convert to hex, then convert to ascii, and print the result
print(convert_to_ascii(format(decrypt(int(c),int(d),int(n)),'x')))

print("\n\nIf you believe the decrypted message is incorrect, it's because you failed to enter the keys properly. Make sure there are no spaces or EOLs in your input.")
Ejemplo n.º 28
0
def test_decrypt_deciphers_encrypt_fixed_key(s):
    cipher = encrypt(s, 20)
    assert decrypt(cipher, 20) == s
Ejemplo n.º 29
0
 def test_restarts_if_reaches_the_beginning_of_the_alphabet(self):
     self.assertEqual('abc', decrypt('xyz', -3))
     self.assertEqual('aBC', decrypt('zAB', -1))
     self.assertEqual('mno', decrypt('vwx', -17))
     self.assertEqual('mNo', decrypt('vWx', -17))
Ejemplo n.º 30
0
 def test_skips_non_alpha_characters(self):
     self.assertEqual('abc123def', decrypt('bcd123efg', 1))
     self.assertEqual('aBC1 3deF!#', decrypt('cDE1 3fgH!#', 2))
Ejemplo n.º 31
0
    p = int(input("Define p for BBS (press 0 to use default) "))
    bitlen = int(input("Define bitlen for BBS (press 0 to use default(1024)) "))
    key_len = int(input("Define key length to be used for AES (press 0 to use default (128)) "))
    if q == 0:
        q = None
    if p == 0:
        p = None
    if bitlen == 0:
        bitlen = 1024
    if key_len == 0:
        key_len = 128
    #CSPRNG
    bbs = BlumBlumShub(q=q, p=p, bitlen=bitlen)
    Alice_secret_key = bbs.generate(seed=K_A, key_len=key_len)
    Bob_secret_key = bbs.generate(seed=K_B, key_len=key_len)
    key_len = len(Bob_secret_key)
    print(f'\nYou have succesfully set up a more secure shared key of length {key_len} for Alice and Bob:\nAlice: {Alice_secret_key}\nBob: {Bob_secret_key}')
    print("\nTest the protocol by writing a message")
    message = input("\n(Alice) Write your message to Bob here: ")
    enc_message = encrypt(message, Alice_secret_key) 
    dec_message = decrypt(enc_message, Bob_secret_key)
    print(f'\nMessage sent over the network: {enc_message}')
    print(f'\nBob decrypting the message by his generated key: {dec_message}')

    message = input("\n(Bob) Write your message to Alice here: ")
    enc_message = encrypt(message, Bob_secret_key) 
    dec_message = decrypt(enc_message, Alice_secret_key)
    print(f'\nMessage sent over the network: {enc_message}')
    print(f'\Alice decrypting the message by her generated key: {dec_message}')

Ejemplo n.º 32
0
def decrypt(blob):
    if blob[0] == "0":
        return blob[1:]
    else:
        return cipher.decrypt(blob[1:])
Ejemplo n.º 33
0
def test_encrypt_decrypt():
    message = u"this is totally a secret"
    cipher_text = cipher.encrypt(message)
    assert message == cipher.decrypt(cipher_text)
Ejemplo n.º 34
0
def test_key_works(i):
    assert decrypt(encrypt('test', i), i) == 'test'
Ejemplo n.º 35
0
def test_decrypt_deciphers_encrypt_variable_key(s, i):
    assert decrypt(encrypt(s, i), i) == s
Ejemplo n.º 36
0
#!/usr/bin/python3
import cipher

if __name__ == '__main__':
    while True:
        print()
        print('----- CipherIT -----')
        print('1. Encrypt')
        print('2. Decrypt')
        print('3. Exit')

        menu_input = int(input('Choice: '))
        print()

        if menu_input == 1:
            text = input('Text: ')
            key = input('Key: ')
            print("Cipher text: " + cipher.encrypt(text, key))
        
        elif menu_input == 2:
            text = input('Text: ')
            key = input('Key: ')
            print("Original text: " + cipher.decrypt(text, key))
        
        elif menu_input == 3:
            break
        
        else:
            print('Unknown input: ' + str(menu_input))
Ejemplo n.º 37
0
#This is the server program for the TauNet system.
#Copyright (c) 2015 Matthew Tighe

host = ''
port = 6283

import socket, cipher
key = input("Please enter your TauNet key: ")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))
while(1):
    s.listen(5)
    conn, addr = s.accept()
    msg = conn.recv(1024)
    if(msg == ""):
        print "\nBlank message received. Discarding..."
    else:
        conn.send("Message received!")
        conn.close()
        print "\nNew message received!\n"
        print cipher.decrypt(msg, key)

Ejemplo n.º 38
0
 def test_decrypt(self):
     for s in self.secrets:
         self.assertEqual(decrypt(self.passwd, s), self.txt)