def verifyDoc(msg, publicKey): print "msg: ",msg print int(publicKey.split(', ')[0]), int(publicKey.split(', ')[1]) try: n = int(publicKey.split(', ')[0]) e = int(publicKey.split(', ')[1]) i = 0 for char in msg: if char == '[': break i += 1 out = list() for c in msg[i+1:-1].split(","): if ']' in c: c = c[:-1] out.append(long(c)) msg = msg[:i-1] rsa = RSA() decrypted = rsa.decrypt(out,n,e) sha = SHA1() hashed = '' for part in range((len(msg)//448)+1): hashed = hashed + sha.doDigest(sha.addPadding(msg)) if hashed == decrypted: print "MENSAJE AUTENTICO!" else: print "MENSAJE MODIFICADO!" except ValueError: print "SE HA INTRODUCIDO UNA LLAVE ERRONEA!"
def encrypt(file, save_as, schema, base_path): if schema == 'AES': pickle_in = open(base_path + 'en-de/aes.p', 'rb') passwd = pickle.load(pickle_in) pickle_in.close() AES.encrypt_AES(file, passwd, save_as) elif schema == 'RSA': RSA.encrypt_RSA(file, save_as, base_path) elif schema == 'DES': pickle_in = open(base_path + 'en-de/des.p', 'rb') passwd = pickle.load(pickle_in) pickle_in.close() DES.encrypt_DES(file, passwd, save_as) elif schema == 'BF': pickle_in = open(base_path + 'en-de/bf.p', 'rb') #print(base_path) passwd = pickle.load(pickle_in) pickle_in.close() bf.encrypt_bf(file, passwd, save_as) else: print('pending') sys.exit(2)
def encrypt(): print("--------------------加密过程开始--------------------") print("--------------------MD5加密开始--------------------") mess=input("请输入想加密的消息(默认为hello):") or "hello" origin=mess md5Tmp=md5.md5hash(mess) print(f"明文长度为: {origin.__len__()}\n输入的明文的MD5值为: {md5Tmp}") print("--------------------MD5加密结束--------------------\n") print("--------------------RSA加密开始--------------------") p = int(input("输入RSA密码算法的p值(必须为素数,默认值为47):") or "47") q = int(input("输入RSA密码算法的q值(必须为素数且不能与上面的值相同,默认值为463):") or "463") ListOut = RSA.generate_key_pair(p,q) encrypted = RSA.encrypt(ListOut[0],ListOut[1], md5Tmp) encrypted_msg=' '.join(map(lambda x: str(x), encrypted)) print(f"RSA公钥为: ({ListOut[0]},{ListOut[1]})\nRSA私钥的key值为: {ListOut[2]}\nRSA私钥的n值为: {ListOut[1]}\nRSA密文为:\n{encrypted_msg}\n") print("--------------------RSA加密结束--------------------\n") print("--------------------DES加密开始--------------------") combine=origin+encrypted_msg noPairKey=input("输入您的DES密钥(默认值为hello123,必须为8个):") or "hello123" desObject=DES.des() finalOut=desObject.encrypt(noPairKey,combine,padding=True) f=open("encrypted.txt","wb") f.write(bytes(finalOut,'utf-8')) f.close() print(f"DES明文为:\n{combine}\nDES密文为:\n{finalOut}\n密文已编码后写入encrypted.txt文件中") print("--------------------DES加密结束--------------------") print("--------------------加密过程结束--------------------\n")
def p46(): rsa = RSA() m = b64decode( 'VGhhdCdzIHdoeSBJIGZvdW5kIHlvdSBkb24ndCBwbGF5IGFyb3VuZCB3aXRoIHRoZSBG' 'dW5reSBDb2xkIE1lZGluYQ==' ) m = int(hexlify(m), 16) c = rsa.enc(m) bounds = [(0, 1), (1, 1)] for _ in range(rsa.N.bit_length()): nm = bounds[0][0] * bounds[1][1] + bounds[1][0] * bounds[0][1] dm = bounds[0][1] * bounds[1][1] * 2 gcd = gcd_func(nm, dm) nm, dm = nm / gcd, dm / gcd c = (pow(2, rsa.e, rsa.N) * c) % rsa.N if rsa.dec(c) % 2 == 0: bounds[1] = (nm, dm) else: bounds[0] = (nm, dm) recovered = bounds[1][0] * rsa.N / bounds[1][1] return 'Recovered message "{}"'.format(unhexlify(hex(recovered)[2:-1]))
def Encrypted(k, t, CP_1, CP_2, keys: list): print('Зашифровываем сеансовый ключ, временную метку и цифровую подпись') c_k = RSA.Encription(keys, int(k)) c_t = RSA.Encription(keys, int(t)) c_CP_1 = RSA.Encription(keys, int(CP_1)) c_CP_2 = RSA.Encription(keys, int(CP_2)) return c_k, c_t, c_CP_1, c_CP_2
def RSA_challenge(self, other): usleep(self.transmission_delay) # wait in getting the package first_response = other.respond_to_id(self.id) success, data = RSA.RSA_Decrypt(self.private_key, first_response) usleep(self.processing_delay) if success is False: print("Something went Wrong in decyrpting response") data = data.decode('utf-8') temp = data.split(',') # other's id, other's nonce, other's timestamp other_pkey = self.publickeylist[int(temp[0])] nonce = random.randint(0, 1000) self.sentNonce = nonce data = temp[1] + ", " + str(nonce) + ", " + str(self.id) + ", " + str(time.gmtime()) data = data.encode('utf-8') self.pointB_id = int(temp[0]) challenger_pkey = self.publickeylist[self.pointB_id] usleep(self.transmission_delay) package = RSA.RSA_Encrypt(challenger_pkey, data) usleep(self.processing_delay) nonce, timestamp = other.verify_nonce(package) usleep(self.transmission_delay) if self.sentNonce == nonce: return True return False
def perf_test(): bits = [16, 32, 64, 1048, 2048] message = "Hello World" print("Encrypting Message: " + message) for size in bits: print("===================================") print("Key size: %d" % size) gen_start = time.perf_counter() keyPair = rsa.KeyPair(size) print(time.perf_counter() - gen_start) print("Encrypting") enc_start = time.perf_counter() cypher = rsa.encryptMessage(keyPair.publicKey, "Hello World") print(time.perf_counter() - enc_start) print("Decrypting") dec_start = time.perf_counter() message = rsa.decryptMessage(keyPair.privateKey, cypher) print(time.perf_counter() - dec_start) print("Decrypted message: " + message) print("===================================\n\n")
def verify_trx(block_path, idx): data = json.load(open(block_path)) in_trx = data['output'][str(idx)] trx = dict() trx['digest'] = str(in_trx["digest"]) trx['idx'] = int(in_trx["idx"]) trx["authorID"] = str(in_trx['authorID']) trx["clientID"] = str(in_trx['clientID']) trx["pub_key"] = str(in_trx['pub_key']) signature = in_trx['signature'] pubkey = str(trx['pub_key']) public = rsa.importKey(pubkey) msg = b64encode(str(trx)) print "\n\n---" print trx['pub_key'] print "---\n\n" print "\n\n---" print msg print "---\n\n" verify = rsa.verify(msg, b64decode(signature), public) return verify, in_trx
def encrypt(tesseractPass, msg): tesseractPass = str(tesseractPass) ent = str(msg) print(' Loading your keys\n ') serializer.recover_keyfile(tesseractPass) serializer.unzip_all() serializer.recover_all(tesseractPass) r1, r2, r3 = serializer.read_cripto8_rotors() public, private = serializer.read_rsa_keys() serializer.del_keys() print(' Keys Loaded\n') c8out = cripto8.encode(ent, r1, r2, r3) ardvkOut = ArDVK64.encode(c8out) if len(ardvkOut) > 500: tmp_paths = serializer.divide_in_blocks(ardvkOut) enc_blocks = RSA.encrypt_blocks(tmp_paths, public) serializer.save_enc_blocks(enc_blocks) print( "\n Text encrypted. The output is all CriptoOutputX.data files. You can zip them with you want.\n" ) print( " You should hide criptoExtreme_keys.cripto file. This contains all the keys to decrypt CriptoOutput.txt\n" ) else: ent = ardvkOut.encode('utf8') enc = RSA.encrypt(ent, public) serializer.save_output(enc) print("\n Text encrypted. The output is in CriptoOutput.data\n") print( " You should hide criptoExtreme_keys.cripto file. This contains all the keys to decrypt CriptoOutput.data\n" ) return True
def RuntimeTest(self): data = self.testData.strip().split('\n') for i in range(len(data)): start = time() des = DES() key = '0001001100110100010101110111100110011011101111001101111111110001' des.SetKey(key) des.EncryptKey() des.SetInputText(data[i]) des.SetCipherText(des.Encrypt()) desResult = des.Decrypt() stop = time() self.runtime += ('DES runtime:' + str(stop - start) + "s\n") start = time() rsa = RSA() rsa.KeyGeneration(128) rsaResult = rsa.Decryption( rsa.Encryption(int(data[i]), rsa.keyPublic, rsa.n), rsa.keyPrivate, rsa.n) stop = time() self.runtime += ('RSA runtime:' + str(stop - start) + "s\n\n") return self.runtime
def run(mode): flag = False while True: if (flag): break flag = True files = os.listdir(os.getcwd()) print files #get common elements files = [i for i in files if i not in Forbidden] print files for i in range(len(files)): if (os.path.isfile(files[i])): if (mode): RSA.runEncrypt(files[i], keyFile=keyPath1) else: if (files[i].endswith('.crypt')): RSA.runDecrypt(files[i], keyFile=keyPath2) else: pass elif (os.path.isdir(files[i])): os.chdir(files[i]) print "dir" flag = False else: pass
def ButtonGenerate(): DisplayText("RSA keys generated!") pssw = appState["UI"]["PasswordTextfield"].get() hasher = Hash.sha1() hasher.update(pssw.encode()) key = hasher.digest() key = key[:16] RS.generateKey(key)
def get_S1_PublicKey(e_CA, n_CA): with open("public_directory", 'r') as f: sender_public_keys = f.read().split() e_S1 = RSA.RSA_decryption(sender_public_keys[2], int(e_CA), int(n_CA)).replace('{', "") n_S1 = RSA.RSA_decryption(sender_public_keys[3], int(e_CA), int(n_CA)).replace('{', "") return e_S1, n_S1
def plotMillerTime(p): multiVar = 10000000000 mills = int(round(time.time()*multiVar)) n = (gmpy2.xmpz(RSA.getRandom())**gmpy2.xmpz(p))+(gmpy2.xmpz(RSA.getRandom())**gmpy2.xmpz(p)-1) while not miller_rabin.millerRabin(n, 2): n = (gmpy2.xmpz(RSA.getRandom())**gmpy2.xmpz(p))+(gmpy2.xmpz(RSA.getRandom())**gmpy2.xmpz(p)-1) mills = int(round(time.time()*multiVar)) - mills return (mills, bit_length(n), totalDigits(n))
def EnDecript(mode, file): settings.init() #print settings.CONFIGS['RSA_KEY_PRIVATE'] if (mode): RSA.runEncrypt(file, keyFile=settings.CONFIGS['RSA_KEY_PUBLIC']) else: RSA.runDecrypt(file, keyFile=settings.CONFIGS['RSA_KEY_PRIVATE'])
def main(): plaintext = b"Hello, I'm another Python programmer." rsa = RSA(1024) ciphertext = rsa.encrypt(plaintext) rsa_server = RSAServer(rsa) recovered_plaintext = unpadded_message_recovery(ciphertext, rsa_server) assert recovered_plaintext == plaintext
def main(): keys = rsa.generate() for x in [2, rsa._prime(), rsa._prime() + 1]: # [0] base case, [1] random 512-bit prime, [2] random 512-bit nonprime. y = rsa.encrypt(keys[0],x) assert(x != y) z = rsa.decrypt(keys[1],y) assert(z == x) #Asserts that all functions in RSA is working.
def fileTranfer(filename, BRSApublickeye, BRSApublickeyn): pattern = r"\.[^.\\/:*?\"<>|\r\n]+$" #step0:打开文件,读取文件内容作为明文 #print "#"*100 #filename=raw_input("输入你的文件名:") result = re.findall(pattern, filename) if result[0] == ".txt": with open("D:\\python\\code\\" + filename, 'r') as f: plainText = ''.join(f.readlines()) elif result[0] == ".jpg": with open("D:\\python\\code\\" + filename, 'rb') as f: plainText = ''.join(f.readlines()) else: with open("D:\\python\\code\\" + filename, 'rb') as f: plainText = ''.join(f.read()) print "打开文件成功=>", #step1:对明文使用MD5算法进行哈希 #print "#" * 100 #myMD5=MD5.MD5(plainText) #myhash=myMD5.encrypt() #print "哈希值是:",myhash myMD5 = hashlib.md5() myMD5.update(plainText) myhash = myMD5.hexdigest() print "生成哈希值成功=>", #step2:对哈希值使用RSA进行数字签名 #print "#" * 100 #print "RSA算法进行数字签名:" #p=int(raw_input("输入私钥p:")) #q=int(raw_input("输入私钥q:")) myRSA = RSA.RSA(myhash, "", p, q, 107, 0) myRSAlength, myDigitalSignature = myRSA.SKencrypt() print "生成数字签名成功=>", #step3:将明文和数字签名的值连接起来,使用AES算法进行对称加密 #print "#" * 100 MplusE = plainText + myDigitalSignature #print "明文和经过数字签名的哈希值连接:\n长度为:",len(MplusE),MplusE #step4:使用AES对称加密算法对明文和哈希值进行加密 #print "#" * 100 #AESkey=raw_input("输入AES密钥:") AESkey = ''.join(random.sample(string.ascii_letters + string.digits, 16)).lower() print "生成随机AESKEY:%s=>" % AESkey, BRSA = RSA.RSA(AESkey, "", 0, 0, BRSApublickeye, BRSApublickeyn) SecretAESkey = BRSA.PKencrypt() myAES = AES.AES(AESkey, MplusE, "") myAESlength, mySecretText = myAES.allEncrypt() finalSecretText = SecretAESkey + mySecretText print "生成最终密文=>" return finalSecretText
def elgamalEncrypt(messageFilename, publicKeyFilename): fo = open(messageFilename, 'r') plaintext = fo.read() fo.close() #print('%s\n\n%s\n%s\n%s\n' %('Text to encrypt:', '***', plaintext, '***')) blocks = RSA.textToBlocks(plaintext) #print('%s\n\n%s\n' %('Text blocks:', blocks)) numbers = RSA.blocksToNumbers(blocks) print('%s\n\n%s\n' %('Blocks as numbers:', numbers)) fo = open(publicKeyFilename, 'r') content = fo.read() fo.close() x, y = content.split(',') Q_a = [int(x), int(y)] #print ( Q_a ) #choose ephemeral key n_b = random.randint(2,p-1) #print(n_b) c1 = cryptomath.ellipticCurveMultiplication([A,0], p, P, n_b) #print (c1) #turn message into points on elliptic curve encryptedPoints, mapping = encodeAsAPoints(numbers,A,p) s_mapping = '' for val in mapping: s_mapping += str(val) #print (s_mapping) #print ('test block:', encryptedPoints) #print ('test mapping', mapping ) c2 = [] nb_Qa = cryptomath.ellipticCurveMultiplication([A,0], p, Q_a, n_b) #print (nb_Qa) for m in encryptedPoints: #print (m) pt = cryptomath.ellipticCurveAddition([A,0] , p, [m,nb_Qa] ) c2.append( pt ) #print (c2) encryptedFile = open('elgamal_message_encrypted.txt', 'w') encryptedFile.write('%s, %s' % (c1[0],c1[1])) encryptedFile.write('\n') for pt in c2: encryptedFile.write('%s, %s' % (pt[0],pt[1])) encryptedFile.write('\n') encryptedFile.write('%s' % (s_mapping)) encryptedFile.close()
def ButtonPassword(): DisplayText("RSA keys read finished!") pssw = appState["UI"]["PasswordTextfield"].get() hasher = Hash.sha1() hasher.update(pssw.encode()) key = hasher.digest() key = key[:16] appState["UI"]["rsaPublic"] = RS.readKey(0, key) appState["UI"]["rsaPrivate"] = RS.readKey(1, key)
def read_next_message(self): try: b1, b2 = self.read_bytes(2) except SocketError as e: # to be replaced with ConnectionResetError for py3 if e.errno == errno.ECONNRESET: logger.info("Client closed connection.") self.keep_alive = 0 return b1, b2 = 0, 0 except ValueError as e: b1, b2 = 0, 0 fin = b1 & FIN opcode = b1 & OPCODE masked = b2 & MASKED payload_length = b2 & PAYLOAD_LEN if opcode == OPCODE_CLOSE_CONN: logger.info("Client asked to close connection.") self.keep_alive = 0 return if not masked: logger.warn("Client must always be masked.") self.keep_alive = 0 return if opcode == OPCODE_CONTINUATION: logger.warn("Continuation frames are not supported.") return elif opcode == OPCODE_BINARY: logger.warn("Binary frames are not supported.") return elif opcode == OPCODE_TEXT: opcode_handler = self.server._message_received_ elif opcode == OPCODE_PING: opcode_handler = self.server._ping_received_ elif opcode == OPCODE_PONG: opcode_handler = self.server._pong_received_ else: logger.warn("Unknown opcode %#x." % opcode) self.keep_alive = 0 return if payload_length == 126: payload_length = struct.unpack(">H", self.rfile.read(2))[0] elif payload_length == 127: payload_length = struct.unpack(">Q", self.rfile.read(8))[0] masks = self.read_bytes(4) message_bytes = bytearray() for message_byte in self.read_bytes(payload_length): message_byte ^= masks[len(message_bytes) % 4] message_bytes.append(message_byte) # messages encryption using RSA. message_encrypt = RSA.RSA_encryption(message_bytes.decode('utf8')) message_decrypt = RSA.RSA_decryption(message_encrypt) opcode_handler(self, message_decrypt)
def main(): plaintext = b"Hello, I'm a Python programmer." ciphertexts = [] for _ in range(3): rsa = RSA(1024) ciphertexts.append((rsa.encrypt(plaintext), rsa.n)) assert rsa_broadcast_attack(ciphertexts) == plaintext
def fileTranfer(secretText, RSApublickeye, RSApublickeyn): # step1:使用AES算法解密 # print "#" * 100 # secretText=raw_input("输入需要解密的密文:") SecretAESkey = secretText[0:48] BRSA = RSA.RSA("", SecretAESkey, p, q, 107, 0) AESkey = BRSA.SKdecrypt() print "解密得到AESkey:%s=>"%AESkey, # AESkey = raw_input("输入AES密钥") myAES = AES.AES(AESkey, "", secretText[48:]) Mlength, M = myAES.allDecrypt() # step2: 去掉填充0,分离明文和数字签名值 for i in xrange(-1, -17, -1): if M[i] != '0': break M = M[:i + 1] myplainText = M[:len(M) - 64] myDigitalSignature = M[-64::] print "分离明文和数字签名成功=>", # step3:利用RSA算法分析出哈希值 # print "#" * 100 # RSApublickeye=int(raw_input("输入RSA解密的公钥e:")) # RSApublickeyn=int(raw_input("输入RSA解密的公钥n:")) myRSA = RSA.RSA("", myDigitalSignature, 0, 0, RSApublickeye, RSApublickeyn) myhash = myRSA.PKdecrypt() print "RSA解密出hash值=>", # step4:对明文使用MD5算法进行哈希 # print "#" * 100 # myMD5 = MD5.MD5(myplainText) # calhash = myMD5.encrypt() myMD5 = hashlib.md5() myMD5.update(myplainText) # .encode(encoding='utf-8')) calhash = myMD5.hexdigest() print "计算哈希值成功=>", # step5:比较哈希是否相同,相同将明文内容写入文件中 if calhash == myhash: print "hash相同,传输内容未被篡改" pattern = r"\.[^.\\/:*?\"<>|\r\n]+$" filename = raw_input("输入你要保存的文件名:") result = re.findall(pattern, filename) if result[0] == ".txt": with open("/root/code/panice/xbz/" + filename, 'w') as f: f.write(myplainText) elif result[0] == ".jpg": with open("/root/code/panice/xbz/" + filename, 'wb') as f: f.write(myplainText) with open("/root/code/panice/xbz/temp.txt", 'w') as f: f.write(secretText) print "将解密出来的明文和密文分别写进%s和temp.txt文件中,请查看!" % filename else: print "hash不同,文本错误!"
def crypto(mode, type, fileLoaded, fileData, window): if fileLoaded: # check if default key file exist if os.path.isfile('./key.txt'): answer = sg.popup_yes_no('Key found in file: key.txt. Do you want to use this key?',keep_on_top = True) key = None # key loaded not from key.file if answer == None or answer == 'No': filename = sg.popup_get_file('Please enter a key file name') if filename != None: if not os.path.isfile(filename): sg.popup_error('File doesn\'t exist!',keep_on_top = True) return else: key = RSA.read_key_from_file(filename) else: return # key loaded from key.file elif answer == 'Yes': key = RSA.read_key_from_file('./key.txt') else: return False if key: file = None # encryption mode if(mode == 'E'): if(type == 'ECB'): fileData.ECB_make_encrypted_file(key) if(type == 'CBC'): fileData.CBC_make_encrypted_file(key) if(type == 'PCBC'): fileData.PCBC_make_encrypted_file(key) if(type == 'EECB2'): fileData.ECB_make_encrypted_file2(key) # decryption mode if(mode == 'D'): if(type == 'ECB'): fileData.ECB_make_decrypted_file(key) if(type == 'CBC'): fileData.CBC_make_decrypted_file(key) if(type == 'PCBC'): fileData.PCBC_make_decrypted_file(key) if(type == 'DECB2'): fileData.ECB_make_decrypted_file2(key) return True else: sg.popup('No keys!') return False # file not loaded error else: sg.popup_error('File is not loaded!')
def OnClientClick(self, event): global key,masKey,public_key,private_key self.clientname=self.InputText1.GetValue() self.socketmode=0 #self.cButton.SetLabel("Client") key=RSA.Build_key(self.clientname) masKey=RSA.Build_key(self.clientname)#Masquerader attack test public_key = key.split('/')[0]+'/'+key.split('/')[1] # n/e pair private_key = key.split('/')[0]+'/'+key.split('/')[2] # n/d pair thread.start_new_thread(self.SocketProc_client,())
def keyGenerator(name): rsa = RSA() publicKey,privateKey = rsa.genKeys() f = io.open('publicKey/public'+name, 'w') f.write(unicode(str(publicKey)[1:-1],'utf-8')) f.close() f = io.open('privateKey/private'+name, 'w') f.write(unicode(str(privateKey)[1:-1],'utf-8')) f.close() print publicKey,privateKey
def Encryption(): print('请输加密文件路径:', end='') file_path = input() print('请输入用户公钥文件路径:', end='') pubkey_path = input() pubkey = RSA.read_pubkey(pubkey_path) text = function.read_file(file_path) text = RSA.rsaEncrypt(text, pubkey) function.save_file(file_path, text) print('文件加密成功!')
def Encrypt_GUI(): global entext, d, N, p, q e, d, N, p, q =RSA.get_key() Text_public_key.insert(1.0, '('+str(N)+','+str(e)+')') '''加密过程''' global entext entext = RSA.RSA_Encrypt(message.get(), N, e) Text_encryption_result.insert(1.0, entext) # RSA通过公钥(N, e)进行加密 tk.messagebox.showinfo('Encryption result', 'The Encryption result is as follows:' + str(entext))
def Decryption(): print('请输入姓名:', end='') name = input() print('请输解密文件路径:', end='') file_path = input() privkey_path = config.certificate + name + '.pem' privkey = RSA.read_privkey(privkey_path) text = function.read_file(file_path) text = RSA.rsaDecrypt(text, privkey) function.save_file(file_path, text) print('文件解密成功!')
def handle(conn, ht): global access_list, NOW_USER, LAST_USER, START_CLOCK log('info', ht[0] + ' connect.') # RSA init ren = RSA() ms = conn.recv(1024).decode('utf-8').strip().split('|') if not ms or len(ms) == 1: conn.send(b'\nLOGIN FAILED.SHUTDOWN HANDLE') conn.close() log('warning', ht[0] + ' send data struct can\'t handle') return False ren.init_en(ms[1], ms[0]) tf = twoFish.TwoFish() conn.send(ren.encode(tf.key).encode()) # RSA-TwoFish PIPE INIT END ms = recv(conn, tf).strip().split('$') if len(ms) == 1: send(conn, tf, 'LOGIN FAILED.SHUTDOWN HANDLE') conn.close() log('warning', ht[0] + ' send data struct can\'t handle') return False if ms[0] not in access_list or not access_list[ms[0]].login(ms[1]): send(conn, tf, 'LOGIN FAILED.SHUTDOWN HANDLE') conn.close() log('warning', ht[0] + ' use ' + ms[0] + ' ' + ms[1] + ' login Failed') return False send(conn, tf, 'LOGIN SUCCESS') log('info', ht[0] + ' login success') user = access_list[ms[0]] NOW_USER = user ret = '' while True: strs = recv(conn, tf).strip() if strs == 'BYEBYE': send(conn, tf, 'GOODBYE') log('info', NOW_USER.name + ' deconnect.') conn.close() return True else: command = strs.split() if command: strip_list(command) if len(command) == 1: if command[0] == 'help': ret = helpmsg #if command[0]=='debug':conn.send(' '.join((str(LAST_USER),str(NOW_USER),str(START_CLOCK))).encode('utf-8')) elif len(command) >= 2: ret = check_ret(access(command[0], command[1:])) else: pass send(conn, tf, ret) ret = ''
def autograph(): print('请输入姓名:', end='') name = input() print('请输入用户私钥文件路径:', end='') privkey_path = input() CApubkey = RSA.creat_key(5120) text = function.read_file(privkey_path) text = RSA.rsaEncrypt(text, CApubkey) function.save_file(config.certificate + name + '.pem', text) print('CA私钥文件路径为:', config.CAprivkey_path) print('申请认证成功!')
def sign(string): global PrivateKey ciphertext = [] for temp in string: ciphertext.append(RSA.rsa(temp, PrivateKey, None)) ciphertext_string = TupleToString(tuple(ciphertext)) return ciphertext_string
def unsign(string): global PubKey_OtherGuy cleartext = '' tuple_string = StringToTuple(string) for temp in tuple_string: cleartext = cleartext + chr(RSA.rsa(temp, None, PubKey_OtherGuy, decrypt=True)) return str(cleartext)
def rsa_given_lambda(semantics_mat, saliences, util_func=log): rsa_obj = RSA(semantics_mat) rsa_obj.r0() # returns a an RSA object given a specific lambda def func_over_lambda(lamb): rsa_obj.l = lamb rsa_obj.s1(util_func) return rsa_obj.r2(saliences) # return function over RSA objects return func_over_lambda
def decrypt(string): global PrivateKey cleartext = '' tuple_string = StringToTuple(string) for temp in tuple_string: cleartext = cleartext + chr(RSA.rsa(temp, None, PrivateKey, decrypt=True)) return str(cleartext)
def __AttemptLogin__(self): # 登录并保持初始cookie logininitpage = self.__session.get("http://bmd.sh.10086.cn/login.jsp") cookie = logininitpage.cookies # 使用登录页面的cookie获取验证码图片 r = self.__session.get("http://bmd.sh.10086.cn/captcha.jpg", stream=True, cookies=cookie) # 获取生产public key用的modulus和exponent public_modulus_hex_re = re.compile("RSAUtils\.getKeyPair(.*)") public_modulus_hex = public_modulus_hex_re.findall(logininitpage.content) keypairs = public_modulus_hex[0].replace("\"", "").replace("(", "").replace(")", "").replace(";", "").split(",") encryptionexponent = keypairs[0].strip() modulus = keypairs[2].strip() with open('verifycode.jpg', 'wb') as f: for chunk in r.iter_content(chunk_size=1024): if chunk: # filter out keep-alive new chunks f.write(chunk) f.flush() f.close() # 获取验证码图片中的字符 vcode = captcha.deCAPTCHA('verifycode.jpg') # 获取登录提交用的密码 encryptedpw = RSA.encrypt(self.__password, modulus, encryptionexponent) payload = {"lg": self.__username, "password": encryptedpw, "mc": vcode} loginpage = self.__session.post("http://bmd.sh.10086.cn/login.wsp", data=payload, cookies=cookie) return loginpage
def signByPrikeyAndSha1(self,message): m=EVP.MessageDigest("sha1") m.update(message) digest=m.final() key_str=file(self.prikeyDirectory,"rb").read() key=RSA.load_key_string(key_str, util.no_passphrase_callback) return key.sign(digest, "sha1")
def __init__(self, pubkey_pkt): import warnings warnings.warn('Deprecated. No maintainer for PGP. If you use this, please inform M2Crypto maintainer.', DeprecationWarning) self._pubkey_pkt = pubkey_pkt self._pubkey = RSA.new_pub_key((pubkey_pkt._e, pubkey_pkt._n)) self._userid = {} self._signature = {}
def encrypt(text): ent=[] textoPlano = [] c = [] tp = text.strip().split() palabras = [] for i in range(len(tp)): palabras.append(tp[i]) for i in range(len(palabras)): for j in range(len(palabras[i])): textoPlano.append(ord(palabras[i][j])) e,d,n = RSA.generarLlave() for i in range(len(textoPlano)): m = textoPlano[i] c.append(RSA.powerMod (m,e,n)) for i in range(len(c)): print c[i] return c
def encrypt(string): global PubKey_OtherGuy if len(PubKey_OtherGuy) == 0: raise ValueError ciphertext = [] for temp in string: ciphertext.append(RSA.rsa(temp, PubKey_OtherGuy, None)) ciphertext_string = TupleToString(tuple(ciphertext)) return ciphertext_string
def read_data(self, n, d): ''' Reads in data from client to be sent and displayed to server. ''' try: my_incoming_message = secure_utils.recv_end(self.my_connection) # receive incoming data my_incoming_message = secure_utils.unpack_cipherblocks_from_transmit(my_incoming_message) # unpack the combined cipher blocks my_incoming_message = RSA.decrypt(my_incoming_message, n, d, len([my_incoming_message])) # decrypt the cipher while my_incoming_message.strip() != self.my_exit_code and len(my_incoming_message) > 0: print "\r\033[1;34m<< {0}\033[1;m".format(my_incoming_message.strip()) my_incoming_message = secure_utils.recv_end(self.my_connection) # continue receiving more messages my_incoming_message = secure_utils.unpack_cipherblocks_from_transmit(my_incoming_message) # continue unpacking the cipher blocks my_incoming_message = RSA.decrypt(my_incoming_message, n, d, len([my_incoming_message])) # continue decrypting # client disconnected self.stop_write_loop() except: pass
def generate2d(): _x = [] _y = [] for x in xrange(1,10): mil = int(round(time.time())*1000000) n = RSA.generateLargePrime(x) mil = int(round(time.time())*10000000000) - mil _y.append(int(mil)) _x.append(bit_length(n)) print _x print _y
def generate_AES_Key_and_exchange(arduino): AES_Key = generate_PR_key() print "Generated Random AES Key = ", AES_Key AES_Key_string = ascii_int_list2string(AES_Key) AES_Key_encrypted = RSA.rsa_encrypt(AES_Key_string, RSA_Others_Public_Key) print "Encrypted AES Key (with RSA) = ", AES_Key_encrypted for i in range(AES_KEY_LENGTH): arduino.write(append_zeros_at_front(AES_Key_encrypted[i], BIGGEST_CIPHERTEXT_LENGTH)) return AES_Key
def verifyByPubkeyAndSha1(self,sign,message): m=EVP.MessageDigest("sha1") m.update(message) digest=m.final() cert_str=file(self.pubkeyDirectory, "rb").read() mb=BIO.MemoryBuffer(cert_str) cert=RSA.load_pub_key_bio(mb) try: cert.verify(digest, sign, "sha1") return True except: return False
def cycle_arduino_to_pc(arduino): arduino_encryted_hash = [] arduino.readline() arduino.readline() for i in range(16): arduino_encryted_hash.append(int(arduino.readline())) print "arduino_encryted_hash = ", arduino_encryted_hash arduino_msg_length = int(arduino.readline()) arduino_msg = '' for i in range(arduino_msg_length): arduino_msg += arduino.readline()[0] print "msg =" , arduino_msg msg_hash_by_pc = MD5.new(arduino_msg) msg_hash_by_pc_string = msg_hash_by_pc.digest() print "msg_hash_by_pc_string = ", msg_hash_by_pc_string msg_hash_by_pc_int_list = [] for i in range(len(msg_hash_by_pc_string)): msg_hash_by_pc_int_list.append(ord(msg_hash_by_pc_string[i])) print "msg_hash_by_pc_int_list = ", msg_hash_by_pc_int_list plain_hash = RSA.rsa_decrypt(arduino_encryted_hash, RSA_Others_Public_Key); hash_int_list = [] for val in plain_hash: hash_int_list.append(ord(val)) print "hash_int_list = ", hash_int_list if hash_int_list == msg_hash_by_pc_int_list : print "Hash and Message match!" else: print "Hash and Message do not match!"
def write_data(self, n, e): ''' Reads in data from prompt and sending out to client ''' try: while self.my_continue_to_write: my_original_message = sys.stdin.readline() # read input from user my_outgoing_message = RSA.encrypt(my_original_message, n, e, len([my_original_message])) # encrypt the users input my_outgoing_message = secure_utils.combine_cipherblocks_for_transmit(my_outgoing_message) + ";;" # add the ";;" delimeter. This indicates the end of a user's input. A fix for not knowing the buffer size. self.my_connection.send(my_outgoing_message) # send out message to the user. # check to see if my outgoing message is EXIT to quit the chat if (my_original_message.strip() == self.my_exit_code): self.my_connection.shutdown(socket.SHUT_RDWR) self.my_connection.close() self.stop_write_loop() except: pass
def desEncrypt(text): archive = open("keys.txt", "r") line = archive.readlines() public = line[0] private = line[1] archive.close() ent = [] textoPlano = [] c = [] llaveP = public.strip().split() e = int(llaveP[0]) n = int(llaveP[1]) llave = private.strip().split() d = int(llave[0]) ent = text.strip().split() for i in range(len(ent)): c.append(int(ent[i])) for i in range(len(c)): temp = c[i] textoPlano.append(RSA.powerMod(temp, d, n)) return textoPlano
def cycle_pc_to_arduino(pc_msg, arduino): send_pc_msg_to_arduino(pc_msg, arduino) pc_hash = MD5.new(pc_msg) pc_hash_string = pc_hash.digest() #send_pc_msg_to_arduino(pc_msg) print "pc_hash_string =", pc_hash_string pc_hash_int_list = [] for i in range(len(pc_hash_string)): pc_hash_int_list.append(ord(pc_hash_string[i])) # Packing pc_msg hash as int list for sending to arduino print "pc_hash_int_list = ", pc_hash_int_list length = len(pc_hash_int_list) encrypted_pc_hash = RSA.rsa_encrypt(pc_hash_string, RSA_Own_Private_Key) # Encrypting the hash by RSA print "encrypted_pc_hash = " ,encrypted_pc_hash # Send encrypted hash to Arduino for i in range(16): # Sending the Encrypted Hash arduino.write(append_zeros_at_front(encrypted_pc_hash[i], MOST_NO_OF_DIGITS)) recieved_by_arduino = arduino.readline()
import RSA public_key = (2539771189, 7) private_key = (2539771189, 725620063) mess = 'testing testing 123 123456 hi dave' ascii_mess = [ord(char) for char in mess] print(ascii_mess) encrypted_ascii_mess = [RSA.encrypt(public_key, message) for message in ascii_mess] print(encrypted_ascii_mess) decrypted_ascii_mess = [RSA.decrypt(private_key, message) for message in encrypted_ascii_mess] print(decrypted_ascii_mess) decrypted_mess = '' for char in decrypted_ascii_mess: decrypted_mess += chr(char) print(decrypted_mess) print(mess)
def RSAKeyGeneration(security_level): keys = RSA.generateKeys(security_level) e, N, d, p, q = keys[0], keys[1], keys[2], keys[3], keys[4] return e, N, d, p, q
def RSAencryption(N, e, message, L): return RSA.encrypt(N, e, message, L)
def genRsaKeypair(self,rsalen = 1024): rsa_key = RSA.gen_key(rsalen, 3, lambda *arg:None) rsa_key.save_key(self.prikeyDirectory, None) rsa_key.save_pub_key(self.pubkeyDirectory)
# читаем файл file = open(sys.argv[2], "r") text = file.read() file.close() # сгенерируем хеш hash_text = "".join([str(hex(h)[2:]).replace("L", "") for h in SHA1.sha1(text)]) # хеш шифруем закрытым ключом file = open(sys.argv[4], "r") buf = file.readline() d = int(buf) buf = file.readline() n = int(buf) file.close() crypted_hash = RSA.encryptstr(d, n, hash_text) # дешифруем с помощью открытого ключа file = open(sys.argv[3], "r") buf = file.readline() e = int(buf) decrypted_hash = "".join([chr(i) for i in RSA.decryptlist(e, n, crypted_hash)]) file.close() # сраниваем подписи if hash_text == decrypted_hash: print("Succesfull validate!") else: print("Digital signatures do not match!") if sys.argv[1] == "genkey_rsa":
print("[e] Calculate multiplicative inverse") print("[f] Calculate entropy") print("[g] Perform a shift") print("[h] Decrypt RSA with primes") print("[i] Decrypt RSA without primes") print("[x] Exit\n>>> ") answer = raw_input() if answer == 'a': Modular_Exponent() elif answer == 'b': n = int(raw_input("What number do you want to factor: ")) print(Crypto.factorize(n)) elif answer == 'c': totient() elif answer == 'd': x = int(raw_input("Enter your first number: ")) y = int(raw_input("Enter your second number: ")) print("The gcd is: " + str(Crypto.egcd(x,y)[0])) elif answer == 'e': x = int(raw_input("Enter your number: ")) y = int(raw_input("Enter your mod: ")) print("The inverse is: " + str(Crypto.modinv(x,y))) elif answer == 'f': Crypto.entropy() elif answer == 'g': Crypto.shift() elif answer == 'h': RSA.decryptRSA() elif answer == 'i': RSA.decryptRSAPrimes()
def RSAdecryption(N, d, p, q, cipher_text, L): return RSA.decrypt(N, d, p, q, cipher_text, L)
def test_integermod_reciprocal_func(modulo, residue, reciprocal): assert RSA.modular_reciprocal(residue, modulo) == reciprocal
def __init__(self, pubkey_pkt): self._pubkey_pkt = pubkey_pkt self._pubkey = RSA.new_pub_key((pubkey_pkt._e, pubkey_pkt._n)) self._userid = {} self._signature = {}
def RSAVerifySignature(N, e, message, signature): return RSA.verifySignature(N, e, message, signature)
def doSquareAttack(n): r = RSA.generate_r(n) bits_to_solve = 32 secretKey = '1' for i in range(1, bits_to_solve): sample_list = getSampleMessages(5000) M1 = [] # M1 is our additional reduction with 1 M2 = [] # M2 is our no reduction set with 1 M3 = [] #M3 is our additional reduction set with 0 M4 = [] #M4 is our no reduction set with 0 for sample in sample_list: if(RSA.CheckReduction(secretKey[0] + '1', sample, n, r)): M1.append(sample) else: M2.append(sample) if(RSA.CheckReduction(secretKey[0] + '0', sample, n, r)): M3.append(sample) else: M4.append(sample) M1_times = [] M2_times = [] M3_times = [] M4_times = [] for y in M1: M1_times.append(connection_handler.getDecryptTime(y)) for x in M2: M2_times.append(connection_handler.getDecryptTime(x)) for i in M3: M3_times.append(connection_handler.getDecryptTime(i)) for j in M4: M4_times.append(connection_handler.getDecryptTime(j)) average_M1 = sum(M1_times) / len(M1_times) average_M2 = sum(M2_times) / len(M2_times) average_M3 = sum(M3_times) / len(M3_times) average_M4 = sum(M4_times) / len(M4_times) if( abs(average_M1 - average_M2) > abs(average_M3 - average_M4)): print secretKey + '1' else: print secretKey + '0' print abs(average_M1 - average_M2) print abs(average_M3 - average_M4) print (abs(average_M1 - average_M2) - abs(average_M3 - average_M4))
def RSAGenerateSignature(N, d, message): return RSA.generateSignature(N, d, message)