def test_crack_shared_cipher(): ciphertext = 'Call me Ishmael.' keypair0 = RSAKeypair.create(e=3) keypair1 = RSAKeypair.create(e=3) keypair2 = RSAKeypair.create(e=3) c0 = rsa_encrypt(ciphertext, keypair0) c1 = rsa_encrypt(ciphertext, keypair1) c2 = rsa_encrypt(ciphertext, keypair2) n0 = keypair0.exponent n1 = keypair1.exponent n2 = keypair2.exponent m_s_0 = n1 * n2 m_s_1 = n0 * n2 m_s_2 = n0 * n1 assert all(gcd(n, n_) == 1 for n, n_ in combinations([n0, n1, n2], 2)) result, _ = crt_inductive([ (c0 * m_s_0 * mod_inverse(m_s_0, n0), keypair0.exponent), (c1 * m_s_1 * mod_inverse(m_s_1, n1), n1), (c2 * m_s_2 * mod_inverse(m_s_2, n2), n2), ]) cube_root, is_exact = iroot(mpz(result), 3) assert is_exact, 'Cube root should have been exact' assert unhexlify('{:02x}'.format(cube_root)).decode() == ciphertext
def encrypt(key, message): """ Encrypt message with Public Key """ public_key = PublicKey.load_pkcs1(key.encode(ENCODING)) enc_msg = rsa_encrypt(message.encode(ENCODING), public_key) return enc_msg.decode(ISO_ENCODING)
def encrypt_display(self): self.plaintext = self.inputField.get() keylength = self.keylengthRadio.get() # make sure user input is not null and encrypt it if self.plaintext == "": self.displayText["text"] = "No user input!" return # make sure user must select the keylength if keylength == 0: self.displayText["text"] = "You should select the keylength !" return # make sure the input is digit if not self.plaintext.isdigit(): self.displayText["text"] = "Only is allowed input the digit !" return else: p, q, n, e, d, plain, cipher, timeEncrypt = rsa_encrypt( int(self.plaintext), keylength) self.d = d self.p = p self.q = q self.encryptOutputField.delete(0, END) self.encryptOutputField.insert(0, cipher) self.displayText["text"] = "Encrypt success ! Cost Time : " + str( timeEncrypt) + " seconds."
def test_rsa(self): n, p, q, e, d = rsa.rsa_gen_keys() m = random.randint(1, n - 1) em = rsa.rsa_encrypt(n, e, m) dm = rsa.rsa_decrypt(n, d, em) self.assertEqual(m, dm)
def main(): cipher_message = [] # 读取消息,将ASCII码转化为16进制 msg = read_message('./sender/messages.txt').encode() msg = binascii.hexlify(msg).decode('ascii') # des的ECB模式加密消息 des_key = read_message('./sender/des_key.txt') des_cipher = des.ECB_encrypt(msg, des_key) cipher_message.append(des_cipher) # 生成rsa公钥、私钥,并写入文件 rsa_e, rsa_n, rsa_d = rsa.createKey(15) if os.path.isfile('./receiver/rsa_d.txt'): os.remove('./receiver/rsa_d.txt') write_message('./receiver/rsa_d.txt', hex(rsa_d)[2:]) if os.path.isfile('./receiver/rsa_e.txt'): os.remove('./receiver/rsa_e.txt') write_message('./receiver/rsa_e.txt', hex(rsa_e)[2:]) if os.path.isfile('./receiver/rsa_n.txt'): os.remove('./receiver/rsa_n.txt') write_message('./receiver/rsa_n.txt', hex(rsa_n)[2:]) # rsa加密对称密钥 des_key_encrypted = rsa.rsa_encrypt(des_key, rsa_e, rsa_n) cipher_message.append(des_key_encrypted) # sha-1生成消息认证码 sha1_hash = sha1.sha1(des_cipher) # rsa对消息认证码数字签名 signed_hash = rsa.rsa_encrypt(sha1_hash, rsa_d, rsa_n) cipher_message.append(signed_hash) # 将消息密文,RSA加密的对称密钥,数字签名后的sha-1消息认证码发送给接收端程序 sender(','.join(cipher_message).encode()) print('\nSent messages:\n' + ','.join(cipher_message))
def main(): (n, e, N) = read_key_file(PUBKEY_FILE) (n, d, N) = read_key_file(PRIVKEY_FILE) pt = "hello world".encode("utf-8") # do the thing ct = rsa_encrypt(pt, n, (e, N)) nt = rsa_decrypt(ct, n, (d, N)) # how did we do? print("plaintext in:") hexdump(pt, 32) print("ciphertext (padded):") hexdump(ct, 32) print("plaintext out:") hexdump(nt, 32)
def test_rsa(self): # 1. Generating key pair public_key, private_key = rsa.generate_rsa_key_pair(13, 17) # 2. Open file 'rsa_to_enc.txt' & read text file_to_enc = open('resources/lab_3/rsa_to_enc.txt', 'r') normal_text = file_to_enc.read() # 3. Encrypt read text encrypted_text = rsa.rsa_encrypt(public_key, normal_text) print(''.join(map(lambda x: str(x), encrypted_text))) # 4. Encrypt decrypted text decrypted_text = rsa.rsa_decrypt(private_key, encrypted_text) # 5. Save decrypted text to 'decrypted.txt' decrypted_file = open('resources/lab_3/rsa_decrypted.txt', 'w') decrypted_file.write(decrypted_text) self.assertEqual(normal_text, decrypted_text)
def check_signature(msg, sig, e, n, bit_length=1024): p = util.bigint_to_bytes(rsa.rsa_encrypt(sig, e, n)) if len(p) > bit_length / 8: return False #pad to bit_length with leading 0 bytes if len(p) < bit_length / 8: p = '\x00' * (bit_length / 8 - len(p)) + p #check that s^e (mod n) starts with #00 01 FF FF ... FF 00 ASN.1 HASH #check for 00 01 FF if not p.startswith(prefix): return False pos = len(prefix) #move past the rest of the FFs while pos < len(p) and p[pos] == '\xff': pos += 1 #check that there is enough space for 00 ASN.1 HASH if pos + len(pkcs_magic_bytes) + 20 > len(p): return False #check for 00 ASN.1 if p[pos:pos + len(pkcs_magic_bytes)] != pkcs_magic_bytes: return False pos += len(pkcs_magic_bytes) #check that hash matches message return p[pos:pos + 20] == util.sha1sum(msg)
import number_theory import rsa import util #see: https://people.freebsd.org/~lstewart/references/apple_tr_kt32_cuberoot.pdf #for computing cube roots if __name__ == '__main__': #get 3 RSA keys all with e = 3 _, e1, n1 = rsa.gen_key_pair(64) _, e2, n2 = rsa.gen_key_pair(64) _, e3, n3 = rsa.gen_key_pair(64) assert ({e1, e2, e3} == {3}) #if same message is encrypted with all keys m = "hello" c1 = rsa.rsa_encrypt(m, 3, n1) c2 = rsa.rsa_encrypt(m, 3, n2) c3 = rsa.rsa_encrypt(m, 3, n3) #then #c_i = m^3 (mod n_i) #So by CTR we can find m^3 (mod n_1*n_2*n_3) m_cubed = number_theory.crt([c1, c2, c3], [n1, n2, n3]) #m < n_i ==> m^3 < n_1*n_2*n_3 #==> we can find m by taking a normal cube root mp = util.bigint_to_bytes(number_theory.ith_root(m_cubed, 3)) assert (m == mp) print 'Recovered message:', mp
# # ==> 2^(i + 1)*m in [n*lower_{i + 1}, n*(lower_{i + 1} + 1)] # ==> m in [n*lower_{i + 1}/2^(i + 1), n*upper_{i + 1}/2^(i + 1)] # Note: invariant 3 still holds lower <<= 1 else: # 2^(i + 1)*m - 2n*lower in [n, 2n] # ==> 2^(i + 1)*m in [n*(2*lower + 1), n*(2*lower + 2)] # ==> 2^(i + 1)*m in [n*(2*lower + 1), n*2*upper] # upper_{i + 1} = 2*upper # lower_{i + 1} = 2*upper - 1 # Note: invariant 2 still holds # # ==> 2^(i + 1)*m in [n*lower_{i + 1}, n*upper_{i + 1}] # ==> m in [n*lower_{i + 1}/2^(i + 1), n*upper_{i + 1}/2^(i + 1)] # Note: invariant 3 still holds #(lower + 1) * 2 - 1 = 2*lower + 1 lower = (lower << 1) + 1 i = i + 1 # 2^i >= n ==> #The interval [n*lower/2^i, n*upper/2^i] has width <= 1 #integer division by 2^i rounds down ==> use upper bound to find m return ((lower + 1)*n) >> i if __name__ == '__main__': pt = base64.b64decode('VGhhdCdzIHdoeSBJIGZvdW5kIHlvdSBkb24ndCBwbGF5IGFyb3VuZCB3aXRoIHRoZSBGdW5reSBDb2xkIE1lZGluYQ==') d, e, n = rsa._sample_params ct = rsa.rsa_encrypt(pt, e, n) print util.bigint_to_bytes(decrypt(ct, e, n, lambda ct: oracle(ct, d, n)))
def lock_files(files_to_lock, rsa_private_key, rsa_public_key, output='archive', secure_delete=False): """Lock files. This function lock `files_to_lock` in an archive `output` using RSA private key `rsa_private_key` and RSA public key `rsa_public_key`. :parameter: files_to_lock : list A list of files to lock. rsa_private_key : string RSA private key rsa_public_key : string RSA public key output : string The output name of the archive. "archive" by default. secure_delete : boolean True if the user want to securely delete his `files_to_lock`. """ try: starttime = time.time() ####################################################################### # Keys generation and importation ####################################################################### # Importe RSA key from PEM rsa_private_key = RSA.importKey(open(rsa_private_key).read()) rsa_public_key = RSA.importKey(open(rsa_public_key).read()) # Generate AES key and iv aes_key = aes.gen_aes_key(AES_KEY_SIZE) aes_iv = aes.gen_iv(AES_BLOCK_SIZE) encrypted_key = rsa.rsa_encrypt(rsa_public_key, aes_key) f = open('cipherkey.lkd', 'w') f.write(encrypted_key) f.close() ####################################################################### # Encryption and MAC of the files ####################################################################### # Put file in a tar archive archive = tools.tarfiles(files_to_lock, 'source.tar') archive_data = open(archive, mode='rb') raw = archive_data.read() archive_data.close() # Encrypt the tar file cipherdata = \ aes.aes_encrypt(AES_BLOCK_SIZE, aes_iv, aes_key, raw) # Save cipher data out = open('encrypted_files.lkd', 'w') out.write(str(cipherdata)) out.close() # Tar cipherkeys, cipherfile and mac file toghether finalfiles = ['cipherkey.lkd', 'encrypted_files.lkd'] ciphertar = tools.tarfiles(finalfiles, 'encrypted_files_and_key.lkd') f = open(ciphertar, mode='rb') ciphertardata = f.read() f.close() # Sign data with private key rsa_signature = rsa.rsa_sign(rsa_private_key, ciphertardata) # Save signature f = open('encrypted_files_and_key.lkd.sign', 'w') f.write(rsa_signature) f.close() # Archive signed file and signature together tools.tarfiles(['encrypted_files_and_key.lkd.sign', 'encrypted_files_and_key.lkd'], output+'.lkd') # Secure delete temp files files_to_delete = ['encrypted_files_and_key.lkd.sign', 'encrypted_files.lkd', 'cipherkey.lkd', archive, ciphertar] for file in files_to_delete: success = tools.secure_delete(file) if not success: print('[error] Something went wrong during the secure file ' 'delete ' 'of ' + file + ', make sure your erase it manually.') # Secure delete sources files if secure_delete: for file in files_to_lock: success = tools.secure_delete(file) if not success: print('[error] Something went wrong during the secure' ' file delete of ' + file + ', make sure your erase it manually.') endtime = time.time() elapsedtime = endtime - starttime print("[info] The files have been successfuly " "locked in %f seconds." % elapsedtime) except AttributeError: print('[error] A method was called with a false attribute.') sys.exit() except IOError: print('[error] Maybe one of your files does not exist') sys.exit() except: print('[error] An unexpected error occurred when locking files.') sys.exit()
def get_ct(self): pt = "%d something" % int(time.time()) ct = rsa.rsa_encrypt(pt, self._e, self._n) self._seen.add(ct) return ct
f.write(resp.content) captcha = raw_input(u'请输入验证码:') # ========================== 检查验证码输入是否正确 =================================== check_captcha_url = 'https://user.lu.com/user/captcha/pre-check' params = {'inputValue': captcha, 'source': 'login', '_': get_timestamp()} resp = session.get(check_captcha_url, headers=headers, params=params) result = json.loads(resp.text) print result if result.get('result') == 'SUCCESS': # ========================== 验证码输入正确则进行登录 ==================================== login_url = 'https://user.lu.com/user/login' data = { 'isTrust': 'Y', 'password': rsa_encrypt(password), 'openlbo': '0', 'deviceKey': '1DA04D5FA06A3DF9351172402D3736E93F5AD7BB4422E6181D17A9C9FE55ABD323517C5B01B09D1254E255600623E57D294B58C7CDAEF4FAA973316CFCAA9CE4E8DD889CF3874E1E9AFFF57FAED8789446D8C69DED5D2EDBAFC73A3B262BF9ED060D16D364AC30720DF3B707A1E81DC89D36822E679D61A3B732A28A02D84678', 'deviceInfo': 'ALxyJ/Hzq1cZXHj+WaUCFi8QMlvz0AkQLB8PE6s8VkmRvQy8v9ALWBjtK6pMCjjElX38kes1jGTKpuNvCqZdwQTDF2YVkoL53zgkMEsgO95ZZV1knicKDZ47IZYGXn9neALil2mOa1uOhco5IRMpHT3dJ+JMNg3L1rNEqAGqoX5sQQ51R/R68T22iAMFll6bXUTJTM6Qqlp8ZtijSDwADPEr2bCSlgvmnVcmPdXHXL3nmufjhJ9p7Y44ZuJ/X8MXg6TD77Gdl0DqXd4j70V8X0REudlB4mmvm0uUI8u/kJbjvLLMmpn8lz55bVxHEcFmncEadDFHqYqz31pVb32N4y7/a4bYw5ccPuV6MWX/ZQcdOwGMKQuIvBbbhv70sZZgaO3Qcksp57oPYZFs1zOKYTQDPHHPCmm8HSMq8oauUUfsquo02hA9a47t6A0lDAxuTEQK5RAkdNA3xJyTWfIWqgsDKiRyDQt51jxIZN4DQceUbZBu68xPABxqHUECt07/hiLBrWrQE2O1XzFt3D7WtIMHmAsMe1x/EaLugBMOv7mw4s5cbAjGrL1c5SqfFiTod3NJw2Bo8ZvXMWkpYIV6RtIyvAEaOeY1WMIb+zGei03ZN3Cdwut7mFJ230sPN15QAErZ5Awtax4JUvq4eG2GZoGIUj/sE7Xy7YVhN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pmm0XqDfp22WqYR773fel51+PZlNTnGe36fB/ISq3mPhLT0MRT1wIWNlpSeazF1BRzm/8pQ4zAGGlvhSTPbmk4+rTEKsZAPebNFFZby7bnejbrk08gKxQrOF1Y++bDNublsYSuApqLemsFSrbr9+wSINjcbkPssrpTJ1xTruh7wqIX7xb1Rxnt+nwfyEqt5j4S09DEU9ciijFQphNS/MesGkl8B3xQZdCGuncowPu7RtxZJLa9U+EtV2WngFY/jCKu1I2ShljZkBMTc1vsT7gcgXkuvIFHLrDb8DvNgoXThmy6XSR83NM4cTvgwCmju0TjFixTlehQRuNuPJhLpMwnQadxfDZMxVJiKwyHHITOhKN+5ffnauI3P54xpTKTS2XwHuV39FFFZnruC/ZMuaddvfdsoG+OyLRC+aEHskAvQmjgqAn6A1XLgKb00j17b6dgMeDQrBLBR/YCNna3E/eT7CRuDLYmd+q7nDrHty/wWqlj6HIAc3cK74/rPkQ0nc73kZ6aU4gtaO2N4181o7PiA3r2CmUxGEVBU0EuT67I+euvujAmNvEfazqACN+T7zFttAb2wsrf9ESMJG10w4nzLQu4Tay62D0hZM/kAZj058L9617hTxsoZ/Zyb4MrlzcxAjNyH8s=', 'loginFlag': '2', 'hIsOpenLboAccStatus': '0', 'hIsSignLboUserCrsChecked': '0', 'userName': username, 'pwd': '************', 'validNum': captcha, 'agreeLbo': 'on', 'agreeLbo': 'on', 'agreeLbo': 'on', 'agreeLbo': 'on',
disconnected = False prog_is_alive = True HOST, PORT = '127.0.0.1', 9090 nickname = '' if __name__ == '__main__': try: while prog_is_alive: server_listener = Server_listener() sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) connect_to_server(HOST, PORT) #establishing a secure connection tagged_server_pub = sock.recv(1024) server_pub = PublicKey.load_pkcs1(tagged_server_pub) xor_encrypted_key = rsa_encrypt(xor_key, server_pub) sock.send(xor_encrypted_key) disconnected = False nickname = pick_username() server_listener.start() user_colors[nickname] = colors['blue'] while not disconnected: message = get_msg() if len(message) > 255: add_str('system: 255 symbols message limit') continue if not (message.strip() in ('', '\n', '\t', '\r')): if message[0] == '!': command = parse_command(message) if command:
def test_create_keypair(): keypair = RSAKeypair.create(e=3) assert rsa_decrypt(rsa_encrypt("bob", keypair), keypair) == "bob"
if padding_oracle((pow(s, e, n) * c) % n): found = True break s += 1 r += 1 a, b = _step3([(a, b)], B, n, s)[0] return b if __name__ == '__main__': #don't want to have to wait for key generation each time #256 bit key #d, e, n = (37255313119928308596958693738000904270148055374803475499902820648455212368979L, 3, 55882969679892462895438040607001356405695530651745489982532299779733176320093L) d, e, n = rsa._sample_params m = 'Hello Adrian.' mod_len = pkcs1.num_bytes(n) B = 1 << (8 * mod_len - 16) M = util.bytes_to_bigint(pkcs1.pkcs1_pad(m, mod_len)) c = rsa.rsa_encrypt(M, e, n) p = decrypt(c, e, n, lambda c: fast_oracle(c, d, n, 2 * B, 3 * B)) p = util.bigint_to_bytes(p) #pad start with 0s so it has same length as modulus p = '\x00' * (mod_len - len(p)) + p p = pkcs1.pkcs1_unpad(p, mod_len) print p assert (p == m)
while rsa.check_MSB(p) or rsa.ckeck_coprime_e(p, e): p = generator.findPrime() q = generator.findPrime() while p == q or rsa.check_MSB(q) or rsa.ckeck_coprime_e(q, e): q = generator.findPrime() n_set.add(p * q) n_set = list(n_set) with open(sys.argv[6], "w") as f: for i in n_set: f.write(str(i)) f.write("\n") # encrypt the file with 3 keys for i in range(3): # encrypt the file by C = M^e mod n through Modular Exponentiation encryptedText = rsa.rsa_encrypt(sys.argv[2], e, n_set[i]) # transform the ciphertext into the hex string and write out to the file with open(sys.argv[i + 3], 'w') as f: f.write(encryptedText.get_hex_string_from_bitvector()) # decrypt the file with cube-root M^3 mod n1*n2*n3 # python breakRSA.py -c enc1.txt enc2.txt enc3.txt n_1_2_3.txt cracked.txt if sys.argv[1] == "-c": n_list = [] with open(sys.argv[5], "r") as f: for i in range(3): n_list.append(int(f.readline().strip())) # decrypt file by M = C^d mod n throgh Chinese Remainder Theorem decryptedText = decrypt(sys.argv[2], sys.argv[3], sys.argv[4], n_list) with open(sys.argv[6], "w") as f: f.write(decryptedText.get_text_from_bitvector())