class LocalOracle(Oracle): def __init__(self, plaintext, mode): Oracle.__init__(self, mode) from rsa import RSA from secret import p, q, e self._rsa = RSA(p, q, e) self._ciphertext = self._rsa.encrypt(bytes_to_long(plaintext)) self._rsa.set_firewall() def call(self, number): Oracle.call(self, number) if self._mode == Oracle.MODE_DECRYPT: return self._rsa.decrypt(number) if self._mode == Oracle.MODE_ENCRYPT: return self._rsa.encrypt(number)
def demonstration(): wire = RSA() print("\nThis program will now walk you through the encryption process...") input = raw_input("Please enter a string to encrypt: ") print("\nYou entered '%s'." % (input)) print("Your public key is: %d" % (wire.publicKey)) print("Your private key is: %d" % (wire.privateKey)) print("Your modulus value is: %d" % (wire.modValue)) raw_input("Press any key to see how encryption works...") print( "\nTo encrypt a string, allow X to equal the ASCII value of a given character. Then use the following formula:" ) print("EncryptedASCII = (X ^ PublicKey) % ModulusValue") print("This results in each character being encrypted as follows:") encryptedCharacters = wire.encrypt(input) for i in range(0, len(encryptedCharacters)): print("\t%s: %d" % (input[i], encryptedCharacters[i])) raw_input("Press any key to see how decryption works...") print( "\nTo decrypt a string, allow X to equal the encrypted value of a given character. Then use the following formula:" ) print("DecryptedASCII = (X ^ PrivateKey) % ModulusValue") print( "\nWhen decrypted, the output should be the same as your initial input!" ) print("'%s' is your original string!" % (wire.decrypt(encryptedCharacters)))
def encrypt_file(self, filename, recipients): message = None # Check if file exists if os.path.exists(filename): with open(filename, 'r') as fp: message = fp.read() else: print("Error: Cannot find file " + filename) return # Send it to each recipient for recipient in recipients: if recipient in self.keys: fp = self.keys[recipient] n, e = None, None with open(fp, 'r') as pub_key: lines = pub_key.readlines() n = int(lines[3]) e = int(lines[4]) encrypted_message = RSA.encrypt(message, n, e) with open(filename + '.pgp', 'w') as fp: fp.write('-----BEGIN PGP MESSAGE-----\n') fp.write( 'Version: Bradley PGPlike - message encoded with ' + recipient + ' public key\n') fp.write('\n') fp.write(encrypted_message + '\n') fp.write('-----END PGP MESSAGE-----') print("Message encoded to " + recipient) else: print("Error: Recipient " + recipient + " not found in keys!")
class Client(object): def __init__(self, rsa_encode_method: str = "oaep"): self.id = random.randint(0, 1 << 64) self.rsa = RSA( encode_method=rsa_encode_method) # RSA key pair of this user self.rsa.generate_key_pairs() # some sensitive private message self.mac = str(random.randint(1000000, 9999999)) # MAC address of user self.imei = str(random.randint(1000000, 9999999)) # IMEI series def send_request(self, content) -> List[Tuple]: """ return a made up WUP request """ # generate a 128-bit AES session key aes_key = random.getrandbits(128) aes = AES.new(aes_key.to_bytes(16, 'big')) # encrypt this session key using a 1024-bit RSA public key encrypted_aes_key = self.rsa.encrypt(aes_key) # use the AES session key to ecrypt the WUP request wups = WUP(content, self.mac, self.imei) encrypted_wups = [aes.encrypt(wup) for wup in wups] # send the RSA-encrypted AES session key and the # encrypted WUP request to the server. return [(self.id, encrypted_aes_key, wup) for wup in encrypted_wups]
def main(): import secret check_secret(secret) rsa = RSA(secret.p, secret.q, secret.e) message = rsa.encrypt(bytes_to_long(read_flag())) rsa.set_firewall() ui = UI(rsa, message) ui.interact()
def encrypt(): data = request.form.get('data') e = request.form.get('e') n = request.form.get('n') if not data or not e or not n: return 'Bad Request', 400 if len(e) > 5 or len(n) > 5: return 'Bad Request', 400 try: encrypted_data = RSA.encrypt(data=data, e=int(e), n=int(n)) except Exception as e: return 'Bad Request', 400 return {'encrypted_data': encrypted_data}
class RSA_Verifier(): def __init__(self, keylen): self.rsa = RSA(keylen) def verify(self, signature, message): signature = b'\x00' + self.rsa.encrypt(signature) r = re.compile(b'\x00\x01\xff+?\x00.{15}(.{20})', re.DOTALL) m = r.match(signature) if not m: print('Signature format wrong') return hash = m.group(1) if hash == bytes.fromhex(sha1(message)): print('Signatures matched') else: print('Signatures did not match')
def showDialog(self): self.anchor = int(self.le1.text()) self.accuracy = int(self.leac.text()) if (self.anchor < self.accuracy): QMessageBox.about(self, "ERROR", "need threshold > accuracy") else: self.text = self.le2.text() rsa1 = RSA(self.anchor, self.accuracy, self.text) rsa1.create_key() self.ciphertext = rsa1.encrypt([rsa1.e, rsa1.n], rsa1.text) self.plaintext = rsa1.decrypt([rsa1.d, rsa1.n], self.ciphertext) self.ciphertext = [chr(a) for a in self.ciphertext] a = ''.join(self.ciphertext) self.le3.setText(str(self.text)) self.le4.setText(str(a)) self.le5.setText(str(self.plaintext)) self.lep.setText(str(rsa1.p)) self.leq.setText(str(rsa1.q)) self.len.setText(str(rsa1.n)) self.lee.setText(str(rsa1.e)) self.led.setText(str(rsa1.d))
def demonstration(): wire = RSA() print("\nThis program will now walk you through the encryption process...") input = raw_input("Please enter a string to encrypt: ") print("\nYou entered '%s'." % (input)) print("Your public key is: %d" % (wire.publicKey)) print("Your private key is: %d" % (wire.privateKey)) print("Your modulus value is: %d" % (wire.modValue)) raw_input("Press any key to see how encryption works...") print("\nTo encrypt a string, allow X to equal the ASCII value of a given character. Then use the following formula:") print("EncryptedASCII = (X ^ PublicKey) % ModulusValue") print("This results in each character being encrypted as follows:") encryptedCharacters = wire.encrypt(input) for i in range(0, len(encryptedCharacters)): print("\t%s: %d" % (input[i], encryptedCharacters[i])) raw_input("Press any key to see how decryption works...") print("\nTo decrypt a string, allow X to equal the encrypted value of a given character. Then use the following formula:") print("DecryptedASCII = (X ^ PrivateKey) % ModulusValue") print("\nWhen decrypted, the output should be the same as your initial input!") print("'%s' is your original string!" % (wire.decrypt(encryptedCharacters)))
def test_encrypt(self, p, q, e, m, encrypted): rsa = RSA(p, q, e) self.assertEqual(encrypted, rsa.encrypt(m))
rsa = RSA(p, q, e) elif use_own_values == "2": rsa = RSA.get_random_rsa() elif use_own_values == "3": run = False break show_values = ask_input("show_values") if show_values == "1": rsa.show_values() continue_with_instance = "1" while continue_with_instance == "1": print() action = ask_input("action") print() if action == "1": word = input('Choose a word: ') print('Word encrypted: {}'.format(rsa.encrypt(word))) elif action == "2": values = input('Input the word encrypted values: ') values = list(map(int, values.split(', '))) print('Word decrypted: {}'.format(rsa.decrypt(values))) continue_with_instance = ask_input("continue_with_instance") run = continue_with_instance != "3"
with open('test.log', 'w') as f: f.seek(0) Alice = RSA("Alice", 256) Bob = RSA("Bob", 256) public_Bob = Bob.public_key public_Alice = Alice.public_key Alice.getpublickey(public_Bob) print("Info about Alice") Alice.info() Bob.getpublickey(public_Alice) print("Info about Bob") Bob.info() print("Test encryption and decryption") open = random.randint(1000000, 9999999999) print("Open text: ", open) cypher = Alice.encrypt(open) print("Encrypted by Alice: ", cypher) message = Bob.decrypt(cypher) print("Decrypted by Bob: ", message) print("Test signature and verification") signa = Bob.Sign(open) print("Message: {}\nSignature: {}".format(signa[0], signa[1])) Ver = Alice.Verify(signa) print("Verification: ", Ver) print("Test for sending keys") key = Alice.send_key() if key == None: key = Bob.send_key() get = Alice.Receive(key) print(get) print("Key from Bob to Alice")
l, u = max(a, ceil(2 * B + r * n, s)), min(b, (3 * B - 1 + r * n) // s) if l > u: print('Something Wrong') return appendAndMerge(M_new, l, u) if len(M_new) == 0: print('Something Wrong!!') return M = M_new i += 1 if __name__ == '__main__': plaintext = b'howdy!' print('Plaintext -', plaintext) m = pkcs1_5Pad(plaintext, 32) print('m -', m) cipher = RSA(256) c = cipher.encrypt(m) print('c -', c) print('Does c have the right padding -', is_padding_correct(c, cipher)) decrypted_plaintext = attack(c, cipher, 32) print('Decrypted Plaintext -', decrypted_plaintext) print('Are they same? ', plaintext == decrypted_plaintext)
#!/usr/bin/env python from rsa import RSA from dh import DHUser, DHSession from elgamal import EGUser, EGSession if __name__ == '__main__': # RSA # CRYPTO-19 c19 = RSA(17, 11, 7) assert c19._d == 23 assert c19.public_key() == (7, 187) assert c19.private_key() == (23, 187) # CRYPTO-20 c = RSA.encrypt(c19.public_key(), 88) m = RSA.decrypt(c19.private_key(), c) assert c == 11 assert m == 88 # Diffie-Hellman # CRYPTO-35 dh_session = DHSession(353, 3) dh_user_a = DHUser(dh_session, 97) dh_user_b = DHUser(dh_session, 233) assert dh_user_a.y == 40 assert dh_user_b.y == 248 assert dh_session.session_key(dh_user_a, dh_user_b) == \ dh_user_a.session_key(dh_user_b.public_key()) == \ dh_user_b.session_key(dh_user_a.public_key()) == 160
import binascii import gmpy2 from rsa import RSA rsa_0 = RSA() n_0 = rsa_0.get_public_key()[1] rsa_1 = RSA() n_1 = rsa_1.get_public_key()[1] rsa_2 = RSA() n_2 = rsa_2.get_public_key()[1] message = "secret" # we use crt to find message number = int(binascii.hexlify(message.encode()), 16) print(number) c_0 = rsa_0.encrypt(number) c_1 = rsa_1.encrypt(number) c_2 = rsa_2.encrypt(number) result = 0 result += c_0 * (n_1 * n_2) * pow(n_1 * n_2, -1, n_0) result += c_1 * (n_0 * n_2) * pow(n_0 * n_2, -1, n_1) result += c_2 * (n_0 * n_1) * pow(n_0 * n_1, -1, n_2) decrypted = result % (n_0 * n_1 * n_2) decrypted = int(gmpy2.cbrt(decrypted)) print(decrypted) print(binascii.unhexlify(hex(decrypted)[2:]).decode())
#设置变量精度 a = Decimal(0) b = Decimal(n) for x in range(limit): t = (a+b)/2 #如果倍增后的明文是偶数,加倍所述明文未包裹模---模数是素数。这意味着明文是不到一半的模量。 if isEven([i2s(m1)]): b = t else: a = t m1 = (m1 * m2) % n return i2s(int(b)).encode('string_escape') if __name__ == "__main__": msg = "VGhhdCdzIHdoeSBJIGZvdW5kIHlvdSBkb24ndCBwbGF5IGFyb3VuZCB3aXRoIHRoZSBGdW5reSBDb2xkIE1lZGluYQ==" myoracle = oracle() pub = myoracle.getPubKey() rsa = RSA() enc = rsa.encrypt(base64.b64decode(msg), pub) returnmeg = attack(enc, pub, myoracle.isEven) print returnmeg
print("[+] Generating keys! Be patient! :) ") print() start = timeit.default_timer() rsa_object.generate_keys(512) stop = timeit.default_timer() print("[i] Keys generated!") print('[+] Elapsed time:', stop-start) print() print("[i] Your public key is: ") time.sleep(.5) print(rsa_object.get_elements()) print() raw_text = input("Write a message to encrypt: ") start = timeit.default_timer() rsa_object.encrypt(raw_text) stop = timeit.default_timer() time.sleep(.2) print("[i] Your message has been encrypted.") print("[+] Elapsed time:", stop-start) time.sleep(1) print() print("[i] Decoding message...") start = timeit.default_timer() rsa_object.decrypt() stop = timeit.default_timer() print("[i] Decoded message with chinese remainder theorem:") print("[i] ", rsa_object.decrypted_text) print("[+] Elapsed time: ", stop-start) print() print("[i] Decoded message with Fast Modular Exponentiation:")
def dataReceived(self, data): global LAST_HASH for item in parse_request(data): js = json.loads(item) command = js['command'] if command == 'SENT': listbox.clear() for item in js['mails']: setText(item) if command == 'INBOX': listbox.clear() for item in js['mails']: setText(item) if command == 'GINBOX': listbox.clear() for item in js['mails']: setText(item) if command == 'MESSAGE': LAST_HASH = js['HASH'] print LAST_HASH m = hashlib.md5() m.update(js['MESSAGE']) print m.hexdigest() if m.hexdigest() != LAST_HASH: print 'BAD HASH' j = json.loads(js['MESSAGE']) ClientUI.readMessage(j) if command == 'PRINT': print js['data'] if command == 'USER': if js['status'] == "OK": currentUser.setParams(js) tk.title('Client ' + currentUser.login) else: # TODO repeat log pass raise Exception("Неверный логин или пароль") if command == "REGISTRATION": # TODO save s_key local o_key, s_key = currentUser.generateRsaKeys() print o_key print s_key with open(js['login'] + '.dat', 'w') as file: json.dump({"s_key": s_key}, file) self.sendData( json.dumps({ "command": "SETOPENKEY", "open_key": o_key, "login": js['login'] })) if command == 'OPENKEY': for request in requests: json_req = json.loads(request) if json_req['command'] == 'SETMESSAGE' and json_req[ "recivers"] == js["login"]: json_req["data"] = RSA.encrypt(json_req["data"], js['open_key']) self.sendData(json.dumps(json_req)) requests[:] = [ item for item in requests if json.loads(item)['recivers'] != js["login"] ] print data
m1 = (m1 * m2) % n limit = int(math.log(n, 2)) + 1 getcontext().prec = limit #设置变量精度 a = Decimal(0) b = Decimal(n) for x in range(limit): t = (a + b) / 2 #如果倍增后的明文是偶数,加倍所述明文未包裹模---模数是素数。这意味着明文是不到一半的模量。 if isEven([i2s(m1)]): b = t else: a = t m1 = (m1 * m2) % n return i2s(int(b)).encode('string_escape') if __name__ == "__main__": msg = "VGhhdCdzIHdoeSBJIGZvdW5kIHlvdSBkb24ndCBwbGF5IGFyb3VuZCB3aXRoIHRoZSBGdW5reSBDb2xkIE1lZGluYQ==" myoracle = oracle() pub = myoracle.getPubKey() rsa = RSA() enc = rsa.encrypt(base64.b64decode(msg), pub) returnmeg = attack(enc, pub, myoracle.isEven) print returnmeg
class RsaTest(object): # Constructor # Populates all verified outcomes def __init__(self): self.publicKey = 65535 self.privateKey = 14440774790529487 self.modValue = 15725236647914011 self.message = "Indiana" self.verifiedResults = [ 6203455842774329L, 10449696731316258L, 10444098371056832L, 13641245043391240L, 7463814312856899L, 10449696731316258L, 7463814312856899L ] # Runs each tests and displays status of each def run(self): self.rsa = RSA() if (self.testGCD() == False): print("\nGCD TEST FAILED!") return else: print("\nGCD TEST PASSED!") if (self.testInvMod() == False): print("MODULAR INVERSE TEST FAILED!") return else: print("MODULAR INVERSE TEST PASSED!") if (self.testIsPrime() == False): print("PRIMALITY TEST FAILED!") return else: print("PRIMALITY TEST PASSED!") if (self.testGeneratePrimePair() == False): print("PRIME PAIR GENERATION TEST FAILED!") return else: print("PRIME PAIR GENERATION TEST PASSED!") if (self.testEncryption() == False): print("ENCRYPTION TEST FAILED!") return else: print("ENCRYPTION TEST PASSED!") if (self.testDecryption() == False): print("DECRYPTION TEST FAILED!") return else: print("DECRYPTION TEST PASSED!") # Runs three tests to ensure Greatest COmmon Denominator functions properly def testGCD(self): if (self.rsa.gcd(12, 40) != 4): return False if (self.rsa.gcd(100, 1000) != 100): return False if (self.rsa.gcd(44, 99) != 11): return False return True # Runs three tests to verify that inverse modulus works properly def testInvMod(self): if (self.rsa.invMod(12, 35) != 3): return False if (self.rsa.invMod(111, 1321) != 1202): return False if (self.rsa.invMod(45, 91) != 89): return False return True # Runs three tests to verify primality function works correctly def testIsPrime(self): if (self.rsa.isPrime(1255567) != True): return False if (self.rsa.isPrime(7) != True): return False if (self.rsa.isPrime(7233) != False): return False return True # Verifies that a random prime pair is generated so that p > q and p != q def testGeneratePrimePair(self): self.rsa.generatePrimePair() a = self.rsa.primePair["p"] b = self.rsa.primePair["q"] if (self.rsa.isPrime(a) == False): return False if (self.rsa.isPrime(b) == False): return False if (b >= a): return False return True # Verifies that the encryption algorithm works correctly def testEncryption(self): self.rsa.publicKey = self.publicKey self.rsa.privateKey = self.privateKey self.rsa.modValue = self.modValue if (self.rsa.encrypt(self.message) != self.verifiedResults): return False return True # Verifies that the decryption algorithm works correctly def testDecryption(self): self.rsa.publicKey = self.publicKey self.rsa.privateKey = self.privateKey self.rsa.modValue = self.modValue if (self.rsa.decrypt(self.verifiedResults) != self.message): return False return True
class Server: def __init__(self, host, port): self.host=host self.port=port self.crypt=RSA() tuple=self.crypt.prime_tuple() p, q = tuple n=p*q e=self.crypt.public_key(tuple) self.pub_k=(e, n) d=self.crypt.private_key(tuple, e) self.priv_k=(d, n) async def start(self, loop): serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: serv.bind((self.host,self.port)) serv.setblocking(False) print("server started...") except socket.error as e: print(str(e)) serv.listen() while True: conn , addr = await loop.sock_accept(serv) print(str(addr)+" connected") loop.create_task(self.handler(conn, loop)) async def handler(self, conn, loop): obj=Data() hash=SHA256.new() username="" password="" public_key="" await loop.sock_sendall(conn, str.encode("Enter username: "******"utf-8") if res: username=res await loop.sock_sendall(conn, str.encode("Enter password: "******"users", username, password) if not result: obj.user_entry(username, password) await loop.sock_sendall(conn, str.encode("Enter public key: ")) res_en=await loop.sock_recv(conn, 2048) res=res_en.decode("utf-8") if res: try: public_key=eval(res) except Exception as e: print(str(e)) await loop.sock_sendall(conn, str.encode("Name a group that you would want to create or join: ")) res_en=await loop.sock_recv(conn, 2048) res=res_en.decode("utf-8") if res is not None: obj.create_table(res) key=random.randint(100000, 1000000) key=self.crypt.encrypt(str(key), public_key) await loop.sock_sendall(conn, str.encode(key)) result=obj.check_table(res, username, password) if not result: obj.group_entry(res, username, password, key) conn.close()
def test_decrypt_encrypt(self, p, q, e, m): rsa = RSA(p, q, e) self.assertEqual(m, rsa.decrypt(rsa.encrypt(m)))
import binascii from rsa import RSA rsa = RSA() plaintext_1 = 42 ciphertext_1 = rsa.encrypt(42) decrypted_1 = rsa.decrypt(ciphertext_1) print(plaintext_1, ciphertext_1, decrypted_1) plaintext_2 = "attack" number = int(binascii.hexlify(plaintext_2.encode()), 16) ciphertext_2 = rsa.encrypt(number) decrypted_2 = rsa.decrypt(ciphertext_2) string = binascii.unhexlify(hex(decrypted_2)[2:]).decode() print(plaintext_2, ciphertext_2, string)
def make(self,msg,key): pkcs15 = PKCS15() rsa = RSA() dgst = hashlib.sha1(message).digest() #计算msg的sha1 paddgst = pkcs15.pad(dgst,len(i2s(key[1]))) #把sha1进行填充,填充函数在前面有解释 return rsa.encrypt(paddgst,key) #调用rsa加密的方法进行加密,c39中有rsa的算法
from rsa import RSA import src.hub as hub """ Universidade Federal de Alagoas - UFAL Programa para criptografia RSA da matéria de Matemática Discreta Participantes: - Ana Ferreira - Frederico Guilherme - Lucas Tenório - Phyllipe Bezerra - Rafael Augusto """ if __name__ == "__main__": # Opção selecionada no menu option = hub.menu() rsa = RSA() if option == 1: print("\n[1] Gerar chave pública") rsa.generate_key() elif option == 2: print("\n[2] Criptografar") rsa.encrypt() elif option == 3: print("\n[3] Descriptografar") rsa.decrypt() else: exit(1)
return last_r, last_x * (-1 if a < 0 else 1), last_y * (-1 if m < 0 else 1) def modinv(a, m): g, x, y = extended_gcd(a, m) if g != 1: raise ValueError return x % m plaintext = b'text Jun3 bug!' ciphertexts = [] for _ in range(3): cipher = RSA(150) ciphertexts.append([cipher.encrypt(plaintext), cipher.n]) (c_0, n_0), (c_1, n_1), (c_2, n_2) = ciphertexts c_0, c_1, c_2 = int.from_bytes(c_0, 'big'), int.from_bytes(c_1, 'big'),\ int.from_bytes(c_2, 'big') ms_0, ms_1, ms_2 = n_1 * n_2, n_0 * n_2, n_0 * n_1 result = ((c_0 * ms_0 * modinv(ms_0, n_0)) + (c_1 * ms_1 * modinv(ms_1, n_1)) +\ (c_2 * ms_2 * modinv(ms_2, n_2))) result = result % (n_0 * n_1 * n_2) lo, hi = 0, result while lo < hi: mid = (lo + hi) // 2 if mid**3 < result: lo = mid + 1
class MainWindow(QMainWindow): def __init__(self): super(MainWindow, self).__init__() loadUi(os.getcwd() + '/gui.ui', self) self.constraint_input() self.connect_buttons() self.elgamal = Elgamal() self.rsa = RSA() self.dh = DiffieHellman() self.mode = None self.format = None def constraint_input(self): self.onlyInt = QIntValidator() self.RSA_key_e_value.setValidator(self.onlyInt) self.RSA_key_d_value.setValidator(self.onlyInt) self.RSA_key_n_value.setValidator(self.onlyInt) self.RSA_sess_n_value.setValidator(self.onlyInt) self.RSA_sess_g_value.setValidator(self.onlyInt) self.RSA_sess_x_value.setValidator(self.onlyInt) self.RSA_sess_y_value.setValidator(self.onlyInt) self.EG_key_p_value.setValidator(self.onlyInt) self.EG_key_g_value.setValidator(self.onlyInt) self.EG_key_x_value.setValidator(self.onlyInt) self.EG_key_y_value.setValidator(self.onlyInt) self.EG_sess_n_value.setValidator(self.onlyInt) self.EG_sess_g_value.setValidator(self.onlyInt) self.EG_sess_x_value.setValidator(self.onlyInt) self.EG_sess_y_value.setValidator(self.onlyInt) self.RSA_output_text.setReadOnly(True) self.EG_output_text.setReadOnly(True) def connect_buttons(self): # Main menu buttons self.rsabutton.clicked.connect( lambda: self.stackedWidget.setCurrentIndex(1)) self.egbutton.clicked.connect( lambda: self.stackedWidget.setCurrentIndex(2)) # RSA buttons self.RSA_key_savebutton.clicked.connect(self.rsa_save_key) self.RSA_act_execbutton.clicked.connect(self.rsa_execute) self.RSA_key_genbutton.clicked.connect(self.rsa_generate_key) self.RSA_key_filebutton.clicked.connect(self.rsa_import_key) self.RSA_act_decbutton.clicked.connect(self.set_mode_dec) self.RSA_act_encbutton.clicked.connect(self.set_mode_enc) self.RSA_input_filebutton.clicked.connect(self.rsa_get_input_file) self.RSA_fmt_txtbutton.clicked.connect(self.set_format_txt) self.RSA_fmt_filebutton.clicked.connect(self.set_format_file) self.RSA_returnbutton.clicked.connect( lambda: self.stackedWidget.setCurrentIndex(0)) self.RSA_sess_genbutton.clicked.connect( self.rsa_diffiehellman_generate_key) # Elgamal buttons self.EG_key_savebutton.clicked.connect(self.elgamal_save_key) self.EG_act_execbutton.clicked.connect(self.elgamal_execute) self.EG_key_genbutton.clicked.connect(self.elgamal_generate_key) self.EG_key_filebutton.clicked.connect(self.elgamal_import_key) self.EG_act_decbutton.clicked.connect(self.set_mode_dec) self.EG_act_encbutton.clicked.connect(self.set_mode_enc) self.EG_input_filebutton.clicked.connect(self.elgamal_get_input_file) self.EG_fmt_txtbutton.clicked.connect(self.set_format_txt) self.EG_fmt_filebutton.clicked.connect(self.set_format_file) self.EG_returnbutton.clicked.connect( lambda: self.stackedWidget.setCurrentIndex(0)) self.EG_sess_genbutton.clicked.connect( self.eg_diffiehellman_generate_key) # DIFFIE HELMAN STUFF def rsa_diffiehellman_generate_key(self): self.dh.generate_parameters() n, g, x, y = self.dh.get_parameters() self.RSA_sess_n_value.setText(str(n)) self.RSA_sess_g_value.setText(str(g)) self.RSA_sess_x_value.setText(str(x)) self.RSA_sess_y_value.setText(str(y)) sess_key = self.dh.get_session_key() self.RSA_sess_result.setText(str(sess_key)) def eg_diffiehellman_generate_key(self): self.dh.generate_parameters() n, g, x, y = self.dh.get_parameters() self.EG_sess_n_value.setText(str(n)) self.EG_sess_g_value.setText(str(g)) self.EG_sess_x_value.setText(str(x)) self.EG_sess_y_value.setText(str(y)) sess_key = self.dh.get_session_key() self.EG_sess_result.setText(str(sess_key)) # RSA STUFF def rsa_save_key(self): fileNamePub, _ = QFileDialog.getSaveFileName( None, "Save RSA Public Key", "", "Public Key File (*.pub)") fileNamePri, _ = QFileDialog.getSaveFileName( None, "Save RSA Private Key", "", "Private Key File (*.pri)") # self.rsa.generate_key() self.rsa.save_generated_keys(fileNamePub, fileNamePri) def rsa_set_public_key(self): e = int(self.RSA_key_e_value.text()) n = int(self.RSA_key_n_value.text()) self.rsa.set_public_key(e, n) def rsa_set_private_key(self): d = int(self.RSA_key_d_value.text()) n = int(self.RSA_key_n_value.text()) self.rsa.set_private_key(d, n) def rsa_execute(self): self.rsa_set_public_key() self.rsa_set_private_key() st = time.time() if self.mode == 'enc': if self.format == 'txt': self.rsa.get_input( bytes(self.RSA_input_text.toPlainText(), 'UTF-8', errors='ignore')) self.rsa.encrypt() self.RSA_output_text.setText(self.rsa.get_cipher_text()) # print("RSA get cipher text: ", bytes(self.rsa.get_cipher_text(), 'UTF-8')) elif self.format == 'file': if self.rsa_inpfile == None: self.display_value_error("File belum dipilih") return assert self.rsa_inpfile is not None self.rsa.enc_from_file(self.rsa_inpfile) self.rsa.encrypt() fileName, _ = QFileDialog.getSaveFileName( None, "Save Encrypted File", "", "All Files (*)") print("tes({})".format(fileName)) if fileName == "": return self.rsa.enc_write_file(fileName) # Print file size self.RSA_size_value.setText( str(os.path.getsize(fileName) / 1000)) else: self.display_value_error("Format belum dipilih") return elif self.mode == 'dec': if self.format == 'txt': check = self.RSA_input_text.toPlainText() print("RSA_input toPlainText ", check) print("length of text = {}".format(len(check))) for c in check: print(c, end='') print() self.rsa.get_input( bytes(self.RSA_input_text.toPlainText(), 'UTF-8', errors='ignore')) self.rsa.parse_msg_to_enc() self.rsa.decrypt() self.RSA_output_text.setText(self.rsa.get_plain_text()) elif self.format == 'file': if self.rsa_inpfile == None: self.display_value_error("File belum dipilih") return assert self.rsa_inpfile is not None self.rsa.dec_from_file(self.rsa_inpfile) self.rsa.decrypt() fileName, _ = QFileDialog.getSaveFileName( None, "Save Encrypted File", "", "All Files (*)") print("tes({})".format(fileName)) if fileName == "": return self.rsa.dec_write_file(fileName) # Print file size self.RSA_size_value.setText( str(os.path.getsize(fileName) / 1000)) else: self.display_value_error("Format belum dipilih") return else: self.display_value_error("Aksi belum dipilih") return end = str(time.time() - st) # Set time execution self.RSA_time_value.setText(end) def rsa_generate_key(self): self.rsa.generate_key() d, n1 = self.rsa.get_private_key() e, n2 = self.rsa.get_public_key() assert n1 == n2 self.RSA_key_n_value.setText(str(n1)) self.RSA_key_d_value.setText(str(d)) self.RSA_key_e_value.setText(str(e)) def rsa_import_key(self): fileNamePub, _ = QFileDialog.getOpenFileName( None, "Import RSA Public Key", "", "Public Key File (*.pub)") fileNamePri, _ = QFileDialog.getOpenFileName( None, "Import RSA Private Key", "", "Private Key File (*.pri)") self.rsa.import_public_key(fileNamePub) self.rsa.import_private_key(fileNamePri) # display the imported key in the text box d, n1 = self.rsa.get_private_key() e, n2 = self.rsa.get_public_key() assert n1 == n2 self.RSA_key_n_value.setText(str(n1)) self.RSA_key_d_value.setText(str(d)) self.RSA_key_e_value.setText(str(e)) def rsa_get_input_file(self): fileName, _ = QFileDialog.getOpenFileName(None, "Get Input File", "", "All Files (*)") self.rsa_inpfile = fileName fileName = fileName.split('/')[-1] self.RSA_inp_file_label.setText("Chosen file: {}".format(fileName)) # ELGAMAL STUFF def elgamal_save_key(self): fileNamePub, _ = QFileDialog.getSaveFileName( None, "Save Elgamal Public Key", "", "Public Key File (*.pub)") fileNamePri, _ = QFileDialog.getSaveFileName( None, "Save Elgamal Private Key", "", "Private Key File (*.pri)") self.elgamal.generate_key() self.elgamal.save_generated_keys(fileNamePub, fileNamePri) def elgamal_set_public_key(self): p = int(self.EG_key_p_value.text()) g = int(self.EG_key_g_value.text()) y = int(self.EG_key_y_value.text()) self.elgamal.set_public_key(p, g, y) def elgamal_set_private_key(self): p = int(self.EG_key_p_value.text()) x = int(self.EG_key_x_value.text()) self.elgamal.set_private_key(p, x) def elgamal_execute(self): self.elgamal_set_public_key() self.elgamal_set_private_key() st = time.time() if self.mode == 'enc': if self.format == 'txt': self.elgamal.get_input( bytes(self.EG_input_text.toPlainText(), 'UTF-8', errors='ignore')) self.elgamal.encrypt() self.EG_output_text.setText(self.elgamal.get_cipher_text()) elif self.format == 'file': self.elgamal.enc_from_file(self.elgamal_inpfile) self.elgamal.encrypt() fileName, _ = QFileDialog.getSaveFileName( None, "Save Encrypted File", "", "All Files (*)") self.elgamal.enc_write_file(fileName) # Print file size self.EG_size_value.setText( str(os.path.getsize(fileName) / 1000)) else: self.display_value_error("Format belum dipilih") return elif self.mode == 'dec': if self.format == 'txt': self.elgamal.get_input( bytes(self.EG_input_text.toPlainText(), 'UTF-8', errors='ignore')) self.elgamal.parse_msg_to_enc() self.elgamal.decrypt() self.EG_output_text.setText(self.elgamal.get_plain_text()) elif self.format == 'file': self.elgamal.dec_from_file(self.elgamal_inpfile) self.elgamal.decrypt() fileName, _ = QFileDialog.getSaveFileName( None, "Save Encrypted File", "", "All Files (*)") self.elgamal.dec_write_file(fileName) # Print file self.EG_size_value.setText( str(os.path.getsize(fileName) / 1000)) else: self.display_value_error("Format belum dipilih") return else: self.display_value_error("Aksi belum dipilih") return end = str(time.time() - st) # Set time execution self.EG_time_value.setText(end) def elgamal_get_input_file(self): fileName, _ = QFileDialog.getOpenFileName(None, "Get Input File", "", "All Files (*)") self.elgamal_inpfile = fileName fileName = fileName.split('/')[-1] self.EG_inp_file_label.setText("Chosen file: {}".format(fileName)) def elgamal_import_key(self): fileNamePub, _ = QFileDialog.getOpenFileName( None, "Import Elgamal Public Key", "", "Public Key File (*.pub)") fileNamePri, _ = QFileDialog.getOpenFileName( None, "Import Elgamal Private Key", "", "Private Key File (*.pri)") self.elgamal.import_public_key(fileNamePub) self.elgamal.import_private_key(fileNamePri) def elgamal_generate_key(self): self.elgamal.generate_key() g, y, p = self.elgamal.get_public_key() x, p = self.elgamal.get_private_key() self.EG_key_p_value.setText(str(p)) self.EG_key_g_value.setText(str(g)) self.EG_key_x_value.setText(str(x)) self.EG_key_y_value.setText(str(y)) # OTHER STUFF def set_mode_enc(self): self.mode = 'enc' def set_mode_dec(self): self.mode = 'dec' def set_format_txt(self): self.format = 'txt' def set_format_file(self): self.format = 'file' # VALIDATION STUFF def display_value_error(self, err_msg: str): msg = QMessageBox() msg.setIcon(QMessageBox.Warning) msg.setText("Error") msg.setInformativeText(err_msg) msg.setWindowTitle("Error") msg.setStandardButtons(QMessageBox.Ok) retval = msg.exec_()
def make(self, msg, key): pkcs15 = PKCS15() rsa = RSA() dgst = hashlib.sha1(message).digest() #计算msg的sha1 paddgst = pkcs15.pad(dgst, len(i2s(key[1]))) #把sha1进行填充,填充函数在前面有解释 return rsa.encrypt(paddgst, key) #调用rsa加密的方法进行加密,c39中有rsa的算法