def send_text_file(self): """ This function receives a path and reads the data from the file in this path. It sends the data to the server in an encrypted form. """ Tk().withdraw() # Asking the server's user to insert a path to create a text file in. path = askopenfilename() # Opening the file in a read mode. with open(path, mode='rt', encoding='utf-8') as f: # Creating the public key and preparing the socket. pub_key = self.recv_pub_key() my_socket = self.socket_operations() chunk_size = 5 f_contents = f.read(chunk_size) # Reading the file's content until there is nothing to read. while True: if len(f_contents) == 0: break # Encrypting the data, sending it to the server and reading the new data. f_contents = encrypt(f_contents, pub_key) my_socket.send(f_contents.encode('utf-8')) f_contents = f.read(chunk_size) my_socket.close() exit(0)
def encrypt(self): if not self.ptxt.get(): tkMessageBox.showinfo(message="Don't leave Empty") return self.etxt.set(encrypt((str(self.ptxt.get())))) self.history.config(state='normal') self.history.insert(Tkinter.END, 'encrypt:\n' + (str(self.etxt.get())) + '\n') self.history.config(state='disabled') self.history.see(Tkinter.END)
def encrypt_watermarking(file_name, mark_file_name, marks="1111000"): # encrypt & binary encrypt_mark = encrypt(code=marks) len_encrypt_mark = len(encrypt_mark) binary_mark = pad_encrypt(encrypt_mark) # print(binary_mark) binary_mark_len = int(len(binary_mark) / 8) # read from file && count by freq contents = read_document(file_name) word_count = count(contents) words = Word.get_words(word_count.keys()) assert len(words) >= binary_mark_len, u"mark的长度超过了文本的字符数,尝试缩小mark或增长文本" # watermarking for index, word in enumerate(words[:binary_mark_len]): mark = binary_mark[index * 8:index * 8 + 8] word.set_special_style(True, mark) # print write_document(words, mark_file_name, contents=contents) return len_encrypt_mark
""" 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
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")
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")
PORT_NUMBER = 5000 SIZE = 1024 print("Test client sending packets to IP {0}, via port {1}\n".format( SERVER_IP, PORT_NUMBER)) mySocket = socket(AF_INET, SOCK_DGRAM) message = 'hello' #first generate the keypair #get these two numbers from the excel file p = 1297333 q = 1297693 ###################################your code goes here##################################### #generate public and private key from the p and q values pk = generate_keypair(p, q) #RSA Keypairs public = pk[1] private = pk[0] message = ('public_key: %d %d' % (public[0], public[1])) mySocket.sendto(message.encode(), (SERVER_IP, PORT_NUMBER)) while True: message = input() ###################################your code goes here##################################### #message is a string input received from the user, encrypt it with RSA character by character and save in message_encoded #message encoded is a list of integer ciphertext values in string format e.g. ['23131','352135','54213513'] for i in message: #loop through message, and send each character through RSA encrytion with private key message_encoded = str(encrypt(private, i)) mySocket.sendto(message_encoded.encode(), (SERVER_IP, PORT_NUMBER)) #[mySocket.sendto(code.encode(),(SERVER_IP,PORT_NUMBER)) for code in message_encoded] sys.exit()
q = 1297651 # ##################################your code goes here##################################### # generate public and private key from the p and q values public, private = generate_keypair(p, q) # send key message = ('public_key: %d %d' % (public[0], public[1])) mySocket.sendto(message.encode(), (SERVER_IP, PORT_NUMBER)) # send des_key message = ('des_key') mySocket.sendto(message.encode(), (SERVER_IP, PORT_NUMBER)) # ##################################your code goes here##################################### # encode the DES key with RSA and save in DES_encoded, the value below is just an example des_encoded = [] for i in message: cipher = encrypt(private, i) des_encoded.append(cipher) [ mySocket.sendto(code.encode(), (SERVER_IP, PORT_NUMBER)) for code in des_encoded ] # read image, encode, send the encoded image binary file file = open(r'penguin.jpg', "rb") data = file.read() file.close() # ##################################your code goes here##################################### # the image is saved in the data parameter, you should encrypt it using des.py # set cbc to False when performing encryption, you should use the des class # use bytearray to send the encryped image through network # r_byte is the final value you will send through socket
public, private = generate_keypair(p, q) # returns (e,n) and (d, n) print("RSA Public Key pair = " + str(public)) print("RSA Private Key pair = " + str(private)) # read message from user print("enter the DES key, 8 Characters") des_key = input() while len(des_key) != 8: # ensure proper input length print("wrong! 8 characters. Try again:") des_key = input() # encrypt the DES key print("encrypting DES KEY with RSA") des_encoded = [str(encrypt(public, chars)) for chars in des_key] print("the encrypted key is " + str(des_encoded)) # encrypt the image with DES print('encrypting image using DES') file = open(r'penguin.jpg', "rb") image_data = file.read() file.close() 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+")
if (int(userOption) == 1): generateKey(2048) if (int(userOption) == 2): print("Encryption for: ") print("1. This Client") print("2. Another Keypair") encryptionOption = input("Your Option: ") if (encryptionOption == 1): userMessage = raw_input("Enter Message to Encrypt: ") file = open("n.txt","r") n = int(file.read()) file.close() e = 5 print(encrypt(e,n,userMessage)) if (encryptionOption == 2): userMessage = input("Enter Message to Encrypt: ") user_e = input("Enter Public Exponent: ") user_n = input("Enter Modulus: ") 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: ")
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))
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
# first generate the keypair # get these two numbers from the excel file p = 1297273 q = 1297651 # generate public and private key from the p and q values # public is (e, n) and private is (d, n) public, private = generate_keypair(p, q) message = ('public_key: %d %d' % (public[0], public[1])) mySocket.sendto(message.encode(), (SERVER_IP, PORT_NUMBER)) while True: message = input("Enter a message:") message.join('\n') message_encoded = [] for i in message: cipher = str(encrypt(private, i)) message_encoded.append(cipher) # message is a string input received from the user, encrypt it with RSA character by character and save in message_encoded # message encoded is a list of integer ciphertext values in string format e.g. ['23131','352135','54213513'] [ mySocket.sendto(code.encode(), (SERVER_IP, PORT_NUMBER)) for code in message_encoded ] sys.exit() # What could I be doing wrong?
#first generate the keypair #get these two numbers from the excel file p = 1297447 q = 1297973 ###################################your code goes here##################################### #generate public and private key from the p and q values public, private = generate_keypair(p, q) message = ('public_key: %d %d' % (public[0], public[1])) mySocket.sendto(message.encode(), (SERVER_IP, PORT_NUMBER)) #send key ###################################your code goes here##################################### # Encrypt and send the DES key using RSA message_encoded = [] for x in range(len(des_key)): message_encoded.append(str(encrypt(private, des_key[x]))) message = ",".join(message_encoded) message = "des_key," + message mySocket.sendto(message.encode(), (SERVER_IP, PORT_NUMBER)) #read image, encode, send the encoded image binary file file = open(r'penguin.jpg', "rb") data = file.read() file.close() ###################################your code goes here##################################### #the image is saved in the data parameter, you should encrypt it using des.py #set cbc to False when performing encryption, you should use the des class #coder=des.des(), use bytearray to send the encryped image through network #r_byte is the final value you will send through socket
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é}')