class MainWindow(QMainWindow, ui.Ui_MainWindow): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.setupUi(self) p = 33478071698956898786044169848212690817704794983713768568912431388982883793878002287614711652531743087737814467999489 q = 36746043666799590428244633799627952632279158164343087642676032283815739666511279233373417143396810270092798736308917 self.rsa = RSA(p, q) self.connect(self.button_e, SIGNAL("clicked()"), self.encrypt) self.connect(self.button_d, SIGNAL("clicked()"), self.decrypt) #self.connect(self.button_e, SIGNAL("clicked()"), lambda:QMessageBox.information(self,"No",u"浮云")) def encrypt(self): message = unicode(self.line_e_m.text()).strip() if not message: QMessageBox.critical(self, u"错误", u"请输入明文") else: ciphertext = self.rsa.encryptString(message) self.text_e_c.setPlainText(QString(unicode(ciphertext))) def decrypt(self): ciphertext = unicode(self.text_d_c.toPlainText()).strip() if not ciphertext: QMessageBox.critical(self, u"错误", u"请输入密文") else: try: message = self.rsa.decrypt(ciphertext) except: self.line_d_m.setText(u"无法解密该密文") else: self.line_d_m.setText(unicode(message))
def main(): global modN global keyE if not len(sys.argv) == 2: print "Usage: python client.py PORT_NUM" os._exit(os.EX_OK) port = int(sys.argv[1]) nthPrime = input("Enter nth prime: ") mthPrime = input("Enter mth prime: ") while nthPrime == mthPrime: print "You cannot use the same number" mthPrime = input("Enter mth prime: ") rsa = RSA(nthPrime, mthPrime) rsa.generateKeys() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("localhost", port)) print "Type .bye to exit" #send keys publicKeys = str(rsa.publicKeyN) + "#" + str(rsa.publicKeyE) s.send(publicKeys) #receive keys keys = s.recv(2048) keys = keys.split("#") modN = int(keys[0]) keyE = int(keys[1]) x = Thread(target=read, args=(s, rsa)) t = Thread(target=write, args=(s, rsa)) x.start() t.start() t.join() s.close() os._exit(os.EX_OK)
def check_invoice(signed_invoice): """Check if the configparser instance is a signed invoice. If not exit.""" seller_sign_key = os.path.join(os.path.join(tools.DIR_SELLER, tools.FILE_PUB_SIGN)) bank_pukf = os.path.join(tools.DIR_BANK, tools.FILE_PUB_KEY) pub_cp = tools.decode_public_key(seller_sign_key, bank_pukf, tools.ROLE_BANK) tools.check_config(pub_cp, tools.STRCT_PUB_KEY) pub_k = RSA(int(pub_cp[tools.SCT_K_KEY][tools.OPT_K_N]), e=int(pub_cp[tools.SCT_K_KEY][tools.OPT_K_E])) check = pub_k.check_signature(signed_invoice[tools.ROLE_SELLER][tools.OPT_S_SIGN]) tmp = open(tools.TMP_FILE, 'w') tmp.write(check) tmp.close() invoice_cp = ConfigParser() invoice_cp.read(tools.TMP_FILE) os.remove(tools.TMP_FILE) tools.check_config(invoice_cp, tools.STRCT_INVOICE) return invoice_cp
def main(): global modN global keyE if len(sys.argv) != 2: print "Usage: python server.py PORT_NUM" os._exit(os.EX_OK) port = int(sys.argv[1]) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(("", port)) s.listen(1) nthPrime = input("Enter nth prime: ") mthPrime = input("Enter mth prime: ") while nthPrime == mthPrime: print "You cannot use the same number" mthPrime = input("Enter mth prime: ") rsa = RSA(nthPrime, mthPrime) rsa.generateKeys() print "waiting to accept" channel, details = s.accept() print "Type .bye to exit" #read keys keys = channel.recv(2048) keys = keys.split("#") modN = int(keys[0]) keyE = int(keys[1]) #send keys to client publicKeys = str(rsa.publicKeyN) + "#" + str(rsa.publicKeyE) channel.send(publicKeys) t = Thread(target=read, args=(channel, rsa)) x = Thread(target=write, args=(channel, rsa)) x.start() t.start() x.join() channel.close() os._exit(os.EX_OK)
class oracle: def __init__(self): self.rsa = RSA() self.pub, self.private = self.rsa.keygen(l=512) def getPubKey(self): return self.pub def isEven(self, num): return ord(self.rsa.decrypt(num, self.private)[-1]) & 1 == 0
def Alice2Bob(newpassword): if 0 > newpassword or newpassword > maxPW: raise ValueError("Password must be between 0 and {}".format(maxPW)) rsa = RSA() rsa.from_message_bit_length(maxPW.bit_length()) #rsa.from_given_pqe(61,53,17,opt=0) rsa_encrypted_newpassword = rsa.public.encrypt(newpassword) rsa_decrypted_newpassword = rsa.private.decrypt(rsa_encrypted_newpassword) print( "newpassword:"******"\nrsa_encrypted_newpassword:"******"\nrsa_decrypted_newpassword:",rsa_decrypted_newpassword ) return
def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.setupUi(self) p = 33478071698956898786044169848212690817704794983713768568912431388982883793878002287614711652531743087737814467999489 q = 36746043666799590428244633799627952632279158164343087642676032283815739666511279233373417143396810270092798736308917 self.rsa = RSA(p, q) self.connect(self.button_e, SIGNAL("clicked()"), self.encrypt) self.connect(self.button_d, SIGNAL("clicked()"), self.decrypt)
def gen_invoice(buyer, seller, total): # Generation of the transaction id random.seed(os.urandom(SEED_LENGTH)) transac_id = hex(random.getrandbits(TRANSACTION_ID_LENGTH))[2:] add_invoice_db(transac_id, total) invoice_cp = ConfigParser() # Generate the invoice invoice_cp.add_section(tools.SCT_I_INVOICE) invoice_cp[tools.SCT_I_INVOICE] = {tools.OPT_I_SELLER: tools.ROLE_SELLER, tools.OPT_I_BUYER: buyer, tools.OPT_I_TOTAL: total, tools.OPT_I_TRANS_ID: transac_id} invoice_fname = buyer + "_" + transac_id + tools.EXT_INVOICE invoice_fname = os.path.join(tools.DIR_SELLER, tools.DIR_INVOICE, invoice_fname) with open(invoice_fname, 'w') as invoice_file: invoice_cp.write(invoice_file) str = "" invoice = open(invoice_fname, 'r') invoice_content = invoice.read() invoice.close() pri_cp = ConfigParser() pri_cp.read(os.path.join(tools.DIR_SELLER, tools.FILE_PRI_KEY)) pri_k = RSA(int(pri_cp[tools.SCT_K_KEY][tools.OPT_K_N]), d=int(pri_cp[tools.SCT_K_KEY][tools.OPT_K_D])) sign_inv = ConfigParser() sign_content = pri_k.sign(invoice_content) sign_inv[tools.ROLE_SELLER] = {tools.OPT_S_SIGN: sign_content} sign_inv.write(sys.stdout)
def __init__(self, parent=None): # RSA self.rsa = RSA() QtGui.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.btnGenerate.clicked.connect(self.generateKeys) self.ui.btnEncMessage.clicked.connect(self.createEncryptMsgDialog) self.ui.btnEncFile.clicked.connect(self.createEncryptFileDialog) self.generateKeys() self.ui.textPublicKey_n.textChanged.connect(self.onPublicKeyChanged) self.ui.textPublicKey_e.textChanged.connect(self.onPublicKeyChanged) self.ui.textPrivateKey.textChanged.connect(self.onPrivateKeyChanged)
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)))
class MainDialog(QtGui.QDialog): def __init__(self, parent=None): # RSA self.rsa = RSA() QtGui.QWidget.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.btnGenerate.clicked.connect(self.generateKeys) self.ui.btnEncMessage.clicked.connect(self.createEncryptMsgDialog) self.ui.btnEncFile.clicked.connect(self.createEncryptFileDialog) self.generateKeys() self.ui.textPublicKey_n.textChanged.connect(self.onPublicKeyChanged) self.ui.textPublicKey_e.textChanged.connect(self.onPublicKeyChanged) self.ui.textPrivateKey.textChanged.connect(self.onPrivateKeyChanged) def generateKeys(self): self.rsa.genKeys() n,e = self.rsa.getPublicKey() self.ui.textPublicKey_n.setText(str(n)) self.ui.textPublicKey_e.setText(str(e)) self.ui.textPrivateKey.setText(str(self.rsa.getPrivateKey())) def createEncryptMsgDialog(self): encryptDialog = EncryptDialog(self.rsa, self) encryptDialog.show() def createEncryptFileDialog(self): encryptFileDialog = EncryptFileDialog(self.rsa, self) encryptFileDialog.show() def onPublicKeyChanged(self): try: n = int(self.ui.textPublicKey_n.toPlainText()) e = int(self.ui.textPublicKey_e.toPlainText()) self.rsa.setPublicKey(n, e) except: print('Error.') def onPrivateKeyChanged(self): try: d = int(self.ui.textPrivateKey.toPlainText()) self.rsa.setPrivateKey(d) except: print('Invalid Key')
cheque_fname = os.path.join(tools.DIR_CUSTOMERS, real_drawer, tools.DIR_CHQ_ISSUED, cheque_fname) if os.path.exists(cheque_fname) and os.path.isfile(cheque_fname): print(ALREADY_PAID, file=sys.stderr) exit(1) cheque_cp = ConfigParser() cheque_cp.add_section(tools.SCT_C_CHEQUE) cheque_cp.set(tools.SCT_C_CHEQUE, tools.OPT_C_DRAWER, drawer) cheque_cp.set(tools.SCT_C_CHEQUE, tools.OPT_C_TOTAL, total) cheque_cp.set(tools.SCT_C_CHEQUE, tools.OPT_C_PAYEE, payee) cheque_cp.set(tools.SCT_C_CHEQUE, tools.OPT_C_TRANS_ID, transac_id) with open(cheque_fname,'w') as cheque_f: cheque_cp.write(cheque_f) cheque_f = open(cheque_fname, 'r') cheque_content = cheque_f.read() pri_cp = ConfigParser() pri_cp.read(os.path.join(tools.DIR_CUSTOMERS, real_drawer, tools.FILE_PRI_KEY)) pri_k = RSA(int(pri_cp[tools.SCT_K_KEY][tools.OPT_K_N]), d=int(pri_cp[tools.SCT_K_KEY][tools.OPT_K_D])) sign = pri_k.sign(cheque_content) sign_cp = ConfigParser() sign_cp[real_drawer] = {tools.OPT_S_SIGN: str(sign)} sign_cp.write(sys.stdout)
#设置变量精度 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
def setkey(self, key): self.key = key self.cipher = RSA(key) key.dump()
class InteractiveShell(cmd.Cmd): intro = '\n type `exit` or `q` to exit (or Ctrl-D in UNIX environment, Ctrl-Z in Windows)\n type `help` or `?` to see usage\n' prompt = 'RSA > ' def __init__(self): cmd.Cmd.__init__(self) self.config = { "e": '65537' } key = RSAKey(bits=1024, e=int(self.config['e'])) print('Default key generated (1024 bits)') self.setkey(key) self.last = None def setkey(self, key): self.key = key self.cipher = RSA(key) key.dump() def do_q(self, line): """ quit """ return True def do_exit(self, line): """ quit """ return True def do_EOF(self, line): """ quit """ return True def do_set(self, line): """ set key val available key: e public exponent """ try: key, val = line.split() except ValueError: print('error while parsing arguments') return if not key: print('key can not be empty') return self.config[key] = val def do_get(self, key): """ get key available key: e public exponent """ if not key: print('key can not be empty') return print('%s: %r' % (key, self.config.get(key, None))) def complete_enc(self, *args): return self.complete_filename(*args) def do_enc(self, file): """ enc [file] keep file empty to read data form stdin """ if not file: data = input('Data to encrypt:') else: try: data = open(file, 'rb').read() except: print('Can not open file %r' % file) return c = self.cipher.encrypt_data(data) self.last = c print('Source data: %r...' % data[:256]) print('Encrypted: %r...' % enhex(c[:256])) def complete_dec(self, *args): return self.complete_filename(*args) def do_dec(self, file): """ dec [file] keep file empty to read data from stdin """ if not file: data = input('Data to decrypt in hex:') try: data = unhex(data) except: print('Read input error') return else: try: data = open(file, 'rb').read() except: print('Can not open file %r' % file) return t, m = profile(lambda: self.cipher.decrypt_data(data)) self.last = m print('%g ms used' % (t * 1000)) print('Source data: %r...' % data[:256]) print('Decrypted: %r...' % m[:256]) def do_keygen(self, bits): """ keygen [bits=1024] """ if not bits: bits = 1024 try: bits = int(bits) except: print('Invalid number') return if bits > 2048: print('You are generating long RSA keypair, it may take some while.') print('Interrupt by Ctrl-C') try: key = RSAKey(bits=bits, e=int(self.config['e'])) self.setkey(key) except ValueError: print('Can not generate key') except KeyboardInterrupt: print('Canceld') def do_simplify(self, line): """ simplify strip unnecessary fields of RSAKey. (this operation will disable CRT decryption optimize) """ self.setkey(self.key.simplify()) def do_prime(self, bits): """ prime bits generate a prime with n-bits length """ print(prime.randprime_bits(int(bits))) def do_dump(self, file): """ dump [file] print last result or save last reuslt to file """ if not self.last: print('Nothing in last result') return if file: try: open(file, 'wb').write(self.last) except: print('Can not save file') else: print(enhex(self.last) if type(self.last) is Bytes else self.last) def do_dumpstr(self, line): """ dumpstr print last result as string """ if not self.last: print('Nothing in last result') return else: print(repr(self.last)) def complete_loadkey(self, *args): return self.complete_filename(*args) def do_loadkey(self, file): """ loadkey [file] read key from file or read JSON-format key from stdin """ if file: try: json_data = open(file, 'rb').read() except: print('Can not read file') return else: json_data = input('Input JSON-format key:') try: key = RSAKey.from_json(json_data) except Exception as e: print('Can not load key, Error show below:') print(e) return self.setkey(key) print('Key loaded') def complete_filename(self, text, line, begidx, endidx): arg = line.split()[1:] if not arg: completions = os.listdir('./') else: dirname, part, base = arg[-1].rpartition('/') if part == '': dirname = './' elif dirname == '': dirname = '/' completions = [] for f in os.listdir(dirname): if f.startswith(base): if os.path.isfile(os.path.join(dirname,f)): completions.append(f) else: completions.append(f+'/') return completions def do_dumpkey(self, file): """ dumpkey [file] dump key to file or stdout """ if file: try: data = self.key.to_json() open(file, 'w').write(data) print('Key dumped to file %s' % file) except: print('Can not dump key to file') else: print(self.cipher.key.as_dict()) self.key.dump()
def verify(self,msg,sign,key): pkcs15 = PKCS15() rsa = RSA() dgst = hashlib.sha1(message).digest() return pkcs15.unpad("\x00"+rsa.decrypt(sign,key)) == dgst #把密文sign和key通过解密函数解密出来,然后在填充之后的包里把msg恢复出来对比一下
def chat(self, data): """接收聊天信息并打印""" sender = data['from'] receiver = data['to'] logArea = self.father.logArea log = ctime() + " Receive Message\n\n" encryptedMessage = data['encryptedMessage'] encryptedKey = data['encryptedKey'] signature = data['signature'] senderPubKey = data['senderPubKey'] decryptionType = self.father.father.selfInfo['decryptionType'] # message = '' r = RSA(0) priKey = self.father.father.selfInfo['priKey'] key = r.decryption(encryptedKey, priKey) if self.father.father.selfInfo['communicationType'] == 'rsa': # priKey = self.father.father.selfInfo['priKey'] if len(encryptedMessage) > 5: result = r.verify(encryptedMessage[0:6], signature, senderPubKey) else: result = r.verify(encryptedMessage, signature, senderPubKey) if result: log += ctime() + " Verify Successfully\n\n" # father.father.logArea.insert(tk.END) key = r.decryption(encryptedKey, priKey) if decryptionType == 'caesar': c = Caesar() key = int(key) message = c.decryption(encryptedMessage, key) # pass elif decryptionType == 'playfair': p = Playfair(0) p.generateMatrix(key) message = p.decryption(encryptedMessage) # pass elif decryptionType == 'des': d = des() message = d.decrypt(key, encryptedMessage) else: d = des() less = data['less'] # print("--------------------",key1, key2, encryptedMessage) message = d.tdecrypt(key[2:10], key[14:22], encryptedMessage) message = message[0:-less] # print("--------------------",message) # pass else: # 输出不合格 pass else: r = RSA(0) if len(encryptedMessage) > 5: result = r.verify(encryptedMessage[0:6], signature, senderPubKey) else: result = r.verify(encryptedMessage, signature, senderPubKey) if result: log += ctime() + " Verify Successfully\n\n" if decryptionType == 'caesar': key = self.father.father.selfInfo['key'] c = Caesar(key) ct, secretKey = c.encryption('aaa') message = c.decryption(encryptedMessage[0], secretKey) print('-----------pass') elif decryptionType == 'playfair': p = Playfair(0) p.generateMatrix(key) message = p.decryption(encryptedMessage) elif decryptionType == 'des': d = des() message = d.decrypt(key, encryptedMessage) else: d = des() less = data['less'] message = d.tdecrypt(key[2:10], key[14:22], encryptedMessage) message = message[0:-less] # pass else: print('-----------not pass') pass # print("i am here") textArea = self.father.textArea text = '['+ sender + ' -> ' + receiver + ' ' + \ ctime() + ']\n\t' + message + '\n' textArea.insert(tk.END, text) textArea.see(tk.END) logArea.insert(tk.END, log) logArea.see(tk.END) print("i am here")
def verify(self, msg, sign, key): pkcs15 = PKCS15() rsa = RSA() dgst = hashlib.sha1(message).digest() return pkcs15.unpad("\x00" + rsa.decrypt( sign, key)) == dgst #把密文sign和key通过解密函数解密出来,然后在填充之后的包里把msg恢复出来对比一下
def __init__(self): self.rsa = RSA() self.pub, self.private = self.rsa.keygen(l=512)
import requests from rsa import RSA import json key_req = requests.get( 'http://asymcryptwebservice.appspot.com/rsa/serverKey?keySize=256') n1 = key_req.text n1 = int(json.loads(n1)['modulus'], 16) e1 = key_req.text e1 = int(json.loads(e1)['publicExponent'], 16) a = RSA(256, 'A') a.GenerateKeyPair() a.log += f"Отримані Modulus та publicExponent: n1 = {n1} , e1 ={e1}\n" while a.o_key[1] > n1: a = RSA(256, 'A') a.GenerateKeyPair() k1, s1 = a.SendKey(e1, n1) e, n = a.o_key request = f"http://asymcryptwebservice.appspot.com/rsa/receiveKey?key={hex(k1)[2:]}&signature={hex(s1)[2:]}&modulus={hex(n)[2:]}&publicExponent={hex(e)[2:]}" a.log += "Перевірка на сайті :\n" a.log += requests.get(request, cookies=key_req.cookies).text sendKey = open('sendKey.txt', 'w', encoding="utf8") sendKey.write(a.log)
class Communicator: def __init__(self, config, register_agent): self.HOST = "" self.config = config self.register_agent = register_agent self.connect_spawn_loop = True self.server_wait = True self.TIMEOUT = 1 self.SERVER_TIMEOUT = 1 self.THREAD_STAY_ALIVE = False self.QUIT = False self.rsa = RSA() # listen for other user's name on socket def recv_other_data(self, sock): other_data = None while not other_data: # TODO maybe stop after a few tries other_data = sock.recv(1024) split_data = other_data.split(":") other_name = split_data[0] pubkey = (int(split_data[1]), int(split_data[2])) return (other_name, pubkey) # get an rsa object god this needs refactoring, also gen keypair def rsa_gen_keypair(self): self.rsa.gen_keypair() self.n, self.e = self.rsa.get_public_key() # wait for a connection, and send our name on it def wait_connection(self): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((self.HOST, C.CLIENT_MAIN_PORT)) sock.listen(1) # wait for an incoming connection # TODO loop on timeout, allow user to kill sock.settimeout(self.SERVER_TIMEOUT) self.server_wait = True conn = None while self.server_wait: try: conn, addr = sock.accept() self.server_wait = False except: continue # close original listen socket sock.close() # if no connection was established, return failure if conn is None: return (None, None) conn.settimeout(self.TIMEOUT) # wait for other user's name other_name, pub_key = self.recv_other_data(conn) self.rsa.get_other_pub_key(pub_key) # send our name back to other user data = self.config.name + ":" + str(self.n) + ":" + str(self.e) conn.sendall(data) return (conn, other_name) # attempt to make a connection, and send our name on it def attempt_connection(self, ip): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((self.HOST, C.CLIENT_MAIN_PORT)) sock.settimeout(1) if self.register_agent.CONNECTED: if len(ip.split(".")) != 4: # this is a name, not an IP, so search userlist for addr in self.register_agent.userlist.keys(): if self.register_agent.userlist[addr][0] == ip: ip = addr try: sock.connect((ip, C.CLIENT_MAIN_PORT)) except: # return None tuple on failure sock.close() return (None, None) sock.settimeout(self.TIMEOUT) #send data to the other user data = self.config.name + ":" + str(self.n) + ":" + str(self.e) sock.sendall(data) # wait for their name in return other_name, pub_key = self.recv_other_data(sock) self.rsa.get_other_pub_key(pub_key) return (sock, other_name)
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的算法
customers.append(sys.argv[2+i]) except IndexError: print("Missing customer name", sys.stderr) exit(1) return customers if __name__ == "__main__": customers_lst = parsing_arguments() # Creating the bank print("Creation of the Bank ", end="",flush=True) os.mkdir(tools.DIR_BANK) keys = RSA.generate_keys() RSA.store_key(tools.DIR_BANK, keys[RSA.private], keys[RSA.public]) print(DONE) rsa_bank = RSA(keys[RSA.private][RSA.modulus], d=keys[RSA.private][RSA.private_exponent]) # Creating the customers os.mkdir(tools.DIR_CUSTOMERS) customers_list = [] for customer in customers_lst: print("Creation of the customer " + customer, end=" ", flush=True) # Creation of the customer's path directory = os.path.join(tools.DIR_CUSTOMERS, customer)
def send(self, data): receiverCertificate = data['certificate'] inputEntry = self.father.inputEntry message = inputEntry.get() sender = self.father.father.username receiver = receiverCertificate['username'] encryptionType = receiverCertificate['encryptionType'] receiverPublicKey = receiverCertificate['publicKey'] communicationType = receiverCertificate['communicationType'] less = 0 logArea = self.father.logArea log = ctime() + " Receive Certificate\n\n" if communicationType == 'rsa': log += ctime() + " Communication Type: RSA\n\n" # logArea.insert(tk.END, log + '\n\n') # logArea.see(tk.END) if encryptionType == 'caesar': # encryption = Caesar() c = Caesar() cypherText, key = c.encryption(message) r = RSA(0) encryptedKey = r.encryption(key, receiverPublicKey) # print(cypherText, self.father.father.selfInfo['priKey']) if len(cypherText) > 5: signature = r.sign( cypherText[0:6], self.father.father.selfInfo['priKey']) else: signature = r.sign( cypherText, self.father.father.selfInfo['priKey']) data = { 'type': 'singleChat', 'encryptedMessage': cypherText, 'encryptedKey': encryptedKey, 'signature': signature, 'to': receiver, 'from': sender } log += ctime() + " Encryption Type: Caesar\n\n" # logArea.insert(tk.END, log + '\n\n') # logArea.see(tk.END) elif encryptionType == 'playfair': p = Playfair() cypherText, key = p.encryption(message) r = RSA(0) encryptedKey = r.encryption(key, receiverPublicKey) if len(cypherText) > 5: signature = r.sign( cypherText[0:6], self.father.father.selfInfo['priKey']) else: signature = r.sign( cypherText, self.father.father.selfInfo['priKey']) data = { 'type': 'singleChat', 'encryptedMessage': cypherText, 'encryptedKey': encryptedKey, 'signature': signature, 'to': receiver, 'from': sender } log += ctime() + " Encryption Type: Playfair\n\n" elif encryptionType == 'des': d = des() key, temp = d.randomkey() cypherText = d.encrypt(key, message) # if message r = RSA(0) encryptedKey = r.encryption(key, receiverPublicKey) if len(cypherText) > 5: signature = r.sign( cypherText[0:6], self.father.father.selfInfo['priKey']) else: signature = r.sign( cypherText, self.father.father.selfInfo['priKey']) data = { 'type': 'singleChat', 'encryptedMessage': cypherText, 'encryptedKey': encryptedKey, 'signature': signature, 'to': receiver, 'from': sender } log += ctime() + " Encryption Type: DES\n\n" # pass else: d = des() keys = d.randomkey() # less = 0 if len(message) % 8 != 0: less = 8 - (len(message) - len(message) // 8 * 8) for i in range(less): message += '0' print(message) # print("--------------------", keys[0], keys[1]) cypherText = d.tencrypt(keys[0], keys[1], message) print("--------------------", keys[0], keys[1], cypherText) r = RSA(0) encryptedKey = r.encryption(keys, receiverPublicKey) if len(cypherText) > 5: signature = r.sign( cypherText[0:6], self.father.father.selfInfo['priKey']) else: signature = r.sign( cypherText, self.father.father.selfInfo['priKey']) data = { 'less': less, 'type': 'singleChat', 'encryptedMessage': cypherText, 'encryptedKey': encryptedKey, 'signature': signature, 'to': receiver, 'from': sender } log += ctime() + " Encryption Type: 3DES\n\n" else: mA = data['mA'] key = pow(mA, self.father.father.selfInfo['secretB'], self.father.father.selfInfo['pAndg'][0]) if encryptionType == 'caesar': c = Caesar(key) cypherText = c.encryption(message) r = RSA(0) encryptedKey = r.encryption(key, receiverPublicKey) if len(cypherText) > 5: signature = r.sign( cypherText[0:6], self.father.father.selfInfo['priKey']) else: signature = r.sign( cypherText, self.father.father.selfInfo['priKey']) data = { 'type': 'singleChat', 'encryptedMessage': cypherText, 'encryptedKey': encryptedKey, 'signature': signature, 'to': receiver, 'from': sender } log += ctime() + " Encryption Type: Playfair\n\n" elif encryptionType == 'playfair': p = Playfair() cypherText, key = p.encryption(message) r = RSA(0) encryptedKey = r.encryption(key, receiverPublicKey) if len(cypherText) > 5: signature = r.sign( cypherText[0:6], self.father.father.selfInfo['priKey']) else: signature = r.sign( cypherText, self.father.father.selfInfo['priKey']) data = { 'type': 'singleChat', 'encryptedMessage': cypherText, 'encryptedKey': encryptedKey, 'signature': signature, 'to': receiver, 'from': sender } log += ctime() + " Encryption Type: Playfair\n\n" elif encryptionType == 'des': d = des() key, temp = d.randomkey() cypherText = d.encrypt(key, message) # if message r = RSA(0) encryptedKey = r.encryption(key, receiverPublicKey) if len(cypherText) > 5: signature = r.sign( cypherText[0:6], self.father.father.selfInfo['priKey']) else: signature = r.sign( cypherText, self.father.father.selfInfo['priKey']) data = { 'type': 'singleChat', 'encryptedMessage': cypherText, 'encryptedKey': encryptedKey, 'signature': signature, 'to': receiver, 'from': sender } log += ctime() + " Encryption Type: DES\n\n" # pass else: d = des() keys = d.randomkey() # less = 0 if len(message) % 8 != 0: less = 8 - (len(message) - len(message) // 8 * 8) for i in range(less): message += '0' print(message) # print("--------------------", keys[0], keys[1]) cypherText = d.tencrypt(keys[0], keys[1], message) print("--------------------", keys[0], keys[1], cypherText) r = RSA(0) encryptedKey = r.encryption(keys, receiverPublicKey) if len(cypherText) > 5: signature = r.sign( cypherText[0:6], self.father.father.selfInfo['priKey']) else: signature = r.sign( cypherText, self.father.father.selfInfo['priKey']) data = { 'less': less, 'type': 'singleChat', 'encryptedMessage': cypherText, 'encryptedKey': encryptedKey, 'signature': signature, 'to': receiver, 'from': sender } log += ctime() + " Encryption Type: 3DES\n\n" # pAndg = receiverCertificate['pAndg'] # self.father.father.selfInfo['secretB'] = getPrimeNum(20) # mB = pow(pAndg[1], self.father.father.selfInfo['secretB'], pAndg[0]) # receiverCertificate['mB'] = mB pass jData = json.dumps(data) self.socket.send(jData.encode()) print('__send__' + jData) # update log log += ctime() + " Send Message Success\n\n" logArea.insert(tk.END, log) logArea.see(tk.END) # update text textArea = self.father.textArea if less != 0: message = message[0:-less] text = '['+ sender + ' -> ' + receiver + ' ' + \ ctime() + ']\n\t' + message + '\n' textArea.insert(tk.END, text) textArea.see(tk.END) inputEntry.delete(0, tk.END)
from rsa import RSA from gmpy2 import powmod, invert def rsa_encrypt(plaintext, publickey): nums = publickey.public_numbers() return powmod(plaintext, nums.e, nums.n) def rsa_decrypt(ciphertext, privatekey): nums = privatekey.private_numbers() return powmod(ciphertext, nums.d, nums.public_numbers.n) if __name__ == "__main__": manager = RSA(public_exponent=65537, key_size=2048) private_key = manager.private_key public_key = manager.public_key n = public_key.public_numbers().n a = 5 b = 10 encrypted_a = rsa_encrypt(a, public_key) encrypted_b = rsa_encrypt(b, public_key) # mutiplying the encrypted value of a with the # encrypted value of b, to obtain the product of # both encrypted values encrypted_product = (encrypted_a * encrypted_b) % n # getting the product of the two plaintext values product = rsa_decrypt(encrypted_product, private_key)
getcontext().prec = keylen * 8 #这里是设置精度 forge = "\x00\x01%s\x00%s" % ("\xff" * 8, dgst) # 填充过程 garbage = "\x00" * (keylen - 8 - len(dgst) - 13) whole = s2i(forge+garbage) cr = int(pow(whole,Decimal(1)/Decimal(3)))+1 #把我们得到的whole开3次方,得到的应该是我们伪造的加密sign return i2s(cr) #转换为字符串 if __name__ == "__main__": message = "hi mom" print 'msg is :'+message+'\n' re = RSA() pub1,priv1 = re.keygen(l=512,s=False) #通过c39里的函数获得密钥 rs = RSAsign() sign = rs.make(message,priv1) #调用函数算出sign的rsa加密之后的结果 print 'rsa sign is :'+''.join(sign)+'\n' if rs.verify(message,sign,pub1): #这个地方是验证如果成功就输出ok print "sign is correct \n" else: print 'sign is incorrect \n' signf = [ forging(message,pub1) ] #这个利用公钥和消息我们可以伪造出一个signf print 'signf is :'+''.join(signf)+'\n' if rs.verify(message,signf,pub1): #这个地方是验证 print "sign is correct \n" else:
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的算法
forge = "\x00\x01%s\x00%s" % ("\xff" * 8, dgst) # 填充过程 garbage = "\x00" * (keylen - 8 - len(dgst) - 13) whole = s2i(forge + garbage) cr = int(pow( whole, Decimal(1) / Decimal(3))) + 1 #把我们得到的whole开3次方,得到的应该是我们伪造的加密sign return i2s(cr) #转换为字符串 if __name__ == "__main__": message = "hi mom" print 'msg is :' + message + '\n' re = RSA() pub1, priv1 = re.keygen(l=512, s=False) #通过c39里的函数获得密钥 rs = RSAsign() sign = rs.make(message, priv1) #调用函数算出sign的rsa加密之后的结果 print 'rsa sign is :' + ''.join(sign) + '\n' if rs.verify(message, sign, pub1): #这个地方是验证如果成功就输出ok print "sign is correct \n" else: print 'sign is incorrect \n' signf = [forging(message, pub1)] #这个利用公钥和消息我们可以伪造出一个signf print 'signf is :' + ''.join(signf) + '\n' if rs.verify(message, signf, pub1): #这个地方是验证 print "sign is correct \n" else:
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())