Exemplo n.º 1
0
    def recv_text_file(self):
        """
        This function receives data from the client and writes it to
        a file the server's user chooses.
        """

        Tk().withdraw()
        # Asking the server's user to insert a path to create a text file in.
        path = askopenfilename()

        # Opening the file in a write mode.
        with open(path, mode='wt', encoding='utf-8') as f:
            # Preparing the keys and the client_socket.
            priv_key = self.prepare_keys()
            client_socket = self.socket_operations()

            data = client_socket.recv(1024).decode('utf-8')

            # Looping until the client sends no data at all.
            while True:
                if not data:
                    break
                # Decrypting the data, writing it to the file and "re-inputting it".
                data = decrypt(data, priv_key)
                f.write(data)
                data = client_socket.recv(1024).decode('utf-8')
            client_socket.close()
        exit(0)
Exemplo n.º 2
0
def read(file_name, file_path):
    """
    Prints in console the decrypted content and/or creates a file in which the decrypted content can be found.
    Throws an exception if the output file cannot be opens or if it cannot be written in
    :param file_name: The file name
    :param file_path: The file path
    :return: None
    """
    enc_content_cursor = metadata_table.find({"Name": file_name})
    for enc_content in enc_content_cursor:
        print("enc: ", enc_content)
        dc = decrypt(enc_content["Content"])
        name, ext = os.path.splitext(file_path)
        if ext == ".txt":
            print(dc.decode("utf-8"))
        else:
            print("Check the file \"result\" for the decoded content! ")
        try:
            path = "C:\\Users\\Daria\\Desktop\\"
            result = "result" + ext
            print_file = open(path + result, "wb")
            print_file.write(dc)
            print_file.close()
        except Exception as e:
            print(e)
Exemplo n.º 3
0
def encrypt_extract(mark_file_name, len_watermark=7, marks=''):
    # read && count
    word_style = read_document_style(mark_file_name)

    contents = read_document(mark_file_name)
    word_count = count(contents)

    # marking
    watermark = ''

    for index, word in enumerate(word_count):
        if index >= math.ceil(len_watermark/8):
            break
        special_mark = word_style.get(word)
        watermark += special_mark

    # print(watermark)
    watermark = del_pad(watermark, len_watermark)
    code = decrypt(origin_code=marks, b=watermark)
    print(code)
Exemplo n.º 4
0
    def decrypt(self):
        if not self.ptxt.get():
            tkMessageBox.showinfo(
                message="U should Ente Plain Text And Click On Encrypt Widget")
            return
        if not self.etxt.get():
            tkMessageBox.showinfo(message="U Should Click On Encrypt Widget")
            return
        if not self.prk.get():
            tkMessageBox.showinfo(message="Enter The Private Key")
            return
        privatekey = str(self.prk.get())

        #self.ptxt.set(decrypt(str(self.etxt.get()),privatekey))
        self.history.config(state='normal')
        self.history.insert(
            Tkinter.END,
            'decrypt:\n' + decrypt(str(self.etxt.get()), privatekey) + '\n')
        self.history.config(state='disabled')
        self.history.see(Tkinter.END)
Exemplo n.º 5
0
"""
This script is only a testing script for our RSA algorithm.py
"""
from RSA import generate, encrypt, decrypt

key_pair = generate(1024)
print "Generated Key pairs"
public_key = key_pair["public"]
private_key = key_pair["private"]

text = "Hello World! Testing the first RSA implementation."
print "Input Text:"
print text

# Now encrypt
ciphertext = encrypt(public_key, text)
print "Ciphertext is: "
print ciphertext

# Now decrypt
output_text = decrypt(private_key, ciphertext)
print "The encrypted text was:"
print output_text
Exemplo n.º 6
0
def right_path(file_path):
    if (file_path == ""):
        return file_path
    separate = file_path.split("\\")
    new = ""
    for temp in separate:
         new += temp + "\\"+"\\"
    return new

while(True):
    command = raw_input('Encrypt file or decrypt cipher?: ')
    if command.lower() == 'encrypt':
        file_path = raw_input('Include full file path: ')
        file_path = right_path(file_path)
        file_name = raw_input('Enter file name with extension: ')
        file_path += file_name
        encrypt(file_path)
        print("File successfully encrypted")
        break

    if command.lower() == 'decrypt':
        cipher_path = raw_input('Include full cipher path: ')
        cipher_path = right_path(cipher_path)
        file_name = raw_input('Enter file name with extension: ')
        cipher_path += file_name
        decrypt(cipher_path)
        print("Cipher successfully decrypted")
        break

    print("Wrong command, try again")
Exemplo n.º 7
0
plaintext = "Daniel Han Kuo-yu is a Taiwanese politician. He was a member of the Legislative Yuan from 1993 to 2002, " \
            "representing a portion of Taipei County for three terms. He later became general manager of Taipei " \
            "Agricultural Products Marketing Corporation. In 2017, Han contested the Kuomintang chairmanship, " \
            "losing to Wu Den-yih. Han was elected Mayor of Kaohsiung in November 2018, and became the first " \
            "Kuomintang politician since Wu in 1998 to hold the office. Han is the KMT's nominee running against " \
            "incumbent president Tsai Ing-wen in the 2020 Taiwan presidential election. "

ciphertext = ""

p, q, n, e, d = initial(1024)
print("==KEY==")
print("p=" + str(p))
print("q=" + str(q))
print("n=" + str(n))
print("e=" + str(e))
print("d=" + str(d) + "\n")

print("==PLAINTEXT==")
print(plaintext + "\n")

print("==CIPHERTEXT==")
ciphertext = encrypt(plaintext, n, e)
print(ciphertext + "\n")

print("==CIPHERTEXT DECRYPT==")
plaintext_decrypt = decrypt(ciphertext, n, d)
print(plaintext_decrypt + "\n")

if plaintext == plaintext_decrypt:
    print("SUCCESS")
SIZE = 1024

hostName = gethostbyname('DE1_SoC')
# hostName = gethostbyname( 'DESKTOP-A30LB1P' )

mySocket = socket(AF_INET, SOCK_DGRAM)
mySocket.bind((hostName, PORT_NUMBER))

print("Test server listening on port {0}\n".format(PORT_NUMBER))
client_public_key = ''
while True:
    (data, addr) = mySocket.recvfrom(SIZE)
    data = data.decode()
    if data.find('public_key') != -1:  # client has sent their public key\
        # retrieve public key and private key from the received message (message is a string!)
        x = data.split()
        public_key_e = int(x[1])
        public_key_n = int(x[2])
        public = (public_key_e, public_key_n)
        print('public key is : %d, %d' % (public_key_e, public_key_n))
    else:
        cipher = int(data)
        public = (public_key_e, public_key_n)
        data_decoded = decrypt(public, cipher)
        print(str(cipher) + ':' + data_decoded)
        # data_decoded is the decoded character based on the received cipher, calculate it using functions in RSA.py
        # python2: print data ,

sys.ext()
# What could I be doing wrong?
Exemplo n.º 9
0
if (int(userOption) == 3):
    print("Decrypt for: ") 
    print("1. Current Client")
    print("2. Another Client")
    encryptionOption = input("Your Option: ")

    if (encryptionOption == 1):
        userMessage = raw_input("Enter Ciphertext to Decrypt: ")
        file = open("n.txt","r")
        n = int(file.read())
        file.close()
        file = open("d5.txt","r")
        d5 = int(file.read())
        file.close()
        print(decrypt(n,d5,userMessage))


    if (encryptionOption == 2):
        userMessage = input("Enter Message to Encrypt: ")
        user_e = input("Enter Public Exponent: ")
        user_n = input("Enter Modulus: ")

if (int(userOption) == 4):
    userMessage = raw_input("Message to sign: ")
    file = open("n.txt","r")
    modulus = int(file.read())
    file.close()
    file = open("d5.txt","r")
    d5 = int(file.read())
    file.close()
Exemplo n.º 10
0
coder = des.des()  # des is a class defined in des.py
r = coder.encrypt(des_key, image_data, cbc=False)  # encrypted image

# write the encrypted image into file
r_byte = bytearray()
for x in r:
    r_byte += bytes([ord(x)])
file = open(r'penguin_encrypted.bin', "wb+")
file.write(r_byte)
file.close()

# recover DES Key
des_key_decoded = []
for data in des_encoded:
    cipher = int(data)
    des_key_decoded += decrypt(private, cipher)
print("DES key decoded = " + str(des_key_decoded))
print("decrypting the image with the recovered key")
decoder = des.des()
des_key_decoded_str = ''
for i in des_key_decoded:
    des_key_decoded_str = des_key_decoded_str + str(i)

rr = decoder.decrypt(des_key, r, cbc=False)  # this is in string  format, must convert to byte format
rr_byte = bytearray()
for x in rr:
    rr_byte += bytes([ord(x)])

# write to file to make sure it is okay
file2 = open(r'penguin_decrypted.jpg', "wb")
file2.write(bytes(rr_byte))
Exemplo n.º 11
0
from RSA import generate_keypair, encrypt, decrypt, find_primes

if __name__ == '__main__':
    '''
    Detect if the script is being run directly by the user
    '''
    print("RSA Encrypter/ Decrypter")
    p, q = find_primes(200)
    print("Generating your public/private keypairs now . . .")
    public, private = generate_keypair(p, q)
    print("Your public key is {} and your private key is {}".format(
        public, private))
    message = input("Enter a message to encrypt with your private key: ")
    encrypted_msg = encrypt(public, message)
    print("Your encrypted message is: ")
    print('---'.join(map(lambda x: str(x), encrypted_msg)))
    print("Decrypting message with public key ", public, " . . .")
    print("Your message is:")
    print(decrypt(private, encrypted_msg))
 data = data.decode()
 if data.find('public_key') != -1:  # client has sent their public key\
     # retrieve public key and private key from the received message (message is a string!)
     x = data.split()
     public_key_e = int(x[1])
     public_key_n = int(x[2])
     public = (public_key_e, public_key_n)
     print('public key is : %d, %d' % (public_key_e, public_key_n))
 elif data.find('des_key') != -1:  # client has sent their DES key
     # read the next 8 bytes for the DES key by running (data,addr) = mySocket.recvfrom(SIZE) 8 times and then decrypting with RSA
     i = 0
     public = (public_key_e, public_key_n)
     while i < 8:
         (data, addr) = mySocket.recvfrom(SIZE)
         i = i + 1
     des_key = decrypt(public, data)
     print('DES key is :' + des_key)
     # now we will receive the image from the client
     (data, addr) = mySocket.recvfrom(SIZE)
     # decrypt the image
     ###################################your code goes here####################
     # the received encoded image is in data
     # perform des decryption using des.py
     coder = des.des()
     newdata = coder.decrypt(public, data)
     # the final output should be saved in a byte array called rr_byte
     rr_byte = bytearray()
     # write to file to make sure it is okay
     file2 = open(r'penguin_decrypted.jpg', "wb")
     file2.write(bytes(rr_byte))
     file2.close()
Exemplo n.º 13
0
try: #Verifica se o arquivo possui uma chave válida
    chaves = content[0].split(',')
    chaves = [int(chaves[i]) for i in range(len(chaves))]    
except: #Caso não possua, cria uma chave
    print('Nenhuma chave válida foi encontrada, deseja incerir uma nova? [s/n]: ')
    switch = input()
    while (switch.upper() != 'S') and (switch.upper() != 'N'): #Verifica se a resposta é válida
        print('Resposta inválida')
        switch = input()        
    while True: #Faz a enttrada da chave e testa se é válida
        if switch.upper() == 'S':
            chave = input('Entre com chaves válidas no seguinte formato "N, Chave Pública, Chave Privada": ')
            try:
                chave = chave.split(',')
                chave = (int(chave[0]),int(chave[1]),int(chave[2]))            
                while decrypt(encrypt('a',chave),chave) != 'a': #Testa validade da chave
                    print('Chave inválida')
                    chave = input('Entre com chaves válidas no seguinte formato "N, Chave Pública, Chave Privada": ')                
            except:
                print('Formato de chave inválido')
        elif switch.upper() == 'N': #Caso não seja inserida uma chave, o programa cria uma
            chave = keyrsa(lista_primos(200))
            print('A chave',chave,'foi gerada com sucesso!')
        log = open('log.txt','r')
        conteudo = log.readlines()
        log = open('log.txt','w')
        conteudo.insert(0,str(chave[0])+','+str(chave[1])+','+str(chave[0])+'\n') 
        log.writelines(conteudo)
        log.close()
        break
    
Exemplo n.º 14
0
    digit_lenght = prime_1 * prime_2
    if digit_lenght < 400:
        digit_lenght = 1
    public_key, private_key, phi = gen_keys(prime_1, prime_2,
                                            2 * len(str(digit_lenght)))
    e, n = public_key
    d = private_key[0]

    print(f"Le couple de nombre premier (p, q) est : {prime_1}, {prime_2}")
    print(f"Produit des deux nombres premiers nommés N = {n}")
    print(f"Phi_n = (prime1-1)(prime2-1) = {phi}")
    print(f"d => d*e % phi_n = 1 : {d}")
    print(f"e => copremier avec phi_n dans ]1, phi_n[ : {e}")
    print(f"La clé publique (e, N) = {public_key}")
    print(f"La clé privée est (d, N) = {private_key}\n")

    print(context_salutation_justified)
    print(context_instruction)
    message = input('Message d\'amour : ')

    message_crypté = encrypt(message, public_key)
    text_crypté = ''.join(str(mot) for mot in message_crypté)
    hexa_text_crypté = hex(int(text_crypté))
    message_décrypter = decrypt(message_crypté, private_key)
    text_décrypté = ''.join(message_décrypter)

    print(f'Le message envoyé en hexadécimale : {hexa_text_crypté}')

    print(context_decrypt_justified)
    print(f'Le message reçu : {text_décrypté}')