def _generate_new_key(self): if self._using_m2crypto: self._private_key = M2RSA.gen_key(2048, 65537, lambda x,y,z: None) self._public_key = M2RSA.RSA_pub(self._private_key.rsa) else: try: (self._public_key, self._private_key) = PYRSA.newkeys(2048, poolsize=4) except: (self._public_key, self._private_key) = PYRSA.newkeys(2048)
def reset_keys(): try: (public_key, private_key) = rsa.newkeys(2048, poolsize=4) except: (public_key, private_key) = rsa.newkeys(2048) Settings.set("private_key", private_key.save_pkcs1()) Settings.set("public_key", serialize_public_key(public_key)) keys["private"] = private_key keys["public"] = public_key
def run_speed_test(bitsize): iterations = 0 start = end = time.time() # At least a number of iterations, and at least 2 seconds while iterations < 10 or end - start < 2: iterations += 1 rsa.newkeys(bitsize, accurate=accurate, poolsize=poolsize) end = time.time() duration = end - start dur_per_call = duration / iterations print('%5i bit: %9.3f sec. (%i iterations over %.1f seconds)' % (bitsize, dur_per_call, iterations, duration))
def test_sign(self): """Test sign works.""" # rsa_pk = M2Crypto.RSA.gen_key(2048, 65537) rsa_keys = rsa.newkeys(2048, 65537) rsa_pk = rsa_keys[1] rsa_pub = rsa_keys[0] salt = 'salt' data = {"flags": 8, "name": "MyAwesomeVM", "ram": 512, "secret": "mg041na39123", "userData": "[amiconfig]\nplugins=cernvm\n[cernvm]\nusers=user:users;password", "vcpus": 1, "version": "1.5"} strBuffer = vmcp.calculate_buffer(data, salt) with patch('rsa.PrivateKey.load_pkcs1', return_value=rsa_pk): with patch('pybossa.vmcp.open', mock_open(read_data=''), create=True) as m: out = vmcp.sign(data, salt, 'testkey') err_msg = "There should be a key named signature" assert out.get('signature'), err_msg err_msg = "The signature should not be empty" assert out['signature'] is not None, err_msg assert out['signature'] != '', err_msg err_msg = "The signature should be the same" signature = base64.b64decode(out['signature']) assert rsa.verify(strBuffer, signature, rsa_pub) == 1, err_msg # The output must be convertible into json object import json assert_not_raises(Exception, json.dumps, out)
def main(): (pubkey, privkey) = rsa.newkeys(512) test = "goob" signature = rsa.sign(test, privkey, 'SHA-1') msg = ("I, Cecil Lam, signed this sentence!") publicKey = pubkey return msg, signature, publicKey;
def main(): message = "I, Raymund Alksninis, signed this sentence!" message_enc = message.encode('utf-8') (publicKey, privateKey) = rsa.newkeys(1024) signature = rsa.sign(message_enc, privateKey, 'SHA-256') return(message, signature, publicKey)
def check_rsa_keys(self): ''' If rsa keys pair doesnt exists, creates them ''' path = self.config.get('General', 'rsa') or './.rsa' if not os.path.exists(path): os.makedirs(path) my_id = self.config.get('General', 'id') priv = os.path.join(path, '%s.priv' % my_id) pub = os.path.join(path, '%s.pub' % my_id) if not os.path.exists(priv) or not os.path.exists(pub): # generate new keys (pubkey, privkey) = rsa.newkeys(512) # save keys pem = privkey.save_pkcs1('PEM') open(priv, 'w').write(pem) pem = pubkey.save_pkcs1('PEM') open(pub, 'w').write(pem) log.info("keys pair generated !!") else: print "RSA ok" # any way, fix permitions os.system("chmod -R 600 %s/*" % path) return True
def keygen(): """Key generator.""" # Parse the CLI options parser = OptionParser( usage="usage: %prog [options] keysize", description='Generates a new RSA keypair of "keysize" bits.' ) parser.add_option( "--pubout", type="string", help="Output filename for the public key. The public key is " "not saved if this option is not present. You can use " "pyrsa-priv2pub to create the public key file later.", ) parser.add_option( "-o", "--out", type="string", help="Output filename for the private key. The key is " "written to stdout if this option is not present.", ) parser.add_option( "--form", help="key format of the private and public keys - default PEM", choices=("PEM", "DER"), default="PEM" ) (cli, cli_args) = parser.parse_args(sys.argv[1:]) if len(cli_args) != 1: parser.print_help() raise SystemExit(1) try: keysize = int(cli_args[0]) except ValueError: parser.print_help() print("Not a valid number: %s" % cli_args[0], file=sys.stderr) raise SystemExit(1) print("Generating %i-bit key" % keysize, file=sys.stderr) (pub_key, priv_key) = rsa.newkeys(keysize) # Save public key if cli.pubout: print("Writing public key to %s" % cli.pubout, file=sys.stderr) data = pub_key.save_pkcs1(format=cli.form) with open(cli.pubout, "wb") as outfile: outfile.write(data) # Save private key data = priv_key.save_pkcs1(format=cli.form) if cli.out: print("Writing private key to %s" % cli.out, file=sys.stderr) with open(cli.out, "wb") as outfile: outfile.write(data) else: print("Writing private key to stdout", file=sys.stderr) sys.stdout.write(data)
def main(): (my_pubkey, my_privkey) = rsa.newkeys(1024) message = 'I, Bryan Ngo, signed this message'.encode('utf-8') sign = rsa.sign(message, my_privkey, "SHA-256") rsa.verify(message, sign, my_pubkey) return message, sign, my_pubkey
def main(): # Do we have our OWN Keys? if not (os.path.isfile('./privkey.pem') and os.path.isfile('./pubkey.pem')): (pubkey, privkey) = rsa.newkeys(512) with open("privkey.pem", 'w') as keyfile: keyfile.write(privkey.save_pkcs1()) with open("pubkey.pem", 'w') as keyfile: keyfile.write(pubkey.save_pkcs1()) else: with open("privkey.pem") as keyfile: keydata = keyfile.read() privkey = rsa.PrivateKey.load_pkcs1(keydata) with open("pubkey.pem") as keyfile: keydata = keyfile.read() pubkey = rsa.PublicKey.load_pkcs1(keydata) # After this, we can use pubkey and privkey as our keypair for encryption # Connect to stomp and fetch messages conn = stomp.StompConnection10() conn.set_listener('', MixListener(privkey)) conn.start() conn.connect() conn.subscribe(destination=QUEUE, id=1, ack='auto') # Yes we do this :-) while (True): time.sleep(10)
def keygen(): parser = OptionParser(usage='usage: %prog [options] keysize', description='Generates a new RSA keypair of "keysize" bits.') parser.add_option('--pubout', type='string', help='Output filename for the public key. The public key is not saved if this option is not present. You can use pyrsa-priv2pub to create the public key file later.') parser.add_option('-o', '--out', type='string', help='Output filename for the private key. The key is written to stdout if this option is not present.') parser.add_option('--form', help='key format of the private and public keys - default PEM', choices=('PEM', 'DER'), default='PEM') cli, cli_args = parser.parse_args(sys.argv[1:]) if len(cli_args) != 1: parser.print_help() raise SystemExit(1) try: keysize = int(cli_args[0]) except ValueError: parser.print_help() print('Not a valid number: %s' % cli_args[0], file=sys.stderr) raise SystemExit(1) print('Generating %i-bit key' % keysize, file=sys.stderr) pub_key, priv_key = rsa.newkeys(keysize) if cli.pubout: print('Writing public key to %s' % cli.pubout, file=sys.stderr) data = pub_key.save_pkcs1(format=cli.form) with open(cli.pubout, 'wb') as outfile: outfile.write(data) data = priv_key.save_pkcs1(format=cli.form) if cli.out: print('Writing private key to %s' % cli.out, file=sys.stderr) with open(cli.out, 'wb') as outfile: outfile.write(data) else: print('Writing private key to stdout', file=sys.stderr) sys.stdout.write(data)
def rsa_demo(): (pubkey,privkey)=rsa.newkeys(1024) print('pubkey >>>> {}'.format(pubkey)) print('privkey >>>> {}'.format(privkey)) with open('pub.pem','w') as f: f.write(pubkey.save_pkcs1().decode()) with open('priva.pem','w') as f: f.write(privkey.save_pkcs1().decode()) message = 'Kill bill tonight' print("message encode {}".format(message.encode())) crypto=rsa.encrypt(message.encode(),pubkey) print('密文{}'.format(crypto)) # 解密 e_message = rsa.decrypt(crypto,privkey) print("解密后{}".format(e_message.decode())) private_sign = rsa.sign(message.encode(),privkey,'SHA-1') print('签名:{}'.format(private_sign)) print('验证签名') print(rsa.verify(message.encode(),private_sign,pubkey))
def get_keypair(): """ Returns a (private, public) key pair as two strings encoded as pkcs1. """ public, private = rsa.newkeys(1024) return (private.save_pkcs1().decode('ascii'), public.save_pkcs1().decode('ascii'))
def main(): (publicKey, privateKey) = rsa.newkeys(1024) msg = ('I, Ran, signed this sentence!').encode('utf-8') signature = rsa.sign(msg, privateKey, 'SHA-256') return [msg, signature, publicKey]
def keys(this): public_name = 'public.txt' private_name = 'private.txt' try: with open(public_name,'r') as f: pubkey = rsa.PublicKey.load_pkcs1(f.read()) with open(private_name,'r') as f: privkey = rsa.PrivateKey.load_pkcs1(f.read()) except: print 'generic keys...' pubkey, privkey = rsa.newkeys(2048, poolsize=2) #2 core with open(public_name,'w') as f: f.write(pubkey.save_pkcs1()) with open(private_name,'w') as f: f.write(privkey.save_pkcs1()) this.pubkey = pubkey this.privkey = privkey # поток выполнил полезную работу, теперь страдаем фигнёй # test 1 text1 =''.join(random.choice(string.ascii_uppercase +\ string.ascii_lowercase + string.digits) for x in range(16)) text2 = rsa.encrypt(text1, this.static_public_key) text3 = rsa.decrypt(text2, this.static_private_key) if text1 != text3: print 'FATAL ERROR: fail test 1' # test 2 text1 =''.join(random.choice(string.ascii_uppercase +\ string.ascii_lowercase + string.digits) for x in range(16)) text2 = rsa.encrypt(text1, pubkey) text3 = rsa.decrypt(text2, privkey) if text1 != text3: print 'ERROR: fail test 2'
def main(): import rsa message = "I, Matthew Kyawmyint, signed this sentence!".encode('utf-8') (matt_pub, matt_priv) = rsa.newkeys(1024) signature = rsa.sign(message, matt_priv, 'SHA-256') return message, signature, matt_priv
def test_encrypt_decrypt_bigfile(self): # Expected block size + 11 bytes padding pub_key, priv_key = rsa.newkeys((6 + 11) * 8) # Encrypt the file message = b('123456Sybren') infile = BytesIO(message) outfile = BytesIO() bigfile.encrypt_bigfile(infile, outfile, pub_key) # Test crypto = outfile.getvalue() cryptfile = BytesIO(crypto) clearfile = BytesIO() bigfile.decrypt_bigfile(cryptfile, clearfile, priv_key) self.assertEquals(clearfile.getvalue(), message) # We have 2x6 bytes in the message, so that should result in two # bigfile. cryptfile.seek(0) varblocks = list(varblock.yield_varblocks(cryptfile)) self.assertEqual(2, len(varblocks))
def rsa_key(self): self.pub, self.pri = newkeys(512) self.rsa_pub.setText(unicode(self.pri.e)) self.rsa_pri.setText(unicode(self.pri.d)) self.rsa_n.setText(unicode(self.pri.n)) self.rsa_p.setText(unicode(self.pri.p)) self.rsa_q.setText(unicode(self.pri.q))
def main(): (pubkey, privkey) = rsa.newkeys(2048) with open('public.pem', 'wb') as fd: fd.write(pubkey.save_pkcs1('PEM')) with open('private.pem', 'wb') as fd: fd.write(privkey.save_pkcs1('PEM')) print('Success!')
def main(): (publicKey, privateKey) = rsa.newkeys(1024) pub = publicKey.save_pkcs1() pubfile = open("public.pem", "w+") pubfile.write(pub) pubfile.close() pri = privateKey.save_pkcs1() prifile = open("private.pem", "w+") prifile.write(pri) prifile.close() prifile = open("private.pem", "r") p = prifile.read() privateKey = rsa.PrivateKey.load_pkcs1(p) prifile.close() pubfile = open("public.pem", "r") p = pubfile.read() publicKey = rsa.PublicKey.load_pkcs1(p) pubfile.close() message = "lalalalal" secret = rsa.encrypt(message, publicKey) non_secret = rsa.decrypt(secret, privateKey) print non_secret signature = rsa.sign(message, privateKey, "SHA-1") rsa.verify("lalalalal", signature, publicKey)
def keys(this): name = 'keys.txt' #TODO зашифровать файл try: with open(name,'r') as f: data = f.read() pubkey = rsa.PublicKey.load_pkcs1(data) privkey = rsa.PrivateKey.load_pkcs1(data) except: print 'generic keys...' pubkey, privkey = rsa.newkeys(2048, poolsize=2) #2 core with open(name,'w') as f: f.write(pubkey.save_pkcs1()) f.write(privkey.save_pkcs1()) this.pubkey = pubkey this.privkey = privkey # поток выполнил полезную работу, теперь страдаем фигнёй # TODO chmod +r name # test 1 text1 =''.join(random.choice(string.ascii_uppercase +\ string.ascii_lowercase + string.digits) for x in range(16)) text2 = rsa.encrypt(text1, this.static_public_key) text3 = rsa.decrypt(text2, this.static_private_key) if text1 != text3: printf ('FATAL ERROR: fail test 1','red') # test 2 text1 =''.join(random.choice(string.ascii_uppercase +\ string.ascii_lowercase + string.digits) for x in range(16)) text2 = rsa.encrypt(text1, pubkey) text3 = rsa.decrypt(text2, privkey) if text1 != text3: printf ('ERROR: fail test 2','red')
def get_keypair(): """ Returns a (private, public) key pair as two strings. """ (pub, priv) = rsa.newkeys(512) return (priv.save_pkcs1().decode('ascii'), pub.save_pkcs1().decode('ascii'))
def __init__(self, networking, request_processor, database_engine, nick_name): super().__init__(networking, request_processor, 'auth_database') #self.users_database = UsersTable() self.database_engine = database_engine #self.database_engine.add_table(self.users_database) self.register_callbacks_for_requests() self.random_msg = [] self.my_name = nick_name self.users_list = [] if self.my_name is None: self.my_name = "Alex" # print("Auth_module: Nick name: " + self.my_name) (self.pubkey, self.privkey) = rsa.newkeys(256) # msg="Hello my friend" # cr=rsa.encrypt(msg, self.pubkey) # msg2=rsa.decrypt(cr, self.privkey) welcome_data = {'nick': self.my_name, 'pubkey_n': self.pubkey.n, 'pubkey_e': self.pubkey.e} for peer in self.networking.get_peers(): # print("Auth_module: Request connect me into p2p network") welcome_request = self.send_request(peer, 'welcome', welcome_data) self.process()
def generateKey(): (pubkey, privkey) = rsa.newkeys(169) print('pubkey: %s,\n privkey: %s' % (pubkey, privkey)) pub = pubkey.save_pkcs1('PEM').decode() ## public.pem','w+' ,decode后不能用wb with open('public.pem', 'w+') as myfile: myfile.write(pub) myfile.close() pri = privkey.save_pkcs1('PEM').decode() with open('private.pem', 'w+') as myfile: myfile.write(pri) myfile.close() message = 'helloworld-python' with open('public.pem', 'r') as f: pubkey = rsa.PublicKey.load_pkcs1(f.read()) print('pubkey%s'%pubkey) with open('private.pem', 'r') as f: privkey = rsa.PrivateKey.load_pkcs1(f.read()) print('privkey%s'%privkey) ## OverflowError: 17 bytes needed for message, but there is only space for 10 crypto = base64.b64encode(rsa.encrypt(message.encode(encoding="UTF-8"), pubkey)) # 私钥解密 message = rsa.decrypt(base64.b64dncode(crypto), privkey) print(message)
def main(): (pcKey, pKey) = rsa.newkeys(1024) messg = 'I, Graciela Vargas Roque, signed this message!' messg = messg.encode('utf-8') sig = rsa.sign(messg, pKey, 'SHA-256') return messg, sig, pcKey
def generate_secret(): """Generate rsa keys for authentication.""" import rsa print("[*] Generating secret, please hang on.") # Generate keys, taken from https://stuvel.eu/python-rsa-doc/usage.html#generating-keys (pubkey, privkey) = rsa.newkeys(2048) # Save private and pub key priv_key_file = open(CONFIG['MobSF']['priv_key'], 'w') priv_key_file.write(privkey.save_pkcs1().decode('utf-8')) priv_key_file.close() pub_key_file = open(CONFIG['MobSF']['pub_key'], 'w') pub_key_file.write(pubkey.save_pkcs1().decode('utf-8')) pub_key_file.close() print( "[!] Please move the private key file\n" "\t{}\n" "\tto MobSF to the path specified in settings.py\n" "\t(default: Mobile-Security-Framework-MobSF/MobSF/windows_vm_priv_key.asc)" .format(CONFIG['MobSF']['priv_key']) ) if sys.version_info.major == 3: # pylint: disable-msg=W0141 # For python3 input("Please press any key when done..") elif sys.version_info.major == 2: raw_input("Please press any key when done..")
def KeyGen(self): (keyPub, keyPriv) = rsa.newkeys(512) print "KeyGen: New keys generated." self.clientKeyPrivate = keyPriv self.clientKeyPublic = keyPub self.KeySave(self.clientKeyPrivate, self.clientKeyFilePrivate, self.keyTypeClient, self.keyClassPrivate) self.KeySave(self.clientKeyPublic, self.clientKeyFilePublic, self.keyTypeClient, self.keyClassPublic) print "KeyGen: New keys saved successfully."
def work_with_big_file(): """encrypt a big file using IO stream """ (pubkey, privkey) = rsa.newkeys(512, poolsize=1) with open(r"testdata\message.txt", "rb") as infile, open(r"testdata\received.txt", 'wb') as outfile: encrypt_bigfile(infile, outfile, pubkey) with open(r"testdata\received.txt", "rb") as infile, open(r"testdata\decrypted.txt", 'wb') as outfile: decrypt_bigfile(infile, outfile, privkey)
def main(UAClass): print "Running Protocol with %s" % UAClass.__name__ print "=" * 40 publickey, privatekey = rsa.newkeys(512) tpm = TPM(privatekey) ua = UAClass(tpm) server = Server(publickey) ua.send_message("Javascript result", server)
def __init__(self, keysize=1024, *args, **kargs): if kargs.get('keysize'): keysize = kargs.pop('keysize') self.sock = socket.socket(*args, **kargs) self.conn = None self.pub, self.priv = rsa.newkeys(keysize) self.keysize = keysize self.key = None
from rsa import newkeys, encrypt, decrypt # Generating public and private key pair print("Generating keypair!") pubkey, privkey = newkeys(4096, poolsize=8) print("Keys generated!") print(f"Your public key is: {pubkey}") print(f"Your private key is: {privkey}") # Accept string to encrypt with public key message = input("Enter a message to encrypt: ").encode("utf-8") # Encrypt the given string using the generated public key encrypted = encrypt(message, pubkey) print(f"Encrypted message is {encrypted}") # Decrypt the encrypted string using the generated private key decrypted = decrypt(encrypted, privkey) print(f"Decrypted message is: {decrypted.decode()}")
import rsa import json import hashlib d = 3171116340292388119434451358851392461119376028218393462974765347922079624990431158157119359468019911817507985531433220411075365766294033871942139272090097 e = 65537 n = 9412810887890857384092379125188808719796211185350280917748865284060389172093699004782158842329541367593956792940586337736197470391447676122078020829219401 p = 6687752773375905845628287846107383612359021833928018756053495242416598040217779597 q = 1407469924032399816120206005991522429163464449823001027488465080413289133 pub = rsa.PublicKey(n, e) priv = rsa.PrivateKey(n, e, d, p, q) with open('WS2021/Модуль2/Task1/Task7-block.json', 'r') as f: block = json.load(f) block = json.dumps(block, separators=(',', ':')) sign = rsa.sign(block.encode(), priv, 'SHA-1').hex() pub, priv = rsa.newkeys(1024) print(len(hashlib.sha512('a'.encode()).hexdigest())) print(len(rsa.sign('a'.encode(), priv, 'SHA-512').hex()))
def __init__(self, name: str): self.name = name self.connections = [] self.messages = [] self.public_key, self.private_key = rsa.newkeys(512)
#!/usr/bin/env python # -*- coding: utf-8 -*- import rsa from base64 import b64encode secret = 'hello' * 1000 pubkey, privkey = rsa.newkeys(512) print(pubkey) print(pubkey.save_pkcs1()) print(repr(pubkey.save_pkcs1('DER'))) print(b64encode(pubkey.save_pkcs1('DER'))) print(privkey) print(privkey.save_pkcs1()) pubkey = rsa.PublicKey( 7415502624357151701843602000555318455948573542840931625729150638611638251360782052774127447815979830851875097447216767147242437831115031378524678172264921, 65537, ) privkey = rsa.PrivateKey( 7415502624357151701843602000555318455948573542840931625729150638611638251360782052774127447815979830851875097447216767147242437831115031378524678172264921, 65537, 5677294416545159019180046849533288120103448090575457288569207215654347148007043218092439893759997074589438975571531525440203012025002055883676278902503473, 4446231151572194572272541834440666920306217930405766286220328832524851462544515341, 1667817612616703003339597571420391729959720600059564280837759069331120381, ) print(pubkey) print(pubkey.save_pkcs1()) print(privkey) print(privkey.save_pkcs1())
sys.stdout.flush() backup = sys.stdin.readline() print backup global entries entries = pickle.loads(rsa.decrypt(backup.decode("base64"), privkey)) print("Successfully restored %d entries\n" % len(entries)) def show_key(): print("Here is your key:") print(str(pubkey)) print("Welcome to Super Password Authentication Manager (SPAM)!") sys.stdout.flush() (pubkey, privkey) = rsa.newkeys(1024) while 1: while 1: print("Menu:") print("1) List Passwords") print("2) Add a Password") print("3) Remove a Password") print("4) Backup Passwords") print("5) Restore backup") print("6) Show the key") sys.stdout.flush() l = str(input()) if len(l) == 1 and l in "123456": [ spam_list, spam_add, spam_del, spam_backup, spam_restore, show_key
import rsa (bob_pub, bob_pri) = rsa.newkeys(512) print(f'公钥:{bob_pub}\n私钥:{bob_pri}\n') message = 'hello world'.encode('utf-8') crypto = rsa.encrypt(message, bob_pub) print(f'密文:{crypto}', len(crypto)) message = rsa.decrypt(crypto, bob_pri) print('解密后:', message.decode('utf-8'))
import rsa import time import threading import keyboard import qrcode import logger import glob ''' An improved version of the old ACDS. What it does is safely overload your CPU and run several priv/pub scripts simultaneously on your server. Please use a spoof for the best experience. ''' public, private = rsa.newkeys(612) HOSTNAME = socket.gethostname() IP = None SECRET = auth.twofactorAUTH.SECRETKEY_AT_LOAD CURSOR = f"\n\033[38;5;129m╔\033[38;5;128m═\033[38;5;123m[\033[38;5;125m{os.getcwd()}\033[38;5;123m]\033[38;5;128m-\033[38;5;123m[\033[38;5;127m{socket.gethostname()}\033[38;5;123m]\n\033[38;5;129m╚══\033[38;5;128m══\033[38;5;124m➤ \033[38;5;123m" TOTP = auth.twofactorAUTH.PinAuthorization.TOTP( auth.twofactorAUTH.Decrypt(SECRET)) pt_infoFiles = glob.glob(f"**\\[p]*.txt", recursive=True) # Match all pentest info files logDB = glob.glob( f"**\\lo??.csv", recursive=True ) # Our local Database data to find all valid pentest info files
def generate_new_key(self, keysize=2048): try: self._public_key, self._private_key = PYRSA.newkeys(keysize, poolsize=4) except: self._public_key, self._private_key = PYRSA.newkeys(keysize)
def create_keys(): return rsa.newkeys(1024)
for i in range(1, self.getLength()): currentBlock = self.chain[i] previousBlock = self.chain[i-1] if not currentBlock.hasValidTransactions(): return False if currentBlock.hash != currentBlock.calculateHash(): return False if currentBlock.prevhash != previousBlock.hash: return False return True # Create my keys keyPair = rsa.newkeys(512) myKey = keyPair[1] myWalletAddress = keyPair[0] print('Your private key:', myKey) print('Your public key:', myWalletAddress) # Create the Blockchain platform Platform = Blockchain() # Prompt user to enter transactions or start the miner work = True while work: dowhat = input('Please enter the things you want to do: enter "mine" for mining, enter "esc" for exit, others for adding transactions> ') if dowhat == 'esc': work = False
def genRSAKeyPair(a, b): (pubKey, privKey) = rsa.newkeys(4096) with open(a, "w+") as pubKeyFile: pubKeyFile.write(pubKey.save_pkcs1(format='PEM')) with open(b, "w+") as privKeyFile: privKeyFile.write(privKey.save_pkcs1(format='PEM'))
# 产生公钥私钥 (pub, pri) = rsa.newkeys(2048) # 构建新的公钥私钥 pubkey = rsa.PublicKey(pri.n, pri.e) pri_key = rsa.PrivateKey(pri.n, pri.e, pri.d, pri.p, pri.q) message = b'\x00\x00\x00\x00\x01' # 加密 message crypto = rsa.encrypt(message, pubkey) # 解密 d_crypto = rsa.decrypt(crypto, pri_key) print(d_crypto) keys = rsa.newkeys(2048) bts_str = { "version": "2.0", "charset": "UTF-8", "messageId": "02dxxadwf3f3a29674e674e6", "guestId": "10100", "appId": "10103", "signType": "RSA2", "reqTime": "2020043011212", "beginTime": "20200804-121212", "endTime": "20200805-231212", "deviceId": "04181100646", "pspId": "2", "businessDate": "20200805" }
from multiprocessing import Queue import multiprocessing, os, pickle, select, socket, sys, time, rsa, traceback from common.safeprint import safeprint from common.bounty import * global ext_port global ext_ip global port global myPriv global myPub ext_port = -1 ext_ip = "" port = 44565 myPub, myPriv = rsa.newkeys(1024) seedlist = [("127.0.0.1",44565), ("localhost",44565), ("10.132.80.128",44565)] peerlist = [("24.10.111.111",44565)] remove = [] bounties = [] #constants peers_file = "data" + os.sep + "peerlist.pickle" key_request = "Key Request".encode('utf-8') close_signal = "Close Signal".encode("utf-8") peer_request = "Requesting Peers".encode("utf-8") bounty_request = "Requesting Bounties".encode("utf-8") incoming_bounties = "Incoming Bounties".encode("utf-8") incoming_bounty = "Incoming Bounty".encode("utf-8") valid_signal = "Bounty was valid".encode("utf-8") invalid_signal = "Bounty was invalid".encode("utf-8") end_of_message = "End of message".encode("utf-8")
def setUp(self): (self.pub, self.priv) = rsa.newkeys(512)
# 'k3':'v3', # } # for k in list(api_dict.keys()): # v = api_dict[k] # if v == 'v2': # del api_dict[k] # print(api_dict) # # for k,v in api_dict.keys(): # # if v == 'v2': # # del api_dict[k] import rsa import base64 # ######### 1. 生成公钥私钥 ######### pub_key_obj, priv_key_obj = rsa.newkeys(256) pub_key_str = pub_key_obj.save_pkcs1() pub_key_code = base64.standard_b64encode(pub_key_str) priv_key_str = priv_key_obj.save_pkcs1() priv_key_code = base64.standard_b64encode(priv_key_str) print(pub_key_code, type(pub_key_code)) print(priv_key_code, type(priv_key_code)) # ######### 2. 加密 ######### def encrypt(value): key_str = base64.standard_b64decode(pub_key_code) pk = rsa.PublicKey.load_pkcs1(key_str)
input('Press ENTER to help Bob encrypt his message to Alice.') elif continuegame.lower() != "yes": print( 'Aww man, that sucks. Unfortunately without your help, Evil Eve figured out how to crash Bob and Alice\'s second date and that ends the Alice and Bob story.' ) sys.exit() #Let's start the encryption portion print( '\nAlrighty, thanks for agreeing to help Bob out. Honestly, Bob is kind of a doof and would not be able to do this without you. Here is the plan. You will need to encrypt Bob\'s message to Alice first. Don\'t know how to do that? Don\'t worry, let\'s walk through this step by step.' ) input('Press ENTER to run the RSA Encryption Program.') #Insert RSA Encryption Program here (this is where the rsa module gets used) #Alice's generated key pair, Bob has public Alice's public key (alice_pub, alice_priv) = rsa.newkeys(512) #Need Alice's private key later to decrypt message, so making a global variable ALICE_PRIV = alice_priv #Bob uses Alice's public key to encrypt message to Alice bobmessage = input('What is the message you want to send? ') message = bobmessage.encode('utf8') #Need CRYPTO to be global so we can call this variable later when Alice decrypts the encrypted message CRYPTO = rsa.encrypt(message, alice_pub) #Here is the encrypted message input('Press ENTER to see the encrypted message.') print('\nGreat job! Here is the encrypted message:' + ' \n' + str(CRYPTO)) input('Press ENTER to continue with the tutorial.') print(
def gen_addr_key_pair(): pubkey, privkey = rsa.newkeys(384) return pubkey_to_address(pubkey), privkey
import rsa import pickle from stegano import lsb from LSBSteg import LSBSteg import cv2 from Crypto.Cipher import AES from Crypto.Util.Padding import pad, unpad global bob_pub global bob_priv global my_pub global my_priv (bob_pub, bob_priv) = rsa.newkeys(512) (my_priv,my_pub)= rsa.newkeys(512) def lis(s): my=[s] while True: r,w,e=select.select(my,[],[]) if s in r: try: global bob_pub global bob_priv (p,te)=pickle.loads(s.recv(100000000)) if p==1:
# # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import rsa # nuitka-skip-unless-imports: rsa (tambe_pub, tambe_priv) = rsa.newkeys(512) message = "beautiful Tambe!".encode("utf8") encrypted_msg = rsa.encrypt(message, tambe_pub) message = rsa.decrypt(encrypted_msg, tambe_priv) def encryption_decryption(): """Function to test encryption and decryption""" assert message.decode("utf8") == "beautiful Tambe!" if __name__ == "__main__": encryption_decryption()
import rsa key = rsa.newkeys(3000) #生成随机秘钥 privateKey = key[1] #私钥 publicKey = key[0] #公钥 message = '中国山东烟台.Now is better than never.' print('Before encrypted:', message) message = message.encode() cryptedMessage = rsa.encrypt(message, publicKey) print('After encrypted:\n', cryptedMessage) message = rsa.decrypt(cryptedMessage, privateKey) message = message.decode() print('After decrypted:', message)
def generate_keys(size): return rsa.newkeys(size)
def generate(filename): (public, private) = rsa.newkeys(1024) sig = saveWallet(public, private, filename) text = "New wallet generated in '"+filename+"' with signature "+sig return text
class Server(ss.StreamRequestHandler): (serverPublicKey, serverPrivateKey) = rsa.newkeys(1600, poolsize=2) # key: address ... val: serverobject clients = dict() # key: name ... val: address usernames = dict() # key:address.... val:pKey publicKeys = dict() # key: name ... val: [messageDict] offlineMessages = dict() def createMessageDict(self, source, data): messageDictionary = {"from": source, "message": data} return messageDictionary def dumpAndEncodeDict(self, messageDictionary): messageJson = json.dumps(messageDictionary) encoded = messageJson.encode() return encoded def encryptMessageAndSend(self, thisClient, encodedMessage, destAddr): pubKey = self.publicKeys[destAddr] encryptedMessage = rsa.encrypt(encodedMessage, pubKey) print(encodedMessage) thisClient.request.sendall(encryptedMessage) def sendEveryoneMessage(self, messageDictionary, myAddr): for addr, client in self.clients.items(): if (addr != myAddr): encoded = self.dumpAndEncodeDict(messageDictionary) self.encryptMessageAndSend(client, encoded, addr) def sendExternalMessage(self, destAddr, messageDictionary): encoded = self.dumpAndEncodeDict(messageDictionary) reciever = self.clients[destAddr] self.encryptMessageAndSend(reciever, encoded, destAddr) def getMyAddr(self): peerName = self.request.getpeername() myAddr = peerName[1] return myAddr def systemResponse(self, message): messageDictionary = {"from": "SERVER", "message": message} encodedMessage = self.dumpAndEncodeDict(messageDictionary) myAddr = self.getMyAddr() self.encryptMessageAndSend(self, encodedMessage, myAddr) def remove(self, connectionAddr, name): res1 = self.clients.pop(connectionAddr, None) res2 = self.usernames.pop(name, None) messageDictionary = { "from": "SERVERTERM", "message": "Have a great day!" } encodedMessage = self.dumpAndEncodeDict(messageDictionary) myAddr = self.getMyAddr() self.encryptMessageAndSend(self, encodedMessage, myAddr) def sendServerKey(self): pickledPublicKey = pickle.dumps(self.serverPublicKey, 0).decode() messageDictionary = { "destName": "SERVERPUBLICKEY", "message": pickledPublicKey } send = self.dumpAndEncodeDict(messageDictionary) self.request.sendall(send) def handle(self): while True: fromAddr = self.getMyAddr() self.data = self.request.recv(1024) jsonData = json.loads(self.data.decode()) message = jsonData["message"] dest = jsonData["destName"] if (dest.startswith("CONNECTEDUSERNAME")): #wants to join try: split = message.split(sep="-") name = split[0] publicKeyPickledDecoded = split[1] except Exception as e: print("NAme pickle split issue") print(e) continue try: publicKeyPickled = publicKeyPickledDecoded.encode() publicKey = pickle.loads(publicKeyPickled) except Exception as e: print("public key depickle issue") print(e) continue try: # add self to clients list self.clients[fromAddr] = self # add self to usernames list self.usernames[name] = fromAddr self.publicKeys[fromAddr] = publicKey print(fromAddr, "with username,", name, "just connected to the server.") except Exception as e: print("ERROR") print(e) response = "Welcome to ClassChat, " + name + ".\n\tTo send a message use the format \"USERNAME-MESSAGE\" " + "\n\t Type GETUSERS to view all users." try: offlineArray = self.offlineMessages.pop(name) offlineResponse = "Welcome to ClassChat, " + name + ".\n\tTo send a message use the format \"USERNAME-MESSAGE\" " + "\n\t Type GETUSERS to view all users. \n\t Type LEAVE to leave. \n\n Here's what you missed while you were gone..... " offlineMessage = { "from": "SERVER", "message": offlineResponse } offlineArray.insert(0, offlineMessage) encodedMessage = self.dumpAndEncodeDict( {"messages": offlineArray}) myAddr = self.getMyAddr() self.encryptMessageAndSend(self, encodedMessage, myAddr) except KeyError as e: print("No offline messages for", e) self.systemResponse(response) elif (dest == "LEAVE"): #wants to leave myAddr = fromAddr myName = list(self.usernames.keys())[list( self.usernames.values()).index(fromAddr)] print("Deleting user,", fromAddr, "with username,", myName, "from server.") self.remove(myAddr, myName) elif (dest.startswith("GETUSERS")): #wants the list of users message = "" self.usernames.keys() for key in sorted(self.usernames.keys()): message += ("\n" + key) self.systemResponse(message) elif (dest.startswith("EVERYONE")): #sending a group message myName = list(self.usernames.keys())[list( self.usernames.values()).index(fromAddr)] messageDict = self.createMessageDict(myName, message) self.sendEveryoneMessage(messageDict, fromAddr) self.systemResponse(("Sent message to " + dest)) else: #sending a direct message myName = list(self.usernames.keys())[list( self.usernames.values()).index(fromAddr)] messageDict = self.createMessageDict(myName, message) try: destAddr = self.usernames[dest] except KeyError as e: self.offlineMessages.setdefault(dest, []).append(messageDict) self.systemResponse("No user available named " + dest + " ....storing message offline.") continue print("Message sent: {} -> {}".format(myName, dest)) self.sendExternalMessage(destAddr, messageDict) self.systemResponse(("Sent message to " + dest))
import pyaes import socket import threading import json from datetime import datetime import rsa import hashlib HOST = '127.0.0.1' PORT = 8888 SECMODE = True if SECMODE: pubkey, prikey = rsa.newkeys(2048) print("Server public key ", pubkey) print("[+] Server Running ") print("[+] Waiting For Connection...") s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) conn, addr = s.accept() print('[+] Connected by ', addr) conn.send(bytes(str(pubkey.n).encode())) data = conn.recv(512) print("Received encrypted session key ", data) AESkey = rsa.decrypt(data, prikey) print("Received decrypted session key ") hashed = hashlib.sha256(AESkey).digest() aes = pyaes.AESModeOfOperationCBC(hashed) cl_pub = conn.recv(2048) n_cl = int(cl_pub.decode())
import rsa public, private = rsa.newkeys(8096) with open("priv_key.txt", "w") as file: file.write(str(private)[11:-1]) with open("pub_key.txt", "w") as file: file.write(str(public)[10:-1])
def make_keys(self): return rsa.newkeys(512)
import rsa import base64 (pub_key, private_key) = rsa.newkeys(512) def check_rsa(): message = b'Hello World!' crypto = rsa.encrypt(message, pub_key) print(crypto) message = rsa.decrypt(crypto, private_key) print(message) def encrypt_rsa_with_base64(message: str) -> bytes: crypto = rsa.encrypt(message.encode(), pub_key) return base64.b64encode(crypto) def decrypt_rsa_with_base64(crypto: bytes) -> str: raws = base64.b64decode(crypto) return str(rsa.decrypt(raws, private_key)) if __name__ == '__main__': crypto_message = encrypt_rsa_with_base64('Hello world!') print(crypto_message) print(decrypt_rsa_with_base64(crypto_message))
def _generate_rsa_keys(cls, nbits: int) -> Tuple[PublicKey, PrivateKey]: cls.logger.debug("Generate RSA key with %i bits", nbits) return rsa.newkeys(nbits)
def __init__(self, number=1024): """ :param number: 公钥、私钥 """ self.pubkey, self.privkey = rsa.newkeys(number)
game_type = dsp_choice_game() deck = [] if(game_type == 1 or game_type == 2 or game_type == 3 or game_type == 4): make_deck_by_type(game_type, deck) else: dsp_end() exit() player_a = [] player_b = [] player_c = [] player_d = [] player_dumy = [] key = rsa.newkeys(4500) public_key = key[0] private_key = key[1] if game_type == 1: deal_to_multi_players(deck, player_a, player_b, player_c) record_deck_crypted_csv(player_a, '争上游01的副牌.csv',public_key) record_deck_crypted_csv(player_b, '争上游02的副牌.csv',public_key) record_deck_crypted_csv(player_c, '争上游03的副牌.csv',public_key) if game_type == 2: deal_to_multi_players(deck, player_a, player_b, player_c, player_d) record_deck_crypted_csv(player_a, '桥牌01的副牌.csv',public_key) record_deck_crypted_csv(player_b, '桥牌02的副牌.csv',public_key) record_deck_crypted_csv(player_c, '桥牌03的副牌.csv',public_key) record_deck_crypted_csv(player_d, '桥牌04的副牌.csv',public_key) if game_type == 3: