def setUp(self): comps = "Cryptodome.SelfTest.Signature.test_vectors.wycheproof".split(".") with open(pycryptodome_filename(comps, "rsa_signature_test.json"), "rt") as file_in: tv_tree = json.load(file_in) class TestVector(object): pass self.tv = [] for group in tv_tree['testGroups']: key = RSA.import_key(group['keyPem']) hash_name = group['sha'] if hash_name == "SHA-256": hash_module = SHA256 elif hash_name == "SHA-224": hash_module = SHA224 elif hash_name == "SHA-1": hash_module = SHA1 else: assert False assert group['type'] == "RSASigVer" for test in group['tests']: tv = TestVector() tv.id = test['tcId'] tv.comment = test['comment'] for attr in 'msg', 'sig': setattr(tv, attr, unhexlify(test[attr])) tv.key = key tv.hash_module = hash_module tv.valid = test['result'] != "invalid" tv.warning = test['result'] == "acceptable" self.tv.append(tv)
def encryptDataWithPubKey(data, pubKeyFile=RSA_pubKeyFile, outFile=None): from Cryptodome.PublicKey import RSA from Cryptodome.Random import get_random_bytes from Cryptodome.Cipher import AES, PKCS1_OAEP recipient_key = RSA.import_key(open(pubKeyFile).read()) session_key = get_random_bytes(16) # Encrypt the session key with the public RSA key cipher_rsa = PKCS1_OAEP.new(recipient_key) # Encrypt the data with the AES session key cipher_aes = AES.new(session_key, AES.MODE_EAX) ciphertext, tag = cipher_aes.encrypt_and_digest(data) print () print (ciphertext) print () print (tag) print () if outFile: file_out = open(outFile, "wb") file_out.write(cipher_rsa.encrypt(session_key)) [ file_out.write(x) for x in (ciphertext.nonce, tag, ciphertext) ]
def sign_string(message, pem_private, pem_passphrase="", sign_algo="SHA384"): """ Generate a signature for string using the `sign_algo` and `RSA` algorithms. """ from Cryptodome.PublicKey import RSA from Cryptodome.Signature import PKCS1_v1_5 from binascii import b2a_hex if sign_algo not in ("MD5", "SHA1", "SHA256", "SHA384", "SHA512"): raise ValueError("Unsupported Signing algorithm") priv_key = RSA.import_key(pem_private, passphrase=pem_passphrase) signer = PKCS1_v1_5.new(priv_key) digest = getattr( __import__("Cryptodome.Hash", fromlist=[sign_algo]), sign_algo ).new() digest.update(message) return b2a_hex(signer.sign(digest))
def key_importer(secret_phrase,menuEncoded): prikey_bytes=open("Serverprivatekey.der","rb").read() restored_keypair=RSA.import_key(prikey_bytes,passphrase=secret_phrase) pubkey_bytes=open("Serverpublickey.pem","r").read() restored_pubkey=RSA.import_key(pubkey_bytes) return signer(restored_keypair , restored_pubkey , menuEncoded)
def read_key(self, k): try: key = RSA.import_key(k) return key except IOError as e: print(e)
def msg_received_get(): for row in c.execute("SELECT address,openfield,timestamp FROM transactions WHERE recipient = ? AND (openfield LIKE ? OR openfield LIKE ? OR openfield LIKE ? OR openfield LIKE ?) ORDER BY timestamp DESC;", (address,) + ("msg=" + '%',) + ("bmsg=" + '%',) + ("enc=msg=" + '%',) + ("enc=bmsg=" + '%',)): # get alias try: c2.execute("SELECT openfield FROM transactions WHERE openfield LIKE ? AND address = ? ORDER BY block_height ASC, timestamp ASC LIMIT 1;", ("alias=" + '%', row[0],)) # asc for first entry msg_address = c2.fetchone()[0] # get alias except: msg_address = row[0] if row[1].startswith("enc=msg="): msg_received_digest = row[1].lstrip("enc=msg=") try: #msg_received_digest = key.decrypt(ast.literal_eval(msg_received_digest)).decode("utf-8") (cipher_aes_nonce, tag, ciphertext, enc_session_key) = ast.literal_eval(msg_received_digest) private_key = RSA.import_key(open("privkey.der").read()) # Decrypt the session key with the public RSA key cipher_rsa = PKCS1_OAEP.new(private_key) session_key = cipher_rsa.decrypt(enc_session_key) # Decrypt the data with the AES session key cipher_aes = AES.new(session_key, AES.MODE_EAX, cipher_aes_nonce) msg_received_digest = cipher_aes.decrypt_and_verify(ciphertext, tag).decode("utf-8") except: msg_received_digest = "Could not decrypt message" elif row[1].startswith("enc=bmsg="): msg_received_digest = row[1].lstrip("enc=bmsg=") try: msg_received_digest = base64.b64decode(msg_received_digest).decode("utf-8") #msg_received_digest = key.decrypt(ast.literal_eval(msg_received_digest)).decode("utf-8") (cipher_aes_nonce, tag, ciphertext, enc_session_key) = ast.literal_eval(msg_received_digest) private_key = RSA.import_key(open("privkey.der").read()) # Decrypt the session key with the public RSA key cipher_rsa = PKCS1_OAEP.new(private_key) session_key = cipher_rsa.decrypt(enc_session_key) # Decrypt the data with the AES session key cipher_aes = AES.new(session_key, AES.MODE_EAX, cipher_aes_nonce) msg_received_digest = cipher_aes.decrypt_and_verify(ciphertext, tag).decode("utf-8") except: msg_received_digest = "Could not decrypt message" elif row[1].startswith("bmsg="): msg_received_digest = row[1].lstrip("bmsg=") try: msg_received_digest = base64.b64decode(msg_received_digest).decode("utf-8") except: msg_received_digest = "Could not decode message" elif row[1].startswith("msg="): msg_received_digest = row[1].lstrip("msg=") msg_received.insert(INSERT, ((time.strftime("%Y/%m/%d,%H:%M:%S", time.gmtime(float(row[2])))) + " From " + msg_address.replace("alias=", "") + ": " + msg_received_digest) + "\n")
n = ui['realName'] logger.info(f'{u} {uu} {n}') with open('userinfo.py', 'w+', encoding='utf-8') as f: f.writelines(f'USER = {u}\n') f.writelines(f'NAME = "{n}"\n') logger.info('Login OK.') return u, n if __name__ == '__main__': logging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s', level=logging.INFO) logger = logging.getLogger() logger.info('I love studying! Study makes me happy!') rsa_key = RSA.import_key(open('key.pem', 'r').read()) public_key = RSA.import_key(open('public.pem', 'r').read()) yzm_key = RSA.import_key(open('yzm.pem', 'r').read()) app_key = utils.md5_digest(str(uuid.uuid4()).replace('-', '')) s = requests.Session() s.headers.update({ 'User-Agent': 'Dalvik/2.1.0 (Linux; U; Android 8.1.0; Pixel 2 XL Build/OPM1.171019.021)', 'Accept-Encoding': 'gzip' }) try: import userinfo user = userinfo.USER
from Cryptodome.Cipher import AES, PKCS1_OAEP from Cryptodome.Random import get_random_bytes from Cryptodome.PublicKey import RSA from string import ascii_lowercase, ascii_uppercase, digits from random import choice re_text = ascii_uppercase + ascii_lowercase + digits print(re_text) for i in range(1, 700): data = ''.join(choice(re_text) for _ in range(736 * 68)) with open('..\\test\\{}'.format(i), 'wb') as out_file: recipient_key = RSA.import_key(open('key\\my_rsa_public.pem').read()) session_key = get_random_bytes(32) cipher_rsa = PKCS1_OAEP.new(recipient_key) out_file.write(cipher_rsa.encrypt(session_key)) cipher_aes = AES.new(session_key, AES.MODE_EAX) data = data.encode() ciphertext, tag = cipher_aes.encrypt_and_digest(data) out_file.write(cipher_aes.nonce) out_file.write(tag) out_file.write(ciphertext)
def process_otherPubKey(self, aotherPubKey): self.otherPubKey = RSA.import_key(aotherPubKey)
def decode_rsa(self, data): priv = PKCS1_OAEP.new(RSA.import_key(self.private_key)) self.decode_raw(priv.decrypt(data))
def encode_rsa(self): publ = PKCS1_OAEP.new(RSA.import_key(self.other_key)) return publ.encrypt(f'{self.msgType} {self.msgValue}'.encode('utf8'))
def ClientRSAPublicKeyreceive(conn): receivedClientPublicRSAKey = RSA.import_key(receive_data(conn)) # Return the RSA key return receivedClientPublicRSAKey
from Cryptodome.PublicKey import RSA from Cryptodome.Cipher import AES, PKCS1_OAEP code = 'nooneknows' with open('encrypted_data.bin', 'rb') as fobj: private_key = RSA.import_key(open('my_rsa_key.pem').read(), passphrase=code) enc_session_key, nonce, tag, ciphertext = [ fobj.read(x) for x in (private_key.size_in_bytes(), 16, 16, -1) ] cipher_rsa = PKCS1_OAEP.new(private_key) session_key = cipher_rsa.decrypt(enc_session_key) cipher_aes = AES.new(session_key, AES.MODE_EAX, nonce) data = cipher_aes.decrypt_and_verify(ciphertext, tag) print(data)
async def sha256_rsa_checker(name: FormalName, sig: SignaturePtrs, key_bits=None) -> bool: sig_info = sig.signature_info if len(bytes(sig.signature_value_buf)) == 0: # For conditions without signature return True # print("Signature type: ", sig_info.signature_type) if key_bits is None: # Default RSA key key_bits = bytes([ 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00, 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01, 0x00, 0xb8, 0x09, 0xa7, 0x59, 0x82, 0x84, 0xec, 0x4f, 0x06, 0xfa, 0x1c, 0xb2, 0xe1, 0x38, 0x93, 0x53, 0xbb, 0x7d, 0xd4, 0xac, 0x88, 0x1a, 0xf8, 0x25, 0x11, 0xe4, 0xfa, 0x1d, 0x61, 0x24, 0x5b, 0x82, 0xca, 0xcd, 0x72, 0xce, 0xdb, 0x66, 0xb5, 0x8d, 0x54, 0xbd, 0xfb, 0x23, 0xfd, 0xe8, 0x8e, 0xaf, 0xa7, 0xb3, 0x79, 0xbe, 0x94, 0xb5, 0xb7, 0xba, 0x17, 0xb6, 0x05, 0xae, 0xce, 0x43, 0xbe, 0x3b, 0xce, 0x6e, 0xea, 0x07, 0xdb, 0xbf, 0x0a, 0x7e, 0xeb, 0xbc, 0xc9, 0x7b, 0x62, 0x3c, 0xf5, 0xe1, 0xce, 0xe1, 0xd9, 0x8d, 0x9c, 0xfe, 0x1f, 0xc7, 0xf8, 0xfb, 0x59, 0xc0, 0x94, 0x0b, 0x2c, 0xd9, 0x7d, 0xbc, 0x96, 0xeb, 0xb8, 0x79, 0x22, 0x8a, 0x2e, 0xa0, 0x12, 0x1d, 0x42, 0x07, 0xb6, 0x5d, 0xdb, 0xe1, 0xf6, 0xb1, 0x5d, 0x7b, 0x1f, 0x54, 0x52, 0x1c, 0xa3, 0x11, 0x9b, 0xf9, 0xeb, 0xbe, 0xb3, 0x95, 0xca, 0xa5, 0x87, 0x3f, 0x31, 0x18, 0x1a, 0xc9, 0x99, 0x01, 0xec, 0xaa, 0x90, 0xfd, 0x8a, 0x36, 0x35, 0x5e, 0x12, 0x81, 0xbe, 0x84, 0x88, 0xa1, 0x0d, 0x19, 0x2a, 0x4a, 0x66, 0xc1, 0x59, 0x3c, 0x41, 0x83, 0x3d, 0x3d, 0xb8, 0xd4, 0xab, 0x34, 0x90, 0x06, 0x3e, 0x1a, 0x61, 0x74, 0xbe, 0x04, 0xf5, 0x7a, 0x69, 0x1b, 0x9d, 0x56, 0xfc, 0x83, 0xb7, 0x60, 0xc1, 0x5e, 0x9d, 0x85, 0x34, 0xfd, 0x02, 0x1a, 0xba, 0x2c, 0x09, 0x72, 0xa7, 0x4a, 0x5e, 0x18, 0xbf, 0xc0, 0x58, 0xa7, 0x49, 0x34, 0x46, 0x61, 0x59, 0x0e, 0xe2, 0x6e, 0x9e, 0xd2, 0xdb, 0xfd, 0x72, 0x2f, 0x3c, 0x47, 0xcc, 0x5f, 0x99, 0x62, 0xee, 0x0d, 0xf3, 0x1f, 0x30, 0x25, 0x20, 0x92, 0x15, 0x4b, 0x04, 0xfe, 0x15, 0x19, 0x1d, 0xdc, 0x7e, 0x5c, 0x10, 0x21, 0x52, 0x21, 0x91, 0x54, 0x60, 0x8b, 0x92, 0x41, 0x02, 0x03, 0x01, 0x00, 0x01 ]) if sig_info and sig_info.signature_type == SignatureType.SHA256_WITH_RSA: startTime = time() pub_key = RSA.import_key(key_bits) verifier = pkcs1_15.new(pub_key) h = SHA256.new() for content in sig.signature_covered_part: logging.debug("Hash content {}".format(bytes(content))) h.update(content) try: logging.debug("Signature value {}".format( bytes(sig.signature_value_buf))) verifier.verify(h, bytes(sig.signature_value_buf)) except ValueError: logging.info( f'{Name.to_str(name)} => Unable to verify the signature') return False logging.debug(f'{Name.to_str(name)} => Verification passed') logging.debug("Validation time is {}".format(time() - startTime)) return True else: print("Validator return true by default") return True
def create_current_encrypt(self, current_chat_key): """Create an encryption object.""" self.current_encrypt = PKCS1_OAEP.new( key=RSA.import_key(current_chat_key), hashAlgo=self.HASH_FUNCTION)
def test_import_key(self): """Verify that import_key is an alias to importKey""" key = RSA.import_key(self.rsaPublicKeyDER) self.failIf(key.has_private()) self.assertEqual(key.n, self.n) self.assertEqual(key.e, self.e)
# *** Important Note: This part should be executed only after executing 'part1.2.py' *** from Cryptodome.PublicKey import RSA from Cryptodome.Signature import PKCS1_PSS from Cryptodome.Hash import MD5 if __name__ == '__main__': # Verifying the Signature Generated From part1.2 keyFile = open('pubKey.pem', 'r') # Open the file containing the public key pubKey = RSA.import_key(keyFile.read( )) # Importing the public key from the file created in the previous part verifier = PKCS1_PSS.new(pubKey) # Creating a verifier with the public key messageFile = open('message.txt', 'r') # Open the file containing the message for read message = messageFile.read() # Read the message messageInByte = str.encode( message ) # Encode the message to bytes (the API accept text encoded in bytes) md5Hash = MD5.new(messageInByte) # Generate the MD5 hash of the message signFile = open('signature.txt', 'rb') # Open the file containing the signature for read signature = signFile.read() # Saving the signature isAuth = verifier.verify( md5Hash, signature) # Checking wether the signature is authentic or not if (isAuth): print("The signature is authentic.") else: print("The signature is not authentic.") # Finished Verifying
#!/usr/bin/env python3 from Cryptodome.Util.number import inverse, long_to_bytes from Cryptodome.PublicKey import RSA with open("us_government.pem") as f: N_us = RSA.import_key(f.read()).n with open("german_government.pem") as f: N_ger = RSA.import_key(f.read()).n with open("russian_government.pem") as f: N_rus = RSA.import_key(f.read()).n C_ger = 3999545484320691620582760666106855727053549021662410570083429799334896462058097237449452993493720397790227435476345796746350169898032571754431738796344192821893497314910675156060408828511224220581582267651003911249219982138536071681121746144489861384682069580518366312319281158322907487188395349879852550922320727712516788080905540183885824808830769333571423141968760237964225240345978930859865816046424226809982967625093916471686949351836460279672029156397296634161792608413714942060302950192875262254161154196090187563688426890555569975685998994856798884592116345112968858442266655851601596662913782292282171174885 C_us = 7156090217741040585758955899433965707162947606350521948050112381514262664247963697650055668324095568121356193295269338497644168513453950802075729741157428606617001908718212348868412342224351012838448314953813036299391241983248160741119053639242636496528707303681650997650419095909359735261506378554601448197330047261478549324349224272907044375254024488417128064991560328424530705840832289740420282298553780466036967138660308477595702475699772675652723918837801775022118361119700350026576279867546392616677468749480023097012345473460622347587495191385237437474584054083447681853670339780383259673339144195425181149815 C_rus = 9343715678106945233699669787842699250821452729365496523062308278114178149719235923445953522128410659220617418971359137459068077630717894445019972202645078435758918557351185577871693207368250243507266991929090173200996910881754217374691865096976051997491208921880703490275111904577396998775470664002942232492755888378994040358902392803421017545356248082413409915177589953816030273082416979477368273328755386893089597798104163894528521114946660635364704437632205696975201216810929650384600357902888251066301913255240181601332549134854827134537709002733583099558377965114809251454424800517166814936432579406541946707525 def root(x, n): high = 1 while high**n < x: high *= 2 low = high // 2 while low < high: mid = ((low + high) // 2) + 1 if low < mid and mid**n < x: low = mid elif high > mid and mid**n > x:
'SHA1': SHA1, 'SHA-224': SHA224, 'SHA-256': SHA256, 'SHA-384': SHA384, 'SHA-512': SHA512, 'SHA3-224': SHA3_224, 'SHA3-256': SHA3_256, 'SHA3-384': SHA3_384, 'SHA3-512': SHA3_512, } public_key_file = sys.argv[1] signed_file = sys.argv[2] key_file = open(public_key_file) public_key = RSA.import_key(key_file.read()) key_file.close() file = open(signed_file, 'r') value = '' dict = {} data_key = '' for line in file.readlines(): if ':' in line: data_key = line.split(':')[0].strip() if data_key != 'Method': value = '' else: value = []
def fromString(self, key_string): if self.keyObject: raise ValueError('key object already exist') self.keyObject = RSA.import_key(key_string) return True
def get_account(filename): if len(filename) == 0: key = new_account() return key newaccount = RSA.import_key(open(filename, 'r').read()) return newaccount
def decode_certificate(encoded_certificate): certificate = b64decode(encoded_certificate).decode() return RSA.import_key(certificate).exportKey("PEM")
def _verify(cls, pub_key_bits, sig_ptrs) -> bool: if sig_ptrs.signature_info.signature_type != SignatureType.SHA256_WITH_RSA: return False pub_key = RSA.import_key(bytes(pub_key_bits)) return verify_rsa(pub_key, sig_ptrs)
def _sign(private_key, msg): key = RSA.import_key(private_key) h = SHA256.new(msg) return pkcs1_15.new(key).sign(h)
def test_positive_1(self): key = RSA.import_key(self.rsa_key) h = SHA256.new(self.msg) verifier = pss.new(key) verifier.verify(h, self.tag)
def test_negative_2(self): key = RSA.import_key(self.rsa_key) h = SHA256.new(self.msg) verifier = pss.new(key, salt_bytes=1000) tag = bytearray(self.tag) self.assertRaises(ValueError, verifier.verify, h, tag)
# Записываем логи logger.info( f'Запущен клиент с парамертами: адрес сервера: {server_address} , ' f'порт: {server_port}, имя пользователя: {client_name}') # Загружаем ключи с файла, если же файла нет, то генерируем новую пару. dir_path = os.path.dirname(os.path.realpath(__file__)) key_file = os.path.join(dir_path, f'{client_name}.key') if not os.path.exists(key_file): keys = RSA.generate(2048, os.urandom) with open(key_file, 'wb') as key: key.write(keys.export_key()) else: with open(key_file, 'rb') as key: keys = RSA.import_key(key.read()) #!!!keys.publickey().export_key() logger.debug("Keys sucsessfully loaded.") # Создаём объект базы данных database = ClientDatabase(client_name) # Создаём объект - транспорт и запускаем транспортный поток try: transport = ClientTransport(server_port, server_address, database, client_name, client_passwd, keys) logger.debug("Transport ready.") except ServerError as error: message = QMessageBox() message.critical(start_dialog, 'Ошибка сервера', error.text) exit(1) transport.setDaemon(True)
def encrypt_data(public_key, data): cipher = RSA.import_key(public_key) recipient_key = PKCS1_v1_5.new(cipher) encrypt_data = recipient_key.encrypt(data) # hex_data = binascii.hexlify(encrypt_data).decode('utf-8') return encrypt_data
private_key = key.export_key() print(f'Private key: {key.size_in_bytes()}') file_out = open("private.pem", "wb") file_out.write(private_key) # gets the public key from memory public_key = key.publickey().export_key() print(f'Public key: {key.publickey().size_in_bytes()}') file_out = open("receiver.pem", "wb") file_out.write(public_key) # some message encoded into bytes data = "I met aliens in UFO. Here is the map.".encode("utf-8") file_out = open("encrypted_data.bin", "wb") # read some public key and create a public_key object recipient_key = RSA.import_key(open("receiver.pem").read()) session_key = get_random_bytes(16) # Encrypt the session key with the public RSA key cipher_rsa = PKCS1_OAEP.new(recipient_key) enc_session_key = cipher_rsa.encrypt(session_key) # Encrypt the data with the AES session key cipher_aes = AES.new(session_key, AES.MODE_EAX) ciphertext, tag = cipher_aes.encrypt_and_digest(data) [ file_out.write(x) for x in (enc_session_key, cipher_aes.nonce, tag, ciphertext) ]
def decrypt_data(hex_data): pri_key = RSA.import_key(open('./pri.key').read(), ) cipher = PKCS1_v1_5.new(pri_key) # en_data = binascii.unhexlify(hex_data.encode('utf-8')) data = cipher.decrypt(hex_data, None) return data
print("Command output : ", d_files) elif int(float(command)) == -1333407573: print("") user_input = raw_input(str("Custom Dir : ")) custom_dir_aes = AES256() euser_input = custom_dir_aes.encrypt(user_input) send_one_message(conn, str(euser_input).encode()) print "" print "Encrypted user response sent" ae_key3 = custom_dir_aes.get_key() apubKey3 = RSA.import_key(known_hosts[0]) encryptor3 = PKCS1_OAEP.new(apubKey3) e_key3 = encryptor3.encrypt(ae_key3) send_one_message(conn, e_key3) print "" print "Encrypted key sent" efiles3 = recv_one_message(conn) efiles3 = efiles3.decode() dfiles3 = AES256.decrypt(efiles3, custom_dir_aes.get_key()) print "" print dfiles3 # 'download_file' elif int(float(command)) == -1469341932:
def q1_break_poor_rsa(rsa_keys): """Question 1 : Breaking RSA keys with poor randomness The RSA public key encryption and digital signature schemes (named after its creators Rivest, Shamir, and Adleman) essentially relies upon the hardness of factoring. An RSA private key consists of two prime numbers `p` and `q`, and the corresponding public key equals the product of the two primes `N = p * q`. The RSA scheme relies upon good sources of randomness when generating the private key: if your entropy source isn't strong, and several people on the Internet choose the same `p` **or** the same `q`, then the scheme will break. And by this point in the class I think you can see where I'm going with this. Unfortunately, this kind of poor random key generation is exactly what has happened with many computers on the Internet, as shown by https://ia.cr/2012/064 and several subsequent papers. Your Task: Given the list of RSA keys in `rsa_keys`, crack as many of the RSA keys as you can. Do **not** try a brute force attack to factor the public keys (that's the next problem), but instead use the fact that factors might be repeated between keys. Args: One of the common ways public/private RSA keys are stored and transmitted is by using one of the X509 File Extensions (`.CRT`, `.PEM`, ...). In this lab, we'll use the `.PEM` extension to handle the public keys. For example, given the public key file `pub_key.pem`, you can use Python as follows to decode the key: ``` from Cryptodome.PublicKey import RSA pem1 = open("pub_key.pem", 'r').read() k1 = RSA.importKey(pem1) ``` In this problem, your input `rsa_keys` will be a list of strings that represents RSA keys in PEM ecoding. For example, to decode the first RSA key in the input list, you can do the following: `k1 = RSA.importKey(rsa_keys[0])` Output: ret (list(Cryptodome.PublicKey.RSA.RsaKey)): A list containing all the private keys of the cracked RSA keys. Note: - The number of bad RSA keys is not always equal to the number of given keys, so don't assume any fixed number. - Given an `n`, `e` and `d` (private exponent), you can create an instance of the `Cryptodome.PublicKey.RSA.RsaKey` object as follows: ``` from Cryptodome.PublicKey import RSA n = 133 e = 5 d = 65 priv_key = RSA.construct((n, e, d), False) # False is passed to # disable parameter checks ``` How to verify your solution: This problem is inspired from the challenge here: http://www.loyalty.org/~schoen/rsa/ So one way you can verify your solution is to use the keys provided in the challenge. I have already imported the keys in `lab7_helper.challenge_keys` So you can check your implementation as follows: ``` assert(lab7_helper.verify_keys( q1_break_poor_rsa( lab7_helper.challenge_keys ) ) ) ``` """ private_Keys = [] public_keys = [] tuple_indices = [] gcd_clashes = {} for i in range(len(rsa_keys)): k1 = RSA.import_key(rsa_keys[i]).n public_keys.append(k1) e = RSA.import_key(rsa_keys[0]).e for j in range(0, len(public_keys)): for i in range(0, len(public_keys)): if j == i: continue val = math.gcd(public_keys[j], public_keys[i]) if val != 1: tuple_indices.append((j, i)) gcd_clashes[val] = list(tuple_indices) tuple_indices.clear() commonFactors = list(gcd_clashes.keys()) for values in commonFactors: keysToAttack = gcd_clashes[values] for keys in keysToAttack: temp_key1 = public_keys[keys[0]] temp_key2 = public_keys[keys[1]] a = temp_key1 // values c = temp_key2 // values n1 = a * values n2 = c * values phi_n1 = (values - 1) * (a - 1) phi_n2 = (values - 1) * (c - 1) d1 = MMI(e, phi_n1) d2 = MMI(e, phi_n2) priv_key1 = RSA.construct((n1, e, int(d1)), False) priv_key2 = RSA.construct((n2, e, int(d2)), False) private_Keys.append(priv_key1) private_Keys.append(priv_key2) return private_Keys
def encrypt_str(data): public_key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDc+CZK9bBA9IU+gZUOc6FUGu7yO9WpTNB0PzmgFBh96Mg1WrovD1oqZ+eIF4LjvxKXGOdI79JRdve9NPhQo07+uqGQgE4imwNnRx7PFtCRryiIEcUoavuNtuRVoBAm6qdB0SrctgaqGfLgKvZHOnwTjyNqjBUxzMeQlEC2czEMSwIDAQAB" rsakey = RSA.import_key(base64.b64decode(public_key)) # 导入读取到的公钥 cipher = PKCS1_v1_5.new(rsakey) # 生成对象 cipher_text = base64.b64encode(cipher.encrypt(data.encode(encoding="utf-8"))) return cipher_text
def get_RSA_publicKey(passPhrase): encoded_key = open(RSA_privKeyFile, "rb").read() key = RSA.import_key(encoded_key, passphrase=passPhrase) return key.publickey().exportKey()