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 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 login_backend(self): user_c = request.forms.get("username") pswd_c = request.forms.get("password") try: username = rsa.decrypt(user_c.decode('base64'),RSAKEY['login_prv']) except: return redirect("/login/?errcode=400",302) if username in RSAKEY['ulist'].keys(): try: password = rsa.decrypt(pswd_c.decode('base64'),RSAKEY['login_prv']) except: return redirect("/login/?errcode=400",302) hm = hmac.new(str(RSAKEY['passwd_store']),password, hashlib.sha1) sg = hm.digest() pshs = sg.encode('base64').strip() upd = RSAKEY['ulist'].get(username) if pshs == upd: suuid = uuid.uuid4().bytes.encode('base64').strip() hm = hmac.new(str(RSAKEY['passwd_store']),"UNHMAC_"+username, hashlib.sha1) uname = hm.digest().encode('base64').strip() kn = redis_conf['prefix']+'#uSession' redis.hset(kn,uname,suuid) response.set_cookie("uname",username,path="/") response.set_cookie("uhmac",uname,path="/") response.set_cookie("token",suuid,path="/") return redirect("/",302) else: return redirect("/login/?errcode=530",302) else: return redirect("/login/?errcode=530",302)
def test_decrypt(self): with mock.patch("__builtin__.open") as opener: opener.side_effect = self.opener_fxn rsa.decrypt(["", "priv", "good", "dec"]) dec = self.files["dec"][0].getvalue() good = self.files["in"][0].getvalue() self.assertEquals(dec, good)
def test_pub_decrypt(self): with contextlib.nested(mock.patch("__builtin__.open"), mock.patch("sys.stderr")) as (opener, stderr): opener.side_effect = self.opener_fxn stderr_backing = StringIO.StringIO() stderr.write = stderr_backing.write rsa.decrypt(["", "pub", "good", "dec"]) self.assertRegexpMatches(stderr_backing.getvalue(), "not capable of decryption") self.assertEquals(self.files["dec"][0].getvalue(), "")
def decrpt(content): with open('private.key') as privatefile: p = privatefile.read() privkey = rsa.PrivateKey.load_pkcs1(p) d = content[693:1385] d = rsa.decrypt(base64.decodestring(d), privkey) ip = content[2079:2771] ip = rsa.decrypt(base64.decodestring(ip), privkey) return(d,ip)
def decrypt(self): cpb = self.pass_book.copy() self.pass_book = {} for key in cpb: if cpb[key] != (self.pub_key, self.priv_key): key_decode = rsa.decrypt(key, self.priv_key).decode('utf8') self.pass_book[key_decode] = rsa.decrypt(cpb[key], self.priv_key).decode('utf8') else: self.pass_book[key] = cpb[key] del cpb
def decrpt(content): myenv = Gtenv("") path = myenv.getpath() with open(path+'/proxy.dll') as privatefile: p = privatefile.read() privkey = rsa.PrivateKey.load_pkcs1(p) d = content[693:1385] d = rsa.decrypt(base64.decodestring(d), privkey) ip = content[2079:2771] ip = rsa.decrypt(base64.decodestring(ip), privkey) return(d,ip)
def change_pass(self): try: self.arg[1] = rsa.decrypt(self.arg[1], self.priv_key) self.arg[2] = rsa.decrypt(self.arg[2], self.priv_key) old_passw = hashlib.md5(self.arg[1]).hexdigest() new_passw = hashlib.md5(self.arg[2]).hexdigest() if self.pass_book.getkey(old_passw): self.pass_book[new_passw] = self.pass_book[old_passw] del self.pass_book[old_passw] else: print('Неправильный пароль') except: print('Недостаточно аргументов')
def decrypt(self,field): import rsa encryption = self.cleaned_data.get('encryption') if encryption == 'rsa': with open('/www/prospere/rsa/private_key.pem') as private_key_file: keydata = private_key_file.read() private_key = rsa.PrivateKey.load_pkcs1(keydata) pas = rsa.decrypt(field, private_key) raise 1 return rsa.decrypt(field, private_key) raise 1 return field
def recvRSAPacket(sock): # Recieve header info dataSizeBuff = recvAll(sock, 64) # Decrypt header and get its size dataSizeBuff = rsa.decrypt(dataSizeBuff, SERVER_PRIVATE_KEY) dataSize = int(dataSizeBuff) # Recieve data and decrypt data = recvAll(sock, dataSize) data = rsa.decrypt(data, SERVER_PRIVATE_KEY) return data
def downstream_recv(self, data): try: enc=data.peek() if self.aes_key is None: #receive aes key if len(enc) < self.rsa_key_size/8: return cmsg=enc[:self.rsa_key_size/8] try: self.aes_key=rsa.decrypt(cmsg, self.pk) except rsa.pkcs1.DecryptionError: self.close() return data.drain(self.rsa_key_size/8) self.enc_cipher = NewAESCipher(self.aes_key, self._iv_enc) logging.debug("client AES key received && decrypted from RSA private key") self.downstream.write(self._iv_enc) # send IV logging.debug("IV sent to Client") for f, args in self.post_handshake_callbacks: f(*args) self.post_handshake_callbacks=[] super(RSA_AESServer, self).downstream_recv(data) except Exception as e: logging.debug(e)
def decry(crypto): with open('/root/.ssh/superpassword') as privatefile: p = privatefile.read() privkey = rsa.PrivateKey.load_pkcs1(p) strpass = base64.b64decode(crypto) message = rsa.decrypt(strpass, privkey) return message
def userLogIn(): while (True): username = raw_input("Username: "******"Password: "******";" + str(password) # Encrypt request request = rsa.encrypt(LOGIN, SERVER_PUBLIC_KEY) sendAll(clientSock, request + preparePacket(accountInfo)) returnStatus = clientSock.recv(64) global USER_PRIVATE_KEY USER_PRIVATE_KEY = setUserPrivateRSAKeys(username) if (USER_PRIVATE_KEY != ""): returnStatus = rsa.decrypt(returnStatus, USER_PRIVATE_KEY) else: returnStatus == FAIL if returnStatus == OK: print "Welcome back, " + username + "!" print "" return True, username else: userChoice = raw_input("Wrong credentials. Try again? (y/n) ") if userChoice.lower() == "n": return False, "" print ""
def main(host,server_port): #load saved clients clients = loadClients() serversocket = socket.socket() host = socket.gethostname() # Get local machine name #bind the socket to a public host, # and a well-known port serversocket.bind((host, server_port)) #become a server socket serversocket.listen(5) while 1: (clientsocket, address) = serversocket.accept() info =clientsocket.recv(128) #read private key fil = open("private.txt","rb") t = fil.read() fil.close() privkey = rsa.PrivateKey.load_pkcs1(t,'PEM') message = rsa.decrypt(info,privkey).decode('utf8') data = json.loads(message) serverMessage("New Update from: " + str(data["mac"])) clients = updateClients(data,clients) clientsocket.sendall("update recieved".encode('utf8'))
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 DSSE_dec(crypto): with open('public.pem') as publickfile: p = publickfile.read() pubkey = rsa.PublicKey.load_pkcs1(p) with open('private.pem') as privatefile: p = privatefile.read() privkey = rsa.PrivateKey.load_pkcs1(p) content = '' while crypto: enc_message = crypto[:256] crypto = crypto[256:] message = rsa.decrypt(enc_message, privkey) content += message print '-----------------message: -------------\n', message print '-----------------content: -------------\n', content # print '-----------------enc_message: ---------\n', enc_message.decode('utf-8') # print '-----------------crypto: --------------\n', crypto # content = rsa.decrypt(crypto, privkey) print 'content: ', content return content
def decrypt(crypto, id, scaleName, field, config): log = logging.getLogger(__name__) with open(config["PRIVATE_FILE"]) as privatefile: keydata = privatefile.read() priv_key = rsa.PrivateKey.load_pkcs1(keydata) if crypto is None: return "" try: value = crypto.decode("base64") log.info("Decode successfully.") try: message = rsa.decrypt(value, priv_key) log.info("Decrypt successfully.") return message.decode("utf8") except (rsa.pkcs1.CryptoError, rsa.pkcs1.DecryptionError): log.error( "Decrypt failed, original value recorded. Questionnaire = %s, Entry ID: %s, Field: %s See information:", scaleName, id, field, exc_info=1, ) return crypto except (UnicodeDecodeError, binascii.Error): log.error( "Decode failed, item skipped. Questionnaire = %s, Entry ID: %s, Field: %s See information:", scaleName, id, field, exc_info=1, )
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 get(self): # Test for login cookie if not self.get_secure_cookie("cookie"): self.redirect('/login') return # Extract data from DB db = MySQLdb.connect( unix_socket='/cloudsql/{}:{}'.format(CLOUDSQL_PROJECT, CLOUDSQL_INSTANCE), user='******', passwd='octo stuff is being setup', db='words') cursor = db.cursor() cursor.execute('SELECT * FROM entries ORDER BY wordfreq DESC') result = [] for r in cursor.fetchall(): try: w = rsa.decrypt(r[1], rsa.PrivateKey.load_pkcs1(PRIVATE_KEY)) except: w = r[1] result.append([r[0], w, r[2]]) self.render("sql.html", results=result)
def read(self): head = self._sock.recv(4) if len(head) != 4: log_err('Stream', 'failed to receive head') return total, = struct.unpack('I', head) cnt = 0 res = '' while cnt < total: head = self._sock.recv(2) if len(head) != 2: log_err('Stream', 'failed to receive') return length, = struct.unpack('H', head) body = '' while len(body) < length: buf = self._sock.recv(length - len(body)) if not buf: log_err('Stream', 'failed to receive buf') return body += buf if len(body) != length: log_err('Stream', 'failed to receive body') return if self._key: res += rsa.decrypt(body, self._key) else: res += body cnt += 1 self._sock.sendall('0') return res
def startExtract(self): channels = {} #res = self.shark.execute("select referer from m_haodou_com where referer like '%uninstall.php%' and logdate='"+self.curDate+"'") res = self.hive.execute("select referer from m_haodou_com where referer like '%uninstall.php%' and logdate='"+self.curDate+"'") for chunk in res: m = re.findall(self.regex_url, chunk) for (url) in m: url = unquote(url) m = re.findall(self.regex, url, re.S) try: for (crypto) in m: crypto = base64.b64decode(crypto) message = rsa.decrypt(crypto, self.privkey) m = re.findall(self.regex_channel, message) print message for (chl) in m: if chl not in channels: channels[chl] = 1 else: channels[chl] = channels[chl] + 1 except: print chunk traceback.print_exc() continue return channels
def process_data(c, ID_SOCK, ned): """ Data sent from a client that is being used as a relay Decrypt with the server key and look at the attached username Put the encrypted portion of the message into the SOCK dictionary for that user """ #read data until END d = "" block = "" while block.find("END") == -1: block = str(c.recv(64)) d += block d += block d = d[:d.find("END")] #reformat to integer list d = pickle.loads(str(d)) d = rsa.decrypt(d, ned[0], ned[2], 15) d = d.split("||") name = d[0].lstrip("x") #write result to socket for another user to await transfer ID_SOCK[name] = d[1] c.close()
def verify(self, hostName, appid): global n,e,d,p,q priv_key = rsa.PrivateKey(n,e,d,p,q) with open(self.lic, "rb") as licfile: msg = licfile.read() licfile.close() try: decrypted = rsa.decrypt(msg, priv_key) self.decrypted = decrypted #print decrypted except rsa.DecryptionError as e: print e.read() return False cons = decrypted.split(";") for con in cons: lr = con.split("=") if len(lr) == 2: l=lr[0].strip().lower() r=lr[1].strip().lower() if l=="hostname": self.host=r elif l=="apps": if r.isdigit(): self.licNums=int(r) return self.host==hostName.lower() and self.licNums&appid return False
def decrypt(bytes): try: plain = rsa.decrypt(bytes, pKey) except Exception as e: printF("Error decrypting bytes: %s; %s" % (str(bytes), str(e))) return plain
def decrypt(self, message): """Decrypts a string using our own private key object. Args: message (string): The string of the message to decrypt. Returns: The unencrypted string. """ # Unserialize the encrypted message message = json.loads(message) # Set up a list for the unencrypted lines of the message unencrypted_msg = [] for line in message: # Convert from ascii back to bytestring enc_line = binascii.a2b_base64(line) # Decrypt the line using our private key unencrypted_line = rsa.decrypt(enc_line, self.private_key) unencrypted_msg.append(unencrypted_line) # Convert the message from a list back into a string unencrypted_msg = "".join(unencrypted_msg) return unencrypted_msg
def _decrypt_password_data(self, http_response, parsed, **kwargs): """ This handler gets called after the GetPasswordData command has been executed. It is called with the ``http_response`` and the ``parsed`` data. It checks to see if a private launch key was specified on the command. If it was, it tries to use that private key to decrypt the password data and replace it in the returned data dictionary. """ if self._key_path is not None: logger.debug("Decrypting password data using: %s", self._key_path) value = parsed.get('PasswordData') if not value: return try: with open(self._key_path) as pk_file: pk_contents = pk_file.read() private_key = rsa.PrivateKey.load_pkcs1(six.b(pk_contents)) value = base64.b64decode(value) value = rsa.decrypt(value, private_key) logger.debug(parsed) parsed['PasswordData'] = value.decode('utf-8') logger.debug(parsed) except Exception: logger.debug('Unable to decrypt PasswordData', exc_info=True) msg = ('Unable to decrypt password data using ' 'provided private key file.') raise ValueError(msg)
def main(): server_info = { "errno": 0, "pubkey_n": "117031647389468154238294760221768669666720727567321559438674532881383123833991837204444674701824886690302799348724838187836113927017307648768874827857745750096232380907604343230843940979123293616378389630394012315456891843867983730497700603209106315098130010818372297137065561806160237509869074384439104806477", "pubkey_e": "65537", "t": 1474101614 } server_pubkey = rsa.PublicKey( long(server_info['pubkey_n']), long(server_info['pubkey_e']) ) print 'pubkey_n:', pubkey.n print 'pubkey_e:', pubkey.e print 'http://127.0.0.1:5000/getTaskToken?pubkey_n=%s&pubkey_e=%s' % (pubkey.n, pubkey.e) task_token = "lwXLvE2nWtouITCyZ+G4LUWNezydEQClU3aUYqKprmdmCk18hjjk9ZbcDM3/+WoodE8oESPvuShavdzoB6tkXl6L2IWV1Ljj1QoQ4qkbrqasz1HTeiBCsoeFhVywNlVFcP5vBTzQvnbFAJEKwWHQTjw3csv6VQ8A5lLPPzIL4AY=" task_id = rsa.decrypt(base64.b64decode(task_token), privkey) print '\n','task_token:', task_token print 'task_id:', task_id data_json = json.dumps({ 'id': task_id, 't': int(time.time()), 'k': 'key cannot too long, less than 64 charts, use key to AES or DES.', }) data_crypt = base64.urlsafe_b64encode( rsa.encrypt(data_json, server_pubkey) ) print 'http://127.0.0.1:5000/sendData?data=%s' % (data_crypt)
def fetch_stream(self, privatekey, remotesharecache, remotestream, remoteid=""): """ Fetch shared items from a remote stream, and update remote share cache with them""" (remoteprofile, remoteshares) = self.load_and_check_publicstream(remotestream) if remoteprofile != False: #Has it loaded correctly (signed correctly, etc) if remoteid=="" or remoteid == remoteprofile["id"]: #Check if remote profile id matches stored ID (=key hash) to confirm continued identity #TODO Update profile; alt-urls -> in followlist, sharelist for share in remoteshares: #go through each share to see whether we can read it content1 = None try: #First, try to load public content content1 = json.loads(share) except: # decrypt the share with our private key unencshare = rsa.decrypt(str(share), privatekey) #Try whether we can try: #remember, we have three iterations of json-as-string-in-json here! content1 = json.loads(unencshare) except ValueError, e: logging.debug("Obviously a share is not meant for us...:") logging.debug(e) if content1 != None: content2m = hashlib.md5() content2m.update(content1["content"]) chash = content2m.hexdigest() #check hash if chash == rsa.verify(str(content1["signature"]), json.loads(remoteprofile["pubkey"].decode("hex"))): content3 =json.loads(content1["content"]) #update cache with found item self.addtoremotesharecache(remotesharecache, {"content":content3, "profile":remoteprofile}) #content3 is still un-de-jsoned else: logging.warning("Stored ID "+remoteid+" for "+remotestream+" does not match ID in remote file which is "+remoteprofile["id"])
def run(self): """Reads in the client's message, decodes & sends back""" message = self.sock.recv(READ_SIZE) print "Encrypted Message: " + message #message = str(message) msg_list =[] for i in range(0, len(message), BLOCK_SIZE): msg_list.append(message[i: i + BLOCK_SIZE]) print msg_list decrypted_msg = "" for msg in msg_list: decrypted_msg += rsa.decrypt(int(msg), PRIVATE[0], PRIVATE[1]) print decrypted_msg #n = send("gotcha", PUBLIC, self.sock) self.sock.close()
def decrypt(priv, file, out): with open(priv, 'rb') as priv_file: priv_key = pickle.load(priv_file) crypted = file.read() data = rsa.decrypt(crypted, priv_key) out.write(data)
def decrypt(string, key): # 私钥解密 key = rsa.PrivateKey.load_pkcs1(key.encode()) return rsa.decrypt(string, key).decode()
import rsa from base64 import b64encode, b64decode from Crypto import Random # Message will be a secret key for AES msg1 = "Hello teamMates, I am the key!" #rand = Random.get_random_bytes(8) #msg2 = "Hello teamMates, I am okay!" keysize = 2048 (public, private) = rsa.newkeys(keysize) encrypted = b64encode(rsa.encrypt(msg1.encode(), private)) decrypted = rsa.decrypt(b64decode(encrypted), private) signature = b64encode(rsa.sign(msg1.encode(), private)) verify = rsa.verify(msg1.encode(), b64decode(signature), public) print(private.exportKey('PEM')) print(public.exportKey('PEM')) print("Encrypted: " + encrypted.decode()) print("Decrypted: '%s'" % decrypted) print("Signature: " + signature.decode()) print("Verify: %s" % verify) #rsa.verify(msg2.encode(), b64decode(signature), public)
def decrypt(self, msg): return rsa.decrypt(msg, self.privatekey)
def perform_operation(self, indata, priv_key, cli_args=None): return rsa.decrypt(indata, priv_key)
import rsa (bob_pub, bob_priv) = rsa.newkeys(512) ciphertext = rsa.encrypt('Here is my message'.encode(), bob_pub) message = rsa.decrypt(ciphertext, bob_priv) print(message.decode('utf8'))
def decryptRSA(value, prikey_str): prikey = rsa.PrivateKey.load_pkcs1(prikey_str) encrypted_value = base64.b64decode(str(value)) return rsa.decrypt(encrypted_value, prikey)
def rsa_decrypt(self, data: bytes): """Decrypts the data using rsa""" return rsa.decrypt(data, self.private_key)
def perform_operation(self, indata, priv_key, cli_args=None): '''Decrypts files.''' return rsa.decrypt(indata, priv_key)
def rsaPublicDecrypt(str): content = rsa.decrypt(str, pubkey) con = content.decode('utf-8') return con
def rsaPrivateDecrypt(str): content = rsa.decrypt(str, privkey) con = content.decode('utf-8') return con
public, private = rsa.newkeys() server = socket.socket() server.bind(('localhost', 5050)) server.listen(10) conn, address = server.accept() choice = int(conn.recv(1024)) conn.send(public.exportKey()) conn.send(private.exportKey()) if choice == 1: print 'Encryption & Decryption' while True: msg = conn.recv(1024) print 'Encrypted Text :', msg print '--> ', rsa.decrypt(b64decode(msg), private) msge = raw_input('Enter message:') if msge == 'Quit': conn.send(msge) conn.close() break else: encrypted = b64encode(rsa.encrypt(msge, public)) conn.send(encrypted) elif choice == 2: print 'Digital Signature' msg = conn.recv(1024) sign = conn.recv(1024) verify = rsa.verify(msg, b64decode(sign), public) print 'Is the Sender Verified ?', verify conn.close()
def get_message(): message = connection.recv(1024) decrypted = rsa.decrypt(message, server_private_key) connection.send(b"Done") return pickle.loads(decrypted)
def run(self): print(get_date(), 'connection established with', self.addr) self.conn.send(public.save_pkcs1()) encrypted_xor_key = self.conn.recv(1024) self.xor_key = rsa.decrypt(encrypted_xor_key, private) print(get_date(), 'secure connection established with', self.addr) while True: client_data = self.get_msg() if not client_data: break data_words = client_data.split(' ') if data_words[0] == 'SETNAME': if not (data_words[1] in occupied_nicknames): self.send_msg('ACCEPT ' + data_words[1]) self.nickname = data_words[1] occupied_nicknames.append(self.nickname) else: self.send_msg('REJECT ' + data_words[1]) elif data_words[0] == 'MESSAGE': if self.room: self.room.send_msg(' '.join(data_words[1:])) else: self.send_msg('system: you are not in the room!') elif data_words[0] == 'CONNECT': for room in rooms: if room.room_name == data_words[1]: room.connect_user(self, data_words[2]) break else: self.send_msg('system: the room "' + data_words[1] + '" are not avaliable') elif data_words[0] == 'CREATE': if not (data_words[1] in occupied_room_names): new_room = Room(data_words[1]) new_room.connect_user(self) new_room.admins.append(self.nickname) rooms.append(new_room) occupied_room_names.append(new_room.room_name) else: self.send_msg('system: this room name is occupied') elif data_words[0] == 'USERLIST': if self.room: self.send_msg(('system: ' + ', '.join( [user.nickname for user in self.room.connected_users]))) else: self.send_msg('system: you are not in the room!') elif data_words[0] == 'ROOMLIST': if occupied_room_names: self.send_msg('system: the list fo avaliable rooms: ' + ', '.join(occupied_room_names)) else: self.send_msg('system: no rooms have been created yet') elif data_words[0] == 'DISCONNECT': if self.room: self.room.disconnect_user(self) else: self.send_msg('system: you are not in the room!') elif data_words[0] == 'BAN': if self.room: self.room.ban_user(self, data_words[1]) else: self.send_msg('system: you are not in the room!') elif data_words[0] == 'KICK': if self.room: self.room.kick_user(self, data_words[1]) else: self.send_msg('system: you are not in the room!') elif data_words[0] == 'PASSWORD': if self.room: self.room.change_pass(self, data_words[1]) else: self.send_msg('system: you are not in the room!') else: client_data = 'Can not recognize: ' + client_data break print(get_date(), client_data) self.conn.close()
import gmpy2 import rsa e = 65537 p = 302825536744096741518546212761194311477 q = 325045504186436346209877301320131277983 n = 98432079271513130981267919056149161631892822707167177858831841699521774310891 d = int(gmpy2.invert(e, (p - 1) * (q - 1))) private_key = rsa.PrivateKey(n, e, d, p, q) if __name__ == '__main__': filename = "/Users/neal/Downloads/fujian/encrypted.message1" filename2 = "/Users/neal/Downloads/fujian/encrypted.message2" filename3 = "/Users/neal/Downloads/fujian/encrypted.message3" with open(filename, 'rb') as f: print(rsa.decrypt(f.read(), private_key).decode()) with open(filename2, 'rb') as f: print(rsa.decrypt(f.read(), private_key).decode()) with open(filename3, 'rb') as f: print(rsa.decrypt(f.read(), private_key).decode())
import rsa print('\\-------------------------------//') print('**Prj Banco de Dados Distribuidos**') print('\\-------------------------------//') print('Decifrador de mensagens') print('Digite as seguintes informacoes') arqnomepri = input('Endereco da chave privada (c:\chaves\myPri.txt): ') arqnomemsg = input( 'Endereco e nome da mensagem a ser decifrada (c:\msg.txt): ') ##abro o arquivo com a chave arq = open(arqnomepri, 'rb') ##carrego a chave txt = arq.read() arq.close() #decodifico para o formato expoente e modulo pri = rsa.PrivateKey.load_pkcs1(txt, format='PEM') #abro o arquivo com a msg arq = open(arqnomemsg, 'rb') ##carrego a msg cifrada msgc = arq.read() arq.close() #decifro a msg msg = rsa.decrypt(msgc, pri) print('Mensagem decifrada: ' + msg.decode('utf-8'))
def _sync_btn_clicked(self): if self.username == "": tkMessageBox.showinfo("Sync Failed", "Sync Failed, Please login!") else: ### Get Filenames from Server rospy.wait_for_service('/server/check_filenames') filenames_service = rospy.ServiceProxy('/server/check_filenames', CheckFiles) username_ser = username() username_ser.username = self.username resp = filenames_service(username_ser) #print resp server_filetimes = resp.filetimes server_files = resp.filenames.filenames client_files = [f for f in os.listdir('.') if os.path.isfile(f)] diff_files = self.Diff(server_files, client_files) ### Send Files to Server that server doesnt have ### Get Client Pub Key with open('../keys/' + self.username + '_key_pub.pem', mode='rb') as privatefile: data = privatefile.read() client_pubkey = rsa.PublicKey.load_pkcs1(data) rospy.wait_for_service('/server/update_server') update_server_service = rospy.ServiceProxy('/server/update_server', UpdateServer) diff = filenames() diff.filenames = [] files_to_send_list = [] keys_to_send_list = [] files_to_send = files() all_filenames = [f for f in os.listdir('.') if os.path.isfile(f)] filetimes = [] for filename in all_filenames: time = os.path.getmtime(filename) filetimes.append(time) for tindex, filename in enumerate(all_filenames): if filename not in server_files and 'key' not in filename: with open(filename, 'r') as myfile: data = myfile.read() key, data = self.aes_file(data) files_to_send_list.append(data) key = rsa.encrypt(key, client_pubkey) keys_to_send_list.append(key) diff.filenames.append(filename) elif filetimes[tindex] > server_filetimes[server_files.index( filename)] and 'key' not in filename: with open(filename, 'r') as myfile: data = myfile.read() key, data = self.aes_file(data) key = rsa.encrypt(key, client_pubkey) keys_to_send_list.append(key) files_to_send_list.append(data) diff.filenames.append(filename) files_to_send.files = files_to_send_list success = update_server_service(username_ser, diff, files_to_send, keys_to_send_list) ### Get files client doesnt have from server rospy.wait_for_service('/server/update_client') update_client_service = rospy.ServiceProxy('/server/update_client', UpdateClient) all_filenames = [f for f in os.listdir('.') if os.path.isfile(f)] filetimes = [] for filename in all_filenames: time = os.path.getmtime(filename) filetimes.append(time) files_to_get_list = [] for tindex, filename in enumerate(server_files): if filename not in client_files and 'key' not in filename: files_to_get_list.append(filename) elif 'key' not in filename and filetimes[all_filenames.index( filename)] < server_filetimes[server_files.index( filename)]: files_to_get_list.append(filename) files_to_get = filenames() files_to_get.filenames = files_to_get_list resp = update_client_service(username_ser, files_to_get) ### Read in encrypted file and decrypt for index, filename in enumerate(resp.filenames.filenames): ### Decrypt encrypted key symm_key = rsa.decrypt(resp.keys[index], self.client_privkey) ### Decrypt the file using symm key data = self.de_aes_file(resp.files.files[index], symm_key) with open(filename, "w") as text_file: text_file.write(data)
def decrypt(self, text): decrypt_text = rsa.decrypt(a2b_hex(text), self.prikey) return decrypt_text
def process_message(self, message): if self.network_encryption: message = self.network_encryption.decrypt( base64.urlsafe_b64decode(message)).decode('utf-8') else: message = message.decode('utf-8') key, data = message.split('§', maxsplit=1) tempfernet = Fernet(rsa.decrypt( base64.urlsafe_b64decode(key.encode('utf-8')), self.private)) data = json.loads(base64.urlsafe_b64decode(tempfernet.decrypt( base64.urlsafe_b64decode(data.encode('utf-8')))).decode('utf-8')) data['args'] = [pickle.loads(base64.urlsafe_b64decode( arg.encode('utf-8'))) for arg in data['args']] data['kwargs'] = {k: pickle.loads(base64.urlsafe_b64decode( data['kwargs'][k].encode('utf-8'))) for k in data['kwargs'].keys()} if data['path'] in self.endpoints.keys(): try: aspec = inspect.getfullargspec(self.endpoints[data['path']]) # I see you <3 if 'node' in aspec.kwonlyargs or aspec.varkw: data['kwargs']['node'] = self if 'originator' in aspec.kwonlyargs or aspec.varkw: data['kwargs']['originator'] = [data['originator'], data['originator_name']] value = self.endpoints[data['path']](*data['args'], **data['kwargs']) if type(value) == SpearResponse: status = value.status value = value.data else: status = 200 return_data = { 'type': 'response', 'originator': self.id, 'originator_name': self.name, 'originator_key': base64.urlsafe_b64encode(self.public.save_pkcs1()).decode('utf-8'), 'target': data['originator'], 'result_status': status, 'result': base64.urlsafe_b64encode(pickle.dumps(value)).decode('utf-8') } except: return_data = { 'type': 'response', 'originator': self.id, 'originator_name': self.name, 'originator_key': base64.urlsafe_b64encode(self.public.save_pkcs1()).decode('utf-8'), 'target': data['originator'], 'result_status': 500, 'result': f'Remote function encountered an unexpected error: {traceback.format_exc()}' } else: return_data = { 'type': 'response', 'originator': self.id, 'originator_name': self.name, 'originator_key': base64.urlsafe_b64encode(self.public.save_pkcs1()).decode('utf-8'), 'target': data['originator'], 'result_status': 404, 'result': f'Path "{data["path"]}" not found.' } encoded_response = base64.urlsafe_b64encode(json.dumps(return_data).encode('utf-8')) encrypted_response = tempfernet.encrypt(encoded_response) packed_response = base64.urlsafe_b64encode(encrypted_response) if self.network_encryption: packed_response = base64.urlsafe_b64encode(self.network_encryption.encrypt(packed_response)) return packed_response
import rsa import base64 tempb = base64.b64decode(input()) print(tempb) f = open("test2.pem", "rb") keydata = f.read() f.close() privkey = rsa.PrivateKey.load_pkcs1(keydata, 'PEM') message = rsa.decrypt(tempb, privkey) print(message)
def data_parse(self, sock, data): address = self.addresses[sock] # incoming socket address incoming_type = self.get_socket_type( sock) # again, we check the incoming type here too # if data length is greater than zero then process it, if not drop the connection # sockets somehow send empty messages when disconnecting if len(data) > 0: s_data = str(data) # make data a string if not s_data_arr = s_data.split(",") # and split using , identifier = int(s_data_arr[0]) # 1 for request 1,hostname # 2 for response 2,hostname # 3 for response response 3,hostname # 4 for messaging 4,mtime,host,dest,msg # 5 for hostname exchange 5,host,host,host,host... # 6 for key exchange request 6,host,dest,publickey # 7 for key exchange response 7,host,dest,pass if identifier == 1: name = s_data_arr[1] # than it's the remote hostname if name not in self.hosts.keys(): # if we don't know them yet self.hosts[name] = [0, 0] # add it to our hosts dict if incoming_type == "wifi": # and set the address accordingly self.hosts[name][0] = address else: self.hosts[name][1] = address if self.cleanup( ) == True: # call the cleanup function, this removes bluetooth sockets if connected via wifi return True # if it returns true, drop the connection here # print IRC style connection messages sock.send("2,%s\t" % self.hostname) return True elif identifier == 2: sock.send("3,%s\t" % self.hostname) name = s_data_arr[1] rowc = 0 rows = conn.execute("SELECT * FROM messages WHERE dest=\"" + name + "\"") for row in rows: rowc += 1 sock.send("4," + self.get_data(row[0], row[1], row[2], row[3])) print self.get_data(row[0], row[1], row[2], row[3]) print "Queued message [%s] sent." % row[3] if rowc > 0: conn.execute("DELETE FROM messages WHERE dest=\"" + name + "\"") conn.commit() print "Messages belonged to %s are removed from database." % name if name not in self.hosts.keys(): # if we don't know them yet self.hosts[name] = [0, 0] # add it to our hosts dict if incoming_type == "wifi": # and set the address accordingly self.hosts[name][0] = address else: self.hosts[name][1] = address self.add_text("\n%s (%s) has joined." % (name, incoming_type)) self.add_connection(s_data_arr[1], "direct") sock.send("5,%s\t" % ",".join([row[1] for row in self.discovered])) return True # all is well elif identifier == 3: name = s_data_arr[1] rowc = 0 rows = conn.execute("SELECT * FROM messages WHERE dest=\"" + name + "\"") for row in rows: rowc += 1 sock.send("4," + self.get_data(row[0], row[1], row[2], row[3])) print self.get_data(row[0], row[1], row[2], row[3]) print "Queued message [%s] sent." % row[3] if rowc > 0: conn.execute("DELETE FROM messages WHERE dest=\"" + name + "\"") conn.commit() print "Messages belonged to %s are removed from database." % name if name not in self.hosts.keys(): # if we don't know them yet self.hosts[name] = [0, 0] # add it to our hosts dict if incoming_type == "wifi": # and set the address accordingly self.hosts[name][0] = address else: self.hosts[name][1] = address self.add_text("\n%s (%s) has joined." % (name, incoming_type)) sock.send("5,%s\t" % ",".join([row[1] for row in self.discovered])) self.add_connection(s_data_arr[1], "direct") return True # all is well elif identifier == 4: mtime = datetime.datetime.fromtimestamp(int( s_data_arr[1])) # get its time host = s_data_arr[2] # host, dest = s_data_arr[3] # destination message = ",".join(s_data_arr[4:]) # if we processed it before, drop it, if not add it to messages list if s_data not in self.messages: self.messages.append(s_data) else: return True if dest != "": if dest == self.hostname: if host not in self.blocked: if host in self.keys.keys(): message = self.decrypt(message, self.keys[host]) self.add_text( "\n[%s] %s: %s" % (self.get_time(mtime), host, message)) return True elif dest in self.hosts.keys(): if self.hosts[dest][0] != 0: sock = self.peers[self.hosts[dest][0]] sock.send(s_data + "\t") else: sock = self.peers[self.hosts[dest][1]] sock.send(s_data + "\t") print "Data sent to that host" return True else: conn.execute( "INSERT INTO messages VALUES (?, ?, ?, ?)", (int(s_data_arr[1]), host, dest, message)) print "Messaged added to queue" conn.commit() self.send_all(4, mtime=int(s_data_arr[1]), host=host, dest=dest, message=message) return True else: if host not in self.blocked: self.add_text("\n[%s] %s: %s" % (self.get_time(mtime), host, message)) self.send_all(4, mtime=int(s_data_arr[1]), host=host, dest=dest, message=message) return True elif identifier == 5: for hostname in s_data_arr[1:]: self.add_connection(hostname, "remote") return True elif identifier == 6: if s_data not in self.messages: self.messages.append(s_data) else: return True host = s_data_arr[1] dest = s_data_arr[2] if dest == self.hostname: print "Messages between you and %s are encrypted from now on." % host remoteKey = rsa.PublicKey.load_pkcs1(s_data_arr[3]) key = str(random.randrange(1000000, 9999999)) keydata = base64.b64encode(rsa.encrypt(key, remoteKey)) self.keys[host] = key if host in self.hosts.keys(): if self.hosts[host][0] != 0: sock = self.peers[self.hosts[host][0]] sock.send("7," + self.hostname + "," + host + "," + keydata + "\t") else: sock = self.peers[self.hosts[host][1]] sock.send("7," + self.hostname + "," + host + "," + keydata + "\t") print "Data sent to that host" return True else: self.send_all(7, host=self.hostname, dest=host, key=keydata) return True else: self.send_all(6, host=host, dest=dest, key=s_data_arr[3]) return True elif identifier == 7: if s_data not in self.messages: self.messages.append(s_data) else: return True host = s_data_arr[1] dest = s_data_arr[2] print "Host: %s, dest: %s" % (host, dest) if dest == self.hostname: print "Messages between you and %s are encrypted from now on." % host key = rsa.decrypt(base64.b64decode(s_data_arr[3]), self.privateKey) self.keys[host] = key return True elif dest in self.hosts.keys(): if self.hosts[dest][0] != 0: sock = self.peers[self.hosts[dest][0]] sock.send("7," + host + "," + dest + "," + s_data_arr[3] + "\t") else: sock = self.peers[self.hosts[dest][1]] sock.send("7," + host + "," + dest + "," + s_data_arr[3] + "\t") print "Data sent to that host" return True else: self.send_all(7, host=host, dest=dest, key=s_data_arr[3]) else: # if data length is zero, drop the connection self.add_text("\n%s has quit. (ping timeout.)" % address) gobject.source_remove(self.sources[address]) hostname = None for host in self.hosts.keys(): if self.hosts[host][0] == self.addresses[sock] or self.hosts[ host][1] == self.addresses[sock]: hostname = host del self.hosts[host] del self.sources[address] del self.peers[address] del self.addresses[sock] if hostname != None: for row in self.discovered: # this is how you remove it from GTK tree view if row[1] == hostname: self.discovered.remove(row.iter) break sock.close() # close the connection return True
def Decrypt(jieshou, pk): #解密函数,传参与返回值请处理为字符串类型 Decrypt_Str = rsa.decrypt(jieshou, pk) Decrypt_Str_1 = Decrypt_Str.decode('utf8') return Decrypt_Str_1
from Crypto.Cipher import AES import rsa #problema para criar o objeto chave privada #privkey = rsa.PrivateKey(n, None, d, None, None) with open('chave_privada.pem', mode='rb') as privatefile: keydata = privatefile.read() print(keydata) privkey = rsa.PrivateKey.load_pkcs1(keydata, format='PEM') file = open("chave_aes_cifrada.pem", "r") chave_aes_cifrada = file.read().encode('utf8') file.close() chave_aes_simples = rsa.decrypt(chave_aes_cifrada, privkey) print(chave_aes_simples) file = open("texto_cifrado.txt", "r") texto_cifrado = file.read() file.close() obj = AES.new(chave_aes_simples, AES.MODE_ECB) texto_cifrado = obj.decrypt(texto_cifrado) print(texto_cifrado)
Scdiag = np.zeros(shape_LL) row = min(shape_LL) Scdiag[:row, :row] = np.diag(Sc) Sc = Scdiag alpha = 0.1 for py in range(0, min(shape_LL)): for px in range(0, min(shape_LL)): Wdnew[py][px] = (LLnew1[py][px] - Sc[py][px]) / alpha cv2.imwrite('images/recovered_watermark.jpg', Wdnew) with open('rsain.txt') as f: content = f.readlines() content = [int(x.strip()) for x in content] st = rsa.decrypt(content) comma = st.find(',') x0 = float(st[0:comma]) u = float(st[comma + 1:]) #Unscrambling x = logistic.get_x_array( x0, u, min(shape_LL)) #generating array of pseudo-random numbers using CLM img = cv2.imread('images/recovered_watermark.jpg', 0) h, w = np.shape(img) c = 0 for py in range(0, h): for px in range(0, w): img[py][px] = (img[py][px] ^ x[c]) % 256 c = c + 1
def decryptWithGhostPriKey(self, msg, isBase64In=True): dmsg = msg if isBase64In: dmsg = base64.b64decode(msg) text = rsa.decrypt(dmsg, self.gprivate_pem) return text
import gmpy2 import rsa p = 275127860351348928173285174381581152299 q = 319576316814478949870590164193048041239 n = 87924348264132406875276140514499937145050893665602592992418171647042491658461 e = 65537 d = int(gmpy2.invert(e, (p - 1) * (q - 1))) privatekey = rsa.PrivateKey(n, e, d, p, q) #根据已知参数,计算私钥 with open("flag.enc", "rb") as f: print(rsa.decrypt(f.read(), privatekey).decode()) #使用私钥对密文进行解密,并打印
def perform_operation(self, indata: bytes, priv_key: rsa.key.AbstractKey, cli_args: Indexable = ()) -> bytes: """Decrypts files.""" assert isinstance(priv_key, rsa.key.PrivateKey) return rsa.decrypt(indata, priv_key)
pubkeyContent = '''-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDK7sG7nZnIUAfl6Hf7UwYwdPKu UjslnB3xAWLZvL295i1e2+tDjN7Eli5yIbhxePxAE760tEAz+6UcWPRGDdlshNRo Gp4lWob1qMEg/7g8rxvhHioUFjnNE0kRy2OJJ9OQSViUagXs09qeqvs0AssOiGup S3CJ/G1Dy8TxcHHbwwIDAQAB -----END PUBLIC KEY-----''' message = 'Message' print("will encrypt: %s" %message) # load公钥和密钥 if pubkeyContent and pubkeyContent.startswith("-----BEGIN RSA PUBLIC KEY-----"): pubkey = rsa.PublicKey.load_pkcs1(pubkeyContent) else: #load_pkcs1_openssl_pem可以加载openssl生成的pkcs1公钥(实为pkcs8格式) pubkey = rsa.PublicKey.load_pkcs1_openssl_pem(pubkeyContent) privkey = rsa.PrivateKey.load_pkcs1(prikeyContent) # 用公钥加密、再用私钥解密 crypto = rsa.encrypt(message, pubkey) print(base64.b64encode(crypto)) message = rsa.decrypt(crypto, privkey) print(message) # sign 用私钥签名认证、再用公钥验证签名 #signature = rsa.sign(message, privkey, 'SHA-256') #signOK=rsa.verify(message, signature, pubkey) #print(signOK)
def decrypt_with_private_key(encryptedtext, EncryptionPrivateKey): message = rsa.decrypt(encryptedtext, EncryptionPrivateKey) return message
def _decrypt_by_private(key, pvt_file_path): with open(pvt_file_path, 'r') as pf: return rsa.decrypt(key, rsa.PrivateKey.load_pkcs1(pf.read()))