def load_client_wallet(configfile): walletfile = configfile + '.wlt' walletcfg = ConfigParser.ConfigParser() try: walletcfg.readfp(open(walletfile)) except IOError: configcontent = ConfigParser.ConfigParser() configcontent.add_section('client') return 'new', RSA.generate(4096), configcontent try: files = pickle.loads(base64.b64decode(walletcfg.get('settings', 'files'))) except: files = 'new' try: rsacontent = pickle.loads(base64.b64decode(walletcfg.get('settings', 'rsakey'))) except: rsacontent = RSA.generate(4096) try: configcontent = pickle.loads(base64.b64decode(walletcfg.get('settings', 'config'))) except: configcontent = ConfigParser.ConfigParser() configcontent.add_section('client') return files, rsacontent, configcontent
def gen_keys(): print("generate keys ...") # generate master private and public keys rsa = RSA.generate(4096, random_generator) private_pem = rsa.exportKey() print("master private keys: %s" % master_private_key_file) with open(master_private_key_file, 'w') as f: f.write(private_pem) print("master public keys: %s" % master_public_key_file) public_pem = rsa.publickey().exportKey() with open(master_public_key_file, 'w') as f: f.write(public_pem) # generate ghost private and public keys rsa = RSA.generate(4096, random_generator) private_pem = rsa.exportKey() print("ghost private keys: %s" % ghost_private_key_file) with open(ghost_private_key_file, 'w') as f: f.write(private_pem) print("ghost public keys: %s" % ghost_public_key_file) public_pem = rsa.publickey().exportKey() with open(ghost_public_key_file, 'w') as f: f.write(public_pem)
def createAuthFile(self): if os.path.isfile(self.authFileName): debug('Auth file already exists') raise ret255 with open (self.authFileName,'w') as authFile: # bank public key self.secretKey = RSA.generate(2048) publicKey = self.secretKey.publickey() authFile.write(publicKey.exportKey('PEM')) # keys separator authFile.write('@@@@@') # privateKey for ATM atmPrivateKey = RSA.generate(2048) authFile.write(atmPrivateKey.exportKey('PEM')) self.atmPublicKey = atmPrivateKey.publickey() # keys separator authFile.write('@@@@@') # AES encryption key alphabet = string.printable.replace('@','') self.AESKey = ''.join([rand.choice(alphabet) for byte in range(32)]) authFile.write(self.AESKey) print 'created' sys.stdout.flush()
def aes_query_keys(request): data = request.POST try: fo_id = data['fo'] try: aes_user = AESUser.objects.get(box_id=fo_id) except Exception as e: private = RSA.generate(1024) public = private.publickey() aes_user = AESUser(box_id=fo_id, public_rsa=public.exportKey(), secret_rsa=private.exportKey()) aes_user.save() receip_ids = data['recipient'].split(" ") i=0 ret_data = {'n_shared': len(receip_ids)} for id in receip_ids: try: aes_user = AESUser.objects.get(box_id=id) except Exception as e: private = RSA.generate(1024) public = private.publickey() aes_user = AESUser(box_id=id, public_rsa=public.exportKey(), secret_rsa=private.exportKey()) aes_user.save() ret_data[str(i)+"_rsa"] = aes_user.public_rsa i+=1 except Exception as e: print "Errors " + str(e) ret_data={ 'success': False, 'error': str(e) } rdata = json.dumps(ret_data) return HttpResponse(rdata, content_type='application/json')
def test_sshkeys(self): assert isinstance(self.git.getsshkeys(), list) self.assertEquals(len(self.git.getsshkeys()), 0) # not working due a bug? in pycrypto: https://github.com/dlitz/pycrypto/issues/99 if ssh_test: name = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8)) rsa_key = RSA.generate(1024) self.assertTrue(self.git.addsshkey(title=name, key=str(rsa_key.publickey().exportKey(format="OpenSSH")))) self.assertGreater(self.git.getsshkeys(), 0) keys = self.git.getsshkeys() assert isinstance(keys, list) key = self.git.getsshkeys()[0] assert isinstance(key, dict) self.assertTrue(self.git.deletesshkey(key["id"])) name = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8)) rsa_key = RSA.generate(1024) self.assertTrue(self.git.addsshkeyuser(self.user_id, title=name, key=str(rsa_key.publickey().exportKey(format="OpenSSH")))) self.assertGreater(self.git.getsshkeys(), 0) keys = self.git.getsshkeys() assert isinstance(keys, list) key = self.git.getsshkeys()[0] assert isinstance(key, dict) self.assertTrue(self.git.deletesshkey(key["id"]))
def __init__(self, login=os.environ['LOGNAME'], sk_priv=None, ck_priv=None, key_bits=2048): # The login must always be a valid name, one including no # delimiters or other odd characters. At least for the mement # we use the same rules for user names as Project names. if not Project.valid_proj_name(login): raise DvczError("not a valid login: '******'" % login) self._login = login # Caller can supply keys with different sizes. if sk_priv: if sk_priv.size() + 1 != key_bits: sk_priv = None elif ck_priv.size() + 1 != key_bits: ck_priv = None if sk_priv is None: sk_priv = RSA.generate(key_bits) ck_priv = None if ck_priv is None: ck_priv = RSA.generate(key_bits) # To write use # with open(path, 'wb+') as file: # file.write(sk_priv.exportKey('PEM')) # To read use # with open(path, 'rb') as file: sk_priv = RSA.importKey(file.read()) self._sk_priv = sk_priv self._ck_priv = ck_priv self._key_bits = sk_priv.size() + 1
def test_handle_create_payload_calls_get_outbound_entity(self, mock_get_outbound_entity): mock_get_outbound_entity.return_value = DiasporaPost() from_user = Mock(private_key=RSA.generate(2048), handle="*****@*****.**") to_user = Mock(key=RSA.generate(2048).publickey()) entity = DiasporaPost() handle_create_payload(from_user, to_user, entity) assert mock_get_outbound_entity.called
def test_handle_create_payload_builds_an_xml(self): from_user = Mock(private_key=RSA.generate(2048), handle="*****@*****.**") to_user = Mock(key=RSA.generate(2048).publickey()) entity = DiasporaPost() data = handle_create_payload(from_user, to_user, entity) assert len(data) > 0 parts = data.split("=") assert len(parts) == 2 assert parts[0] == "xml" assert len(parts[1]) > 0
def gen_rsa_key_pair_files(merchant_id, merchant_user): RSAkey = RSA.generate(1024) private = RSA.generate(1024) public = private.publickey() fh = open(merchant_id + '_' + merchant_user + '_private.pem', 'w') fh.write(private.exportKey()) fh.close() fh = open(merchant_id + '_' + merchant_user + '_public.pem', 'w') fh.write(public.exportKey()) fh.close()
def test_good_committers(self): """ Test a range of valid parameter values. """ # login, key_bits) self.do_test_good('froggy', 'grinch', None, None, 1024) self.do_test_good('wombat', 'charlie', None, None, 2048) sk_priv = RSA.generate(1024) ck_priv = RSA.generate(1024) self.do_test_good('gorp', 'fred', sk_priv, ck_priv, 1024)
def init_keys(): key_one = RSA.generate(2048) key_two = RSA.generate(2048) key_three = RSA.generate(2048) with open('key_one.der','w') as key_one_file: key_one_file.write(key_one.exportKey(format="DER")) with open('key_two.der','w') as key_two_file: key_two_file.write(key_two.exportKey(format="DER")) with open('key_three.der','w') as key_three_file: key_three_file.write(key_three.exportKey(format="DER")) return (key_one, key_two, key_three)
def test_good_users(self): """ Feed various cominations of known-good parameters to the do_test_good() function. """ # login, key_bits) self.do_test_good('grinch', None, None, 1024) self.do_test_good('charlie', None, None, 2048) sk_priv = RSA.generate(1024) ck_priv = RSA.generate(1024) self.do_test_good('fred', sk_priv, ck_priv, 1024)
def key_get(self, mess, args): """Generates or returns an SSH public key for allowing the bot to access private repositories.""" users = self['users'] if 'users' in self else {} if mess.frm.username not in users: self.log.debug('Adding user {0}'.format(mess.frm.username)) users[mess.frm.username] = {'key': RSA.generate(2048)} user_info = users[mess.frm.username] if 'key' not in user_info: user_info['key'] = RSA.generate(2048) users[mess.frm.username] = user_info self['users'] = users ssh_pub_key = user_info['key'].publickey().exportKey('OpenSSH').decode("utf-8") return "Your public key to grant me access to repositories is:\n{0}".format(ssh_pub_key)
def setUp(self): from Crypto.PublicKey import RSA srv.app.config['TESTING'] = True srv.app.config['V2_SIGNUP'] = 'v2_signup_test' srv.app.config['V2_AUTH'] = 'v2_auth_test' self.actor1 = '*****@*****.**' self.actor1_key = RSA.generate(1024) self.actor2 = '*****@*****.**' self.actor2_key = RSA.generate(1024) self.alone = '*****@*****.**' # no connection guy self.alone_key = RSA.generate(1024) self.app = srv.app.test_client()
def test_do_remote_reject_jwks_signed_with_unknown_key(self): url = "https://example.com/signed_jwks" signing_key = RSAKey(key=RSA.generate(1024), alg="RS256") other_key = RSAKey(key=RSA.generate(1024), alg="RS256") jws = create_signed_jwks(signing_key) responses.add(responses.GET, url, body=jws, status=200, content_type="application/jose") kb = SignedKeyBundle(verification_key=other_key, source=url) with pytest.raises(UpdateFailed) as exc: kb.do_remote() assert "signature" in str(exc.value)
def test_get(self): JWT_PRIVATE_SIGNING_KEY = RSA.generate(2048).exportKey('PEM') JWT_EXPIRED_PRIVATE_SIGNING_KEYS = [RSA.generate(2048).exportKey('PEM'), RSA.generate(2048).exportKey('PEM')] secret_keys = [JWT_PRIVATE_SIGNING_KEY] + JWT_EXPIRED_PRIVATE_SIGNING_KEYS with override_settings(JWT_PRIVATE_SIGNING_KEY=JWT_PRIVATE_SIGNING_KEY, JWT_EXPIRED_PRIVATE_SIGNING_KEYS=JWT_EXPIRED_PRIVATE_SIGNING_KEYS): response = self.client.get(reverse('jwks')) self.assertEqual(response.status_code, 200) actual = json.loads(response.content) expected = { 'keys': [views.JwksView.serialize_rsa_key(key) for key in secret_keys], } self.assertEqual(actual, expected)
def create_auth_file(self, path): try: os.remove(path) except: pass # Create two private key self.server_key = RSA.generate(KEY_SIZE) self.client_key = RSA.generate(KEY_SIZE) # save ATM private key and server public key in file with open(path,'w+') as f: f.write(self.server_key.publickey().exportKey('PEM')) f.write("#####") f.write(self.client_key.exportKey('PEM'))
def __init__(self, methodName='runTest', args=None, **kwargs): """Create the base test object for others to inherit.""" super(BaseTest, self).__init__(methodName, **kwargs) self.args = args rsa_key = RSA.generate(2048) ssh_private_key = rsa_key.exportKey() host_public_key = rsa_key.publickey().exportKey('OpenSSH') BaseTest.TEST_SERVER_AS_DICT['ssh_private_key'] = ssh_private_key BaseTest.TEST_SERVER_AS_DICT['host_public_key'] = host_public_key rsa_key = RSA.generate(2048) ssh_private_key_edit = rsa_key.exportKey() host_public_key_edit = rsa_key.publickey().exportKey('OpenSSH') BaseTest.TEST_SERVER_EDIT_AS_DICT['ssh_private_key'] = ssh_private_key_edit BaseTest.TEST_SERVER_EDIT_AS_DICT['host_public_key'] = host_public_key_edit
def generate(self): """ Generate key and encrypt private key. """ key = RSA.generate(self.RSA_KEYSIZE) privateDer = key.exportKey(format="DER") self.publicKey = key.publickey() self.wrapPrivateKey(privateDer)
def _generateCertificates(self): """ Generates new private RSA keys for the SFTP service. return: Paths to public and private key files. """ from Crypto.PublicKey import RSA from twisted.python.randbytes import secureRandom # get default path pub_file = os.path.join(self.env.config.path, SSH_PUBLIC_KEY) priv_file = os.path.join(self.env.config.path, SSH_PRIVATE_KEY) # generate msg = "Generating new certificate files for the SSH service ..." self.env.log.warn(msg) rsa_key = RSA.generate(1024, secureRandom) # public key pub_key = keys.Key(rsa_key).public().toString('openssh') file(pub_file, 'w+b').write(str(pub_key)) msg = "Private key file %s has been created." self.env.log.warn(msg % pub_file) # private key priv_key = keys.Key(rsa_key).toString('openssh') file(priv_file, 'w+b').write(str(priv_key)) msg = "Private key file %s has been created." self.env.log.warn(msg % priv_file) # write config self.env.config.set('ssh', 'public_key_file', pub_file) self.env.config.set('ssh', 'private_key_file', priv_file) self.env.config.save() return pub_file, priv_file
def generate_key_pair(): # client = lib.transport.client() if(os.path.exists(lib.constants.m_private_key_file)): print("key file already present : {0}".format(lib.constants.m_private_key_file)) f = open(lib.constants.m_private_key_file, "r") key = RSA.importKey(f.read()) public_key = key.publickey().exportKey("PEM") lib.debug.debug(public_key) else: if(not os.path.exists(lib.constants.masterdir)): try: os.makedirs(lib.constants.masterdir) except: print (sys.exc_info()) random_generator = Random.new().read key = RSA.generate(2048, random_generator) private_key_file = open(lib.constants.m_private_key_file, "w") private_key_file.write(key.exportKey("PEM")) private_key_file.flush() private_key_file.close() public_key = key.publickey().exportKey("PEM") lib.debug.debug(public_key) # client.send(message_type_args={lib.constants.msg_keys.tasktype:lib.constants.tasktypes.key_register, # lib.constants.msg_keys.payload :public_key, # # }) print ("done writing private key")
def pair(): key = RSA.generate(2048, os.urandom) # Create public key. ssh_rsa = '00000007' + base64.b16encode('ssh-rsa') # Exponent. exponent = '%x' % (key.e, ) if len(exponent) % 2: exponent = '0' + exponent ssh_rsa += '%08x' % (len(exponent) / 2, ) ssh_rsa += exponent modulus = '%x' % (key.n, ) if len(modulus) % 2: modulus = '0' + modulus if modulus[0] in '89abcdef': modulus = '00' + modulus ssh_rsa += '%08x' % (len(modulus) / 2, ) ssh_rsa += modulus public_key = 'ssh-rsa %s' % ( base64.b64encode(base64.b16decode(ssh_rsa.upper())), ) return key, public_key
def test_keypair_crud_with_key(openstack_provider, appliance): """ This will test whether it will create new Keypair and then deletes it. Steps: * Provide Keypair name. * Select Cloud Provider. * Also delete it. Polarion: assignee: rhcf3_machine initialEstimate: 1/4h """ key = RSA.generate(1024) public_key = key.publickey().exportKey('OpenSSH') try: keypair = appliance.collections.cloud_keypairs.create(fauxfactory.gen_alphanumeric(), openstack_provider, public_key) except TimedOutError: if BZ(1444520, forced_streams=['5.6', '5.7', 'upstream']).blocks: pytest.skip('Timed out creating keypair, BZ1444520') else: pytest.fail('Timed out creating keypair') assert keypair.exists keypair.delete(wait=True) assert not keypair.exists
def __init__(self, source_dir, key_file, output_file): """ source_dir : the path to package resource directory. key_file : the path to RSA private key file, if the file is invalid, generator will create it automatically. output_file : the output XPK file path. """ self.source_dir_ = source_dir self.output_file_ = output_file if not os.path.exists(key_file): try: print('Start to generate RSA key') rng = Random.new().read self.RSAkey = RSA.generate(1024, rng) kfile = open(key_file, 'w') kfile.write(self.RSAkey.exportKey('PEM')) kfile.close() print('Finished generating RSA key, saved as %s' % key_file) except IOError: if os.path.exists(key_file): os.remove(key_file) traceback.print_exc() else: self.RSAkey = RSA.importKey(open(key_file, 'r').read()) self.pubkey = self.RSAkey.publickey().exportKey('DER')
def get_new_rsakey(size=2048): # Generate Private Key key = RSA.generate(size, os.urandom) private_key = key.exportKey() # Create public key ssh_rsa = '00000007' + base64.b16encode('ssh-rsa') # Exponent. exponent = '%x' % (key.e, ) if len(exponent) % 2: exponent = '0' + exponent ssh_rsa += '%08x' % (len(exponent) / 2, ) ssh_rsa += exponent modulus = '%x' % (key.n, ) if len(modulus) % 2: modulus = '0' + modulus if modulus[0] in '89abcdef': modulus = '00' + modulus ssh_rsa += '%08x' % (len(modulus) / 2, ) ssh_rsa += modulus public_ssh_key = 'ssh-rsa %s' % ( base64.b64encode(base64.b16decode(ssh_rsa.upper())), ) public_key = key.publickey().exportKey() return private_key, public_key, public_ssh_key
def generate(self): log.info("Generating new RSA keys") seckey = RSA.generate(config.getint('general', 'keylen')) pubkey = seckey.publickey() pubpem = pubkey.exportKey(format='PEM') keyid = hashlib.md5(pubpem).hexdigest() expire = config.getint('general', 'keyvalid') insert = (keyid, config.get('general', 'name'), config.get('general', 'address'), pubpem, seckey.exportKey(format='PEM'), timing.today(), timing.date_future(days=expire), 1, config.getboolean('general', 'smtp'), 100, 0) self.exe('''INSERT INTO keyring (keyid, name, address, pubkey, seckey, validfr, validto, advertise, smtp, uptime, latency) VALUES (?,?,?,?,?,?,?,?,?,?,?)''', insert) self.conn.commit() return (str(keyid), seckey)
def __init__(self, user, password): # Generate an RSA key self.rsa_full = RSA.generate(2048) self.cipher_full = PKCS1_v1_5.new(self.rsa_full) self._content_type_json = 'application/json; charset=utf-8' self._login_stage = ['email', 'twocfactor', 'captcha'] self._steamid = str(random_number(17)) # Register URIs httpretty.register_uri(httpretty.POST, 'https://steamcommunity.com/mobilelogin/getrsakey/', body=json.dumps({ 'success': True, 'publickey_mod': format(self.rsa_full.n, 'x').upper(), 'publickey_exp': format(self.rsa_full.e, 'x').upper(), 'timestamp': '64861350000', # TODO don't know how this is constructed }), content_type=self._content_type_json) httpretty.register_uri(httpretty.POST, 'https://steamcommunity.com/mobilelogin/dologin/', body=self.generate_dologin_response) httpretty.register_uri(httpretty.GET, 'https://steamcommunity.com/public/captcha.php', body=self.generate_captcha_response, adding_headers={ 'Set-Cookie': 'sessionid=%s; path=/' % ( random_ascii_string(24), ), }) httpretty.register_uri(httpretty.POST, 'https://steamcommunity.com/login/transfer', body='Success', status=200) super(SteamWebBrowserMocked, self).__init__(user, password)
def getRSAKeys(keypath="."): if not os.path.exists(keypath): print "Could not find specified keypath (%s)" % keypath sys.exit(1) pubkey = os.path.join(keypath, "public.key") privkey = os.path.join(keypath, "private.key") if not (os.path.exists(pubkey) and os.path.exists(privkey)): sys.stdout.write("Generating RSA keypair... ") from Crypto.PublicKey import RSA from twisted.python import randbytes KEY_LENGTH = 1024 rsaKey = RSA.generate(KEY_LENGTH, randbytes.secureRandom) publicKeyString = keys.Key(rsaKey).public().toString('openssh') privateKeyString = keys.Key(rsaKey).toString('openssh') file(pubkey, 'w+b').write(publicKeyString) file(privkey, 'w+b').write(privateKeyString) sys.stdout.write("Done.\n") else: publicKeyString = file(pubkey).read() privateKeyString = file(privkey).read() return publicKeyString, privateKeyString
def getKeyPair(pubkeyfile, privkeyfile): """ This function looks for RSA keypair files in the current directory. If they do not exist, the keypair is created. """ if not (os.path.exists(pubkeyfile) and os.path.exists(privkeyfile)): # No keypair exists. Generate a new RSA keypair print(" Generating SSH RSA keypair ...", end=' ') from Crypto.PublicKey import RSA KEY_LENGTH = 1024 rsaKey = Key(RSA.generate(KEY_LENGTH)) publicKeyString = rsaKey.public().toString(type="OPENSSH") privateKeyString = rsaKey.toString(type="OPENSSH") # save keys for the future. file(pubkeyfile, 'w+b').write(publicKeyString) file(privkeyfile, 'w+b').write(privateKeyString) print(" done.") else: publicKeyString = file(pubkeyfile).read() privateKeyString = file(privkeyfile).read() return Key.fromString(publicKeyString), Key.fromString(privateKeyString)
def Generate(size=keyinfo.RSA_PRIV.default_size): """ Return a newly generated RSA private key. @param size: length of key in bits to generate @type size: integer @return: a RSA private key @rtype: L{RsaPrivateKey} """ key = RSA.generate(size, util.RandBytes) #NOTE: PyCrypto stores p < q, u = p^{-1} mod q #But OpenSSL and PKCS8 stores q < p, invq = q^{-1} mod p #So we have to reverse the p and q values params = { 'privateExponent': util.BigIntToBytes(key.d), 'primeP': util.BigIntToBytes(key.q), 'primeQ': util.BigIntToBytes(key.p), 'primeExponentP': util.BigIntToBytes(key.d % (key.q - 1)), 'primeExponentQ': util.BigIntToBytes(key.d % (key.p - 1)), 'crtCoefficient': util.BigIntToBytes(key.u) } pubkey = key.publickey() pub_params = { 'modulus': util.BigIntToBytes(key.n), 'publicExponent': util.BigIntToBytes(key.e) } pub = RsaPublicKey(pub_params, pubkey, size) return RsaPrivateKey(params, pub, key, size)
def gen_key_pair(): return RSA.generate(1024)
def main(): parser = argparse.ArgumentParser( description='Lenovo UEFI signing tool, (C) 2019 Stefan Schmidt') parser.add_argument('file', metavar='INPUT_FILE', nargs=1, help='input file') parser.add_argument('-o', '--output', dest='outfile', metavar='OUTPUT_FILE', required=True, help='signed output file') args = parser.parse_args() input_file = open(args.file[0], "rb") data = input_file.read() input_file.close() # Find public RSA key location in the input file pubkey_location = find_pubkey_location(data) # Extract the FFSv2 volume offset ffsv2_offset = find_first_ffsv2_volume_offset(data) # Get all TCPA blocks to update signature on each tcpa_volume_blocks = find_tcpa_volume_blocks(data) # Generate a new RSA key-pair print("INFO: Generating new 1024 bit key with 3 as public exponent...") key = RSA.generate(1024, e=3) for tcpa_volume_block in tcpa_volume_blocks: # Warning: We assume volume size and offset are still correct here, that may not be the case! tcpa_volume_offset = int.from_bytes(tcpa_volume_block[1][52:56], byteorder='little') tcpa_volume_size = int.from_bytes(tcpa_volume_block[1][56:62], byteorder='little') print("INFO: Volume offset: " + str(tcpa_volume_offset)) print("INFO: Volume size: " + str(tcpa_volume_size)) # Shift the offsets so that they're relative to the FFSv2 volume tcpa_volume_offset += ffsv2_offset # Calculate actual volume hash volume_data = data[tcpa_volume_offset:tcpa_volume_offset + tcpa_volume_size] volume_hash = SHA1.new(data=volume_data) # Insert calculated hash into TCPA volume block tcpa_volume_block[1] = tcpa_volume_block[1][:32] + volume_hash.digest( ) + tcpa_volume_block[1][32 + 20:] print("INFO: Volume hash updated") # Extract the block of data that is to be hashed for the signature block_to_hash = tcpa_volume_block[1][:tcpa_volume_block_length - 131] # Calculate SHA hash of the block tcpa_hash = SHA1.new(data=block_to_hash).digest() # Pad the block to the correct length for RSA padded_tcpa_hash = (b'\x00' * 108) + tcpa_hash # Calculate the signature sig = key._decrypt(int.from_bytes(padded_tcpa_hash, byteorder='big')) # Convert the raw signature number to a block of bytes signature_block = number.long_to_bytes( sig, number.ceil_div(number.size(key.n), 8)) print("INFO: Signature calculated") assert (len(signature_block) == 128) # Insert new signature into TCPA volume block tcpa_volume_block[1] = tcpa_volume_block[1][:tcpa_volume_block_length - 128] + signature_block # Insert modified block into data data = data[:tcpa_volume_block[0]] + tcpa_volume_block[1] + data[ tcpa_volume_block[0] + tcpa_volume_block_length:] print("INFO: TCPA volume block signed") # Signatures updated, now insert public key modulus_block = key.n.to_bytes(length=pubkey_modulus_length, byteorder='big') data = data[:pubkey_location] + modulus_block + data[ pubkey_location + pubkey_modulus_length:] print("INFO: Public key stored") # Write updated data output file output_file = open(args.outfile, "wb") output_file.write(data) output_file.close() print("\nIMAGE SIGNED!")
def create_KeyPair(self): #Crea un par de claves publico/privada, y las almacena dentro de la instancia key = RSA.generate(self.KEY_LENGTH) self.private_key = key self.public_key = key.publickey()
signature = signer.sign(session_key_signed) return signature #Generate purchaser's nonce alphabet = string.ascii_letters + string.digits nonce_p = ''.join(secrets.choice(alphabet) for i in range(8)) print('\nSecure Purchase Order') s = socket.socket() # Create a socket object port = 60000 # Reserve a port for your service. s_pd = socket.socket() # Create a socket object port_pd = 50000 # Reserve a port for your service. #Generate the purchaser's RSA key rsa_key_p = RSA.generate(2048) #Generate the purchaser's public key from the RSA key pub_key_p = rsa_key_p.publickey() pubKeyPEM_p = pub_key_p.exportKey() #Obtain p's private key privKeyPEM_p = rsa_key_p.exportKey() print("Purchaser:") print("\nConnecting to manager...") print("Connecting to purchasing department...") time.sleep(1) s.connect(('127.0.0.1', port)) s_pd.connect(('127.0.0.1', port_pd)) print("Connected to manager...") print("Connected to purchasing department...")
def generate(self, size=DEFAULT_KEY_SIZE): self.keypair = RSA.generate(size) self.privkey = self.keypair.__getstate__() self.pubkey = self.keypair.publickey().__getstate__() self.privatekey = json.dumps(self.privkey).encode("base64") self.publickey = json.dumps(self.pubkey).encode("base64")
if a == 0: return (b, 0, 1) else: g, y, x = egcd(b % a, a) return (g, x - (b // a) * y, y) if __name__ == '__main__': n_length = 1024 e = 3 print("Starting...") # generate three keys with low e key1 = RSA.generate(n_length, e=e) key2 = RSA.generate(n_length, e=e) key3 = RSA.generate(n_length, e=e) n1 = key1.n n2 = key2.n n3 = key3.n print(n1) print(n2) print(n3) print(key1.e) # encrypt the message, no OAEP, three times m = b'This is a secret message' m_int = int.from_bytes(m, byteorder='big')
def decryption_RSA(ciphertext, p_key): decryptor = PKCS1_OAEP.new(p_key) decrypted = decryptor.decrypt(ciphertext) return decrypted file_name_plaintext = os.path.expanduser("~/Desktop/testdata.txt") small_file_name_plaintext = os.path.expanduser("~/Desktop/smallfile.txt") rsa_encrypted_file = os.path.expanduser("~/Desktop/rsa_encrypted.txt") rsa_decrypted_file = os.path.expanduser("~/Desktop/rsa_decrypted.txt") random_generator = Random.new().read start_time_2048 = int(round(time.time() * 1000)) key_2048 = RSA.generate(2048, random_generator) print("Time taken to create 2048 bit key in milli seconds: %s" % (int(round(time.time() * 1000)) - start_time_2048)) publickey_2048 = key_2048.publickey() random_generator = Random.new().read start_time_2048 = int(round(time.time() * 1000)) key_3072 = RSA.generate(3072, random_generator) print("Time taken to create 3072 bit key in milli seconds: %s" % (int(round(time.time() * 1000)) - start_time_2048)) publickey_3072 = key_3072.publickey() print("\n ############ Encrypt and Decrypt 1MB file with 2048 bit key #######") file_plaintext = open(file_name_plaintext, 'rb') encrypted_file = open(rsa_encrypted_file, 'wb') decrypted_file = open(rsa_decrypted_file, 'wb')
def encrypt(message, cipher): padded = message + " " * (16 - len(message) % 16) ciphertext = cipher.encrypt(padded) return ciphertext def decrypt(message, cipher): text = cipher.decrypt(message) text = text.strip() return text random_generator = Random.new().read rsa_private_key = RSA.generate(1024, random_generator) rsa_public_key = rsa_private_key.publickey() P = 1000000000000241 g = 23 a = 11 serverName = '192.168.24.145' if len(sys.argv) > 1: serverName = sys.argv[1] serverPort = 12000 clientSocket = socket(AF_INET, SOCK_STREAM) clientSocket.connect((serverName, serverPort)) # #clientSocket.send(sentence)
ID = 0 available = [True, True, True, True, True] given = [1, 2, 3, 4, 5] active = [0, 0, 0, 0, 0] pot = 0 turn = 1 current_bet = 0 flags = [0, 0, 0, 0, 0] check = True num_players = 0 running = False #Generate private and public keys #Keys for making accounts random_generator = Random.new().read private_key0 = RSA.generate(1024, random_generator) public_key0 = private_key0.publickey() #Keys for getting session keys random_generator = Random.new().read private_key1 = RSA.generate(1024, random_generator) public_key1 = private_key1.publickey() #Barrier class class Barrier: def __init__(self, n): self.n = n self.count = 0 self.mutex = Semaphore(1) self.barrier = Semaphore(0) def wait(self):
def _newPubPrivKeyPair(): k = RSA.generate(2048) return k.publickey().exportKey('OpenSSH'), k.exportKey('PEM')
def __init__(self): random_generator = Random.new().read self.privateKey = RSA.generate(2048, random_generator) self.publicKey = self.privateKey.publickey() self.privateCipher = PKCS1_OAEP.new(self.privateKey)
def new_key(): """Create a new key.""" return RSA.generate(2048)
from Crypto.Cipher import PKCS1_OAEP from Crypto import Random # constants IPv4 = socket.AF_INET TCP = socket.SOCK_STREAM HOST = 'localhost' PORT = 1234 BYE = 'Good Bye' # rnadom generator rnd_gen = Random.new().read # client keys private_key = RSA.generate(1024, rnd_gen) public_key = private_key.publickey() private_dec = PKCS1_OAEP.new(private_key) try: s = socket.socket(IPv4, TCP) except: print('sorry, unable to create socket') else: try: s.connect((HOST, PORT)) print('----------- Connection Established! -------------') except ConnectionRefusedError: print( '>> Are you sure any server is listening on defined host or port?!' )
def generate_keys(): modulus_length = 4096 private_key = RSA.generate(modulus_length, Random.new().read) public_key = private_key.publickey() return private_key, public_key
def generateRSAkey(options): from Crypto.PublicKey import RSA print 'Generating public/private rsa key pair.' key = RSA.generate(int(options['bits']), randbytes.secureRandom) _saveKey(key, options)
def register(self): """ Gets authentication info from a DPT-RP1. You can call this BEFORE DigitalPaper.authenticate() Returns (ca, priv_key, client_id): - ca: a PEM-encoded X.509 server certificate, issued by the CA on the device - priv_key: a PEM-encoded 2048-bit RSA private key - client_id: the client id """ reg_url = "http://{addr}:8080".format(addr=self.addr) register_pin_url = '{base_url}/register/pin'.format(base_url=reg_url) register_hash_url = '{base_url}/register/hash'.format(base_url=reg_url) register_ca_url = '{base_url}/register/ca'.format(base_url=reg_url) register_url = '{base_url}/register'.format(base_url=reg_url) register_cleanup_url = '{base_url}/register/cleanup'.format( base_url=reg_url) print("Cleaning up...") r = requests.put(register_cleanup_url, verify=False) print(r) print("Requesting PIN...") r = requests.post(register_pin_url, verify=False) print(r) m1 = r.json() n1 = base64.b64decode(m1['a']) mac = base64.b64decode(m1['b']) yb = base64.b64decode(m1['c']) yb = int.from_bytes(yb, 'big') n2 = os.urandom(16) # random nonce dh = DiffieHellman() ya = dh.gen_public_key() ya = b'\x00' + ya.to_bytes(256, 'big') zz = dh.gen_shared_key(yb) zz = zz.to_bytes(256, 'big') yb = yb.to_bytes(256, 'big') derivedKey = PBKDF2(passphrase=zz, salt=n1 + mac + n2, iterations=10000, digestmodule=SHA256).read(48) authKey = derivedKey[:32] keyWrapKey = derivedKey[32:] hmac = HMAC(authKey, digestmod=SHA256) hmac.update(n1 + mac + yb + n1 + n2 + mac + ya) m2hmac = hmac.digest() m2 = dict(a=base64.b64encode(n1).decode('utf-8'), b=base64.b64encode(n2).decode('utf-8'), c=base64.b64encode(mac).decode('utf-8'), d=base64.b64encode(ya).decode('utf-8'), e=base64.b64encode(m2hmac).decode('utf-8')) print("Encoding nonce...") r = requests.post(register_hash_url, json=m2) print(r) m3 = r.json() if (base64.b64decode(m3['a']) != n2): print("Nonce N2 doesn't match") return eHash = base64.b64decode(m3['b']) m3hmac = base64.b64decode(m3['e']) hmac = HMAC(authKey, digestmod=SHA256) hmac.update(n1 + n2 + mac + ya + m2hmac + n2 + eHash) if m3hmac != hmac.digest(): print("M3 HMAC doesn't match") return pin = input("Please enter the PIN shown on the DPT-RP1: ") hmac = HMAC(authKey, digestmod=SHA256) hmac.update(pin.encode()) psk = hmac.digest() rs = os.urandom(16) # random nonce hmac = HMAC(authKey, digestmod=SHA256) hmac.update(rs + psk + yb + ya) rHash = hmac.digest() wrappedRs = wrap(rs, authKey, keyWrapKey) hmac = HMAC(authKey, digestmod=SHA256) hmac.update(n2 + eHash + m3hmac + n1 + rHash + wrappedRs) m4hmac = hmac.digest() m4 = dict(a=base64.b64encode(n1).decode('utf-8'), b=base64.b64encode(rHash).decode('utf-8'), d=base64.b64encode(wrappedRs).decode('utf-8'), e=base64.b64encode(m4hmac).decode('utf-8')) print("Getting certificate from device CA...") r = requests.post(register_ca_url, json=m4) print(r) m5 = r.json() if (base64.b64decode(m5['a']) != n2): print("Nonce N2 doesn't match") return wrappedEsCert = base64.b64decode(m5['d']) m5hmac = base64.b64decode(m5['e']) hmac = HMAC(authKey, digestmod=SHA256) hmac.update(n1 + rHash + wrappedRs + m4hmac + n2 + wrappedEsCert) if hmac.digest() != m5hmac: print("HMAC doesn't match!") return esCert = unwrap(wrappedEsCert, authKey, keyWrapKey) es = esCert[:16] cert = esCert[16:] hmac = HMAC(authKey, digestmod=SHA256) hmac.update(es + psk + yb + ya) if hmac.digest() != eHash: print("eHash does not match!") return #print("Certificate: ") #print(cert) print("Generating RSA2048 keys") new_key = RSA.generate(2048, e=65537) #with open("key.pem", 'wb') as f: # f.write(new_key.exportKey("PEM")) keyPubC = new_key.publickey().exportKey("PEM") selfDeviceId = str(uuid.uuid4()) print("Device ID: " + selfDeviceId) selfDeviceId = selfDeviceId.encode() #with open("client_id.txt", 'wb') as f: # f.write(selfDeviceId) wrappedDIDKPUBC = wrap(selfDeviceId + keyPubC, authKey, keyWrapKey) hmac = HMAC(authKey, digestmod=SHA256) hmac.update(n2 + wrappedEsCert + m5hmac + n1 + wrappedDIDKPUBC) m6hmac = hmac.digest() m6 = dict(a=base64.b64encode(n1).decode('utf-8'), d=base64.b64encode(wrappedDIDKPUBC).decode('utf-8'), e=base64.b64encode(m6hmac).decode('utf-8')) print("Registering device...") r = requests.post(register_url, json=m6, verify=False) print(r) print("Cleaning up...") r = requests.put(register_cleanup_url, verify=False) print(r) return (cert.decode('utf-8'), new_key.exportKey("PEM").decode('utf-8'), selfDeviceId.decode('utf-8'))
def generate_key_pair(key_length = 1024): key = RSA.generate(key_length) public_key = key.publickey().exportKey() private_key = key.export_key() return KeyPair(private_key, public_key)
# -*- encoding:utf-8 -*- from Crypto.PublicKey import RSA from Crypto import Random from happyPY import settings # rsa算法生成实例 RANDOM_GENERATOR = Random.new().read if __name__ == '__main__': rsa = RSA.generate(1024, RANDOM_GENERATOR) # master的秘钥对的生成 PRIVATE_PEM = rsa.exportKey() with open(settings.BASE_DIR + '/hlPY/statics/pem/master-private.pem', 'w+') as f: f.write(PRIVATE_PEM.decode()) print(PRIVATE_PEM) PUBLIC_PEM = rsa.publickey().exportKey() print(PUBLIC_PEM) with open(settings.BASE_DIR + '/hlPY/statics/pem/master-public.pem', 'w+') as f: f.write(PUBLIC_PEM.decode())
def newkeys(keysize): random_generator = Random.new().read key = RSA.generate(keysize, random_generator) private, public = key, key.publickey() return public, private
return unhexlify(f'{n:0128x}') if len(argv) < 2: print(f'Usage: {argv[0]} [db_filename]') exit(1) try: with open(argv[1], 'rb') as f: r = f.read() except FileNotFoundError: open(argv[1], 'w') r = '' if len(r) % 64: print('Length must be a multiple of 64') exit(1) s = set(int(hexlify(r[i:i + 64]), 16) for i in range(0, len(r), 64)) while True: key = RSA.generate(2**10) if key.p not in s: with open(argv[1], 'ab') as f: f.write(data(key.p)) s.add(key.p) if key.q not in s: with open(argv[1], 'ab') as f: f.write(data(key.q)) s.add(key.q) print(len(s))
def handler(system: flow_api.System, this: flow_api.Execution): """ In this example we setup a Virtual Machine (VM) in the google-cloud. Then, Ubuntu will be installed and a small bash script is executed. Bash scripts can be used to install more software on the VM or change settings, anything you could do on a local machine in a terminal. This flow also requires the two files: * create google cloud vm example.sh * create google cloud vm example.json In the future, you can take these as an example, adopt them and upload them with a new name in Cloudomation > Files. """ # This is a pop-up message form, it will ask for some information # The last element is an OK-button, after clicking it the # values are passed further and the pop-up message closes. form_response = system.message( subject='Input information to setup a VM in google-cloud', message_type='POPUP', body={ 'type': 'object', 'properties': { 'connector_name': { 'element': 'string', 'type': 'string', 'label': 'Enter name for the connector: \n\ (This name can be searched for and is used to connect with your VM)', 'example': 'my-vm-on-gcloud', 'order': 1, }, 'project_id': { 'element': 'string', 'type': 'string', 'label': 'Enter your google cloud project-ID:', 'default': 'my-first-project-id', 'order': 2, }, 'machine_type': { 'element': 'string', 'type': 'string', 'label': 'Enter the machine type you want to use on google-cloud:', 'default': 'n1-standard-1', 'order': 3, }, 'server_location': { 'element': 'string', 'type': 'string', 'label': 'Enter the desired location of the hosting server from google-cloud:', 'default': 'europe-west1-b', 'order': 4, }, 'Ok': { 'element': 'submit', 'label': 'OK', 'type': 'boolean', 'order': 5, }, }, 'required': [ 'connector_name', 'project_id', 'machine_type', 'server_location', ], }, ).wait().get('response') connector_name = form_response['connector_name'] project_id = form_response['project_id'] machine_type = form_response['machine_type'] server_location = form_response['server_location'] # generate a ssh key-pair for the setup-user: setup_user_key = RSA.generate(2048) setup_user_priv = setup_user_key.export_key().decode() setup_user_pub = setup_user_key.publickey().export_key( format='OpenSSH').decode() setup_user_key = None # load the startup script and pass the public ssh key to the script: vm_startup_script = system.file( 'create google cloud vm example.sh').get_text_content() vm_startup_script = vm_startup_script.format( setup_user_pub=setup_user_pub, ) # load the configuration for the VM and setup last parameters: vm_config_str = system.file( 'create google cloud vm example.json').get_text_content() vm_config = json.loads(vm_config_str) vm_config['name'] = connector_name vm_config['machineType'] = \ f'projects/{project_id}/zones/{server_location}/machineTypes/{machine_type}' vm_config['zone'] = f'projects/{project_id}/zones/{server_location}' vm_config['metadata']['items'][0]['value'] = vm_startup_script vm_config['disks'][0]['deviceName'] = connector_name vm_config['disks'][0]['initializeParams']['diskType'] = \ f'projects/{project_id}/zones/{server_location}/diskTypes/pd-ssd' vm_config['networkInterfaces'][0]['subnetwork'] = \ f'projects/{project_id}/regions/{server_location[:-2]}/subnetworks/default' # NOTE: two sources can be used for initial system installation: # a) from 'sourceSnapshot' # b) from 'sourceImage' # This flow script will install Ubuntu, using the parameter 'sourceImage'. # For installing a system from snapshot use the respective parameter. # This paramter is set under: disks / initializeParams # Connect to the VM operation = this.connect( 'gcloud', name=f'launch {connector_name}', api_name='compute', api_version='v1', collection='instances', request='insert', params={ 'project': project_id, 'zone': server_location, 'body': vm_config, }, ).get('output_value')['result'] this.flow( 'google_operation_wait', operation=operation, ) # retrieve external IP and hostkey (required for creating a SSH connector): for _ in range(60): try: instance_list = this.connect( 'gcloud', name=f'find {connector_name}', api_name='compute', api_version='v1', collection='instances', request='list', params={ 'project': project_id, 'zone': server_location, 'filter': f'name={connector_name}', }, ).get('output_value') except flow_api.DependencyFailedError: this.sleep(1) if len(instance_list['result'].get('items', [])) != 0: break this.sleep(1) else: return this.error('did not find VM within 60 tries') external_ip = instance_list['result']['items'][0]['networkInterfaces'][0][ 'accessConfigs'][0]['natIP'] last_try_guest_attribute = None for _ in range(60): if last_try_guest_attribute is not None: last_try_guest_attribute.archive() try: last_try_guest_attribute = this.connect( 'gcloud', name=f'get {connector_name} hostkey', api_name='compute', api_version='v1', collection='instances', request='getGuestAttributes', params={ 'project': project_id, 'zone': server_location, 'instance': connector_name, 'queryPath': 'hostkeys/ssh-rsa', }, wait=system.return_when.ALL_ENDED, ) except Exception: this.sleep(1) else: if last_try_guest_attribute.load('status') == 'ENDED_SUCCESS': break else: return this.error('did not find hostkey within 60 tries') hostkey = last_try_guest_attribute.get( 'output_value')['result']['queryValue']['items'][0]['value'] # setup the SSH connector for the VM system.connector(f'{connector_name}-ssh').save( connector_type='SSH', value={ 'hostname': external_ip, 'hostkey': hostkey, 'username': '******', 'key': setup_user_priv, 'script_timeout': 600, 'interpreter': '/usr/bin/env bash -ex', }, ) # Run a little bash script on the VM: last_try_script_echo = None for _ in range(20): if last_try_script_echo is not None: last_try_script_echo.archive() try: last_try_script_echo = this.connect( f'{connector_name}-ssh', script=""" echo "litte test content" >> ~/test_file.txt cat ~/test_file.txt rm ~/test_file.txt """, name='run test script on new vm', ) except: this.sleep(1) else: if last_try_script_echo.load('status') == 'ENDED_SUCCESS': break else: return this.error('Failed to run the little test script.') script_echo = last_try_script_echo.get('output_value')['report'] this.set_output(f'Echo from test-script:\n{script_echo}') # Save flow state and pause, manually resume this script's execution to remove the VM this.save( message= 'The VM was successfully deployed. Resume this execution to remove the VM' ) this.pause() # Remove the VM operation = this.connect( 'gcloud', name=f'remove {connector_name}', api_name='compute', api_version='v1', collection='instances', request='delete', params={ 'project': project_id, 'zone': server_location, 'instance': connector_name, }, ).get('output_value')['result'] this.flow( 'google_operation_wait', operation=operation, ) return this.success('all done')
print("\nEncryption password creation for ATM2") ssl2 = 'openssl aes-256-cbc -salt -in server/a_bal.txt -out server/a_bal.txt.enc'.split( ) call(ssl2) print("\n*****PASSWORDS CREATED*****\n\n") #Creating 3 different directories. One for atm key, server key, and customer records. #This is to look for the keys easily. #This files will be created under their belonging directory os.mkdir('atm/atm_keys') os.mkdir('server/server_keys') os.mkdir('server/bank_statement') #This loop will create keys for both atms. for i in range(1, 3): key = RSA.generate(2048) f = open('atm/atm_keys/atm{}_privkey.pem'.format(i), 'w') f.write(key.exportKey('PEM')) f.close() pub_key = key.publickey() f_handler = (open('atm/atm_keys/atm{}_pubkey.pem'.format(i), 'w'), open('server/server_keys/atm{}_pubkey.pem'.format(i), 'w')) for h in f_handler: h.write(pub_key.exportKey('PEM')) h.close() key = RSA.generate(2048) f = open('server/server_keys/server_privkey.pem', 'w') f.write(key.exportKey('PEM')) f.close()
print(host) s_p.bind(('127.0.0.1', port_p)) s_pd.bind(('127.0.0.1', port_pd)) # Bind to the port print("Manager") s_p.listen(1) s_pd.listen(1) # Now wait for client connection. print("\nWaiting to connect...\n") conn_p, addr_p = s_p.accept() # Establish connection with client. print("Connected to Purchaser...") conn_pd, addr_pd = s_pd.accept() # Establish connection with client. print("Connected to Purchasing Department...\n") #Generate the m's RSA key rsa_key_m = RSA.generate(2048) #Generate the m's public key from the m's RSA key pub_key_m = rsa_key_m.publickey() pubKeyPEM_m = pub_key_m.exportKey() #Obtain m's private key privKeyPEM_m = rsa_key_m.exportKey() #m sends its public key conn_p.send(pubKeyPEM_m) conn_pd.send(pubKeyPEM_m) #m receives p's public key and prints it pub_key_received_p = conn_p.recv(524288) pub_key_p = RSA.importKey(pub_key_received_p)
# v0.2: Added RSA Key Generation & Exchange # v0.3: Added Encryption & Decryption # v0.4: Added Padding # v0.5: Added RSA Sign/Verify from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_OAEP from hashlib import sha512 import binascii import socket, threading import time # Public/Private Key Generation keys = RSA.generate(4096) pubKey = keys.publickey() pubStr = pubKey.exportKey("PEM") pubStr = pubStr.decode('utf-8') # User input for server's address and port host_no = input("Enter server IP address: ") port_no = int(input("Enter desired port number: ")) # Username # if-else will check if whitespace are present in input, if present, replace whitespace with null ADDR = (host_no, port_no) name = input("Enter your name: ") if " " in name: name = name.replace(" ", "")
def setUp(self): self.rng = Random.new().read self.key1024 = RSA.generate(1024, self.rng)
def __genKey(self): self.RSAKey=RSA.generate(2048,e=65537) print "Key generation successful" return self.RSAKey
def generate_RSA(bits=2048): new_key = RSA.generate(bits, e=65537) public_key = new_key.publickey().exportKey("PEM") private_key = new_key.exportKey("PEM") return public_key, private_key
def form_packet(payload): return bytes(str(len(payload)).zfill(4), "utf8") + payload + bytes( "".zfill(BUFSIZE - len(payload) - 4), "utf8") def receive(skt, *argv): pkt = skt.recv(BUFSIZE) debug(">> [PACKET]", *argv, pkt) if len(pkt) == 0: return -1 pktlen = int(pkt[:4].decode("utf8")) return pkt[4:pktlen + 4] debug("Generate RSA...") KEY = RSA.generate(2048) PRIVATE_KEY = KEY.export_key() PUBLIC_KEY = KEY.publickey().export_key() debug("RSA Generated.") SERVER = socket(AF_INET, SOCK_STREAM) SERVER.bind((HOST, PORT)) SERVER.listen(1) while True: debug("Waiting for connection...") # file = 0 client, client_address = SERVER.accept() debug("%s:%s has connected." % client_address) debug(" Receiving Client RSA...")
def rsakeys(): length=1024 privatekey = RSA.generate(length, Random.new().read) publickey = privatekey.publickey() return privatekey, publickey
import Crypto from Crypto.PublicKey import RSA from Crypto import Random # Geração da Chave Privada e da Chave Pública: randomGenerator = Random.new().read privateKey = RSA.generate(1024, randomGenerator) publicKey = privateKey.publickey() # Criptografando com a Chave Pública: encrypted = publicKey.encrypt(str.encode('Mensagem a ser criptografada!'),1024) print ('Encrypted Message:', encrypted) # Descriptografando com a Chave Privada: decrypted = privateKey.decrypt(encrypted) print ('Decrypted Messsage:', decrypted.decode())