def process_request(self, request): # ugly hack 1 # authenticate user based on email. This will be a non persistent authentication # required to bypass djangos @login_required decorator. no session or cookie can # be set here. if request.method == 'GET': token = request.GET.get('token', '') if request.META.get('HTTP_X_USER_TOKEN') and validate_token(request.body, request) == True: token = unicode(request.META.get('HTTP_X_USER_TOKEN','')) user = None if not token == '': if request.user is not None and request.user.is_authenticated(): key = cm_credentials('shared_secret')[0:16] token = aes.decrypt(token, key) if not request.user.email == token: self.auth_user(request, token) else: # check validity key = cm_credentials('shared_secret') key = key[0:16] token = aes.decrypt(token, key) self.auth_user(request, token)
def test_decrypt(): ''' perform AES decryption using 128-bit hex_key on 128-bit ciphertext hex_ciphertext, where both key and ciphertext values are expressed in hexadecimal string notation. ''' p = "00112233445566778899aabbccddeeff" k = "000102030405060708090a0b0c0d0e0f" c = "69c4e0d86a7b0430d8cdb78070b4c55a" actual = AES.decrypt(k, c) assert actual == p p = "6bc1bee22e409f96e93d7e117393172a" k = "2b7e151628aed2a6abf7158809cf4f3c" c = "3ad77bb40d7a3660a89ecaf32466ef97" actual = AES.decrypt(k, c) assert actual == p p = "ae2d8a571e03ac9c9eb76fac45af8e51" k = "2b7e151628aed2a6abf7158809cf4f3c" c = "f5d3d58503b9699de785895a96fdbaaf" actual = AES.decrypt(k, c) assert actual == p p = "30c81c46a35ce411e5fbc1191a0a52ef" k = "2b7e151628aed2a6abf7158809cf4f3c" c = "43b1cd7f598ece23881b00e3ed030688" actual = AES.decrypt(k, c) assert actual == p p = "f69f2445df4f9b17ad2b417be66c3710" k = "2b7e151628aed2a6abf7158809cf4f3c" c = "7b0c785e27e8ad3f8223207104725dd4" actual = AES.decrypt(k, c) assert actual == p
def Test(self, ciphers, M): hashGen = hashlib.sha256() hashGen.update(str(self.key[0]).encode()) hash = hashGen.hexdigest() for cipher in ciphers: aes.decrypt(cipher, hash[:32]) if (M == aes.decrypt(cipher, hash[:32])): print('yes')
def decrypt_files(key, path, out_path): if os.path.exists(out_path): shutil.rmtree(out_path) shutil.copytree(path, out_path) for root, dirs, files in os.walk(out_path): for name in files: p = (os.path.join(root, name)) print(p) aes.decrypt(key, p) os.remove(p)
def AES(): while True: title('AES Encryption / Decryption', fillchar='-') [print() for i in range(5)] print('Do you want to...') print('1. Encrypt a file') print('2. Decrypt a file') print('3. Exit') print('_' * utils.get_terminal_size()[0]) print() action = input('>> ').lower() if action in ['1', 'encrypt', 'e']: title('AES Encryption / Decryption', fillchar='-') print() print() print('Please select a file in the dialog box.') Tk().withdraw() filename = askopenfilename(initialdir=cwd, title='Choose a file to encrypt...') password = getpass('Enter password for file: ').encode('utf-8') print('Choose the name for the encrypted file.') outfilename = asksaveasfilename( initialdir=cwd, title='Choose the name for the encrypted file...') chunksize = input('Enter encryption chunksize: ') or 64 * 1024 if chunksize: chunksize = int(chunksize) aes.encrypt(password, filename, outfilename, chunksize) elif action in ['2', 'decrypt', 'd']: title('AES Encryption / Decryption', fillchar='-') print() print() print('Please select a file in the dialog box.') Tk().withdraw() filename = askopenfilename(initialdir=cwd, title='Choose a file to decrypt...') password = getpass('Enter password to decrpyt file: ').encode( 'utf-8') print('Choose the name for the output file.') outfilename = asksaveasfilename( initialdir=cwd, title='Choose the name for the decrypted file...') chunksize = input('Enter decryption chunksize: ') or 24 * 1024 if chunksize: chunksize = int(chunksize) aes.decrypt(password, filename, outfilename, chunksize) elif action in ['3', 'exit', 'quit', 'q']: exit(0) else: clear() _tmp = input('That is not an action.')
def decrypt_file(key, file, out=None): if out is None: out = tempfile.gettempdir() else: if not os.path.isdir(out): os.makedirs(out) print('Output directory: %s' % out) filename = Path(file).stem path = os.path.join(out, filename) aes.decrypt(key, file, path) webbrowser.open(out) return path
def data_received(self, data: bytes) -> None: if self.state == STATE_OPEN and self.chall == True: print(data) sign = data[-256:] y = cert.verificaEC(self.cert) if y == True: data = data[:len(data) - 256] print(sign) if self.tipo == "AES": data = aes.decrypt(data, self.b, self.h, self.private_key) if self.tipo == "CHACHA20": data = chacha20.decrypt(data, self.h, self.private_key) print(data) else: print("Nao confiavel") elif self.state == STATE_OPEN and self.chall == False: pass elif self.state == STATE_DATA: print(data) if self.tipo == "AES": data = aes.decrypt(data, self.b, self.h, self.private_key) if self.tipo == "CHACHA20": data = chacha20.decrypt(data, self.h, self.private_key) """ Called when data is received from the client. Stores the data in the buffer :param data: The data that was received. This may not be a complete JSON message :return: """ logger.debug('Received: {}'.format(data)) try: self.buffer += data.decode() except: logger.exception('Could not decode data from client') idx = self.buffer.find('\r\n') while idx >= 0: # While there are separators frame = self.buffer[:idx + 2].strip() # Extract the JSON object self.buffer = self.buffer[ idx + 2:] # Removes the JSON object from the buffer self.on_frame(frame) # Process the frame idx = self.buffer.find('\r\n') if len(self.buffer ) > 4096 * 1024 * 1024: # If buffer is larger than 4M logger.warning('Buffer to large') self.buffer = '' self.transport.close()
def test_decrypt(self): iio = BytesIO() oio = BytesIO() for tv in self.__class__.TEST_VECTORS: iio.truncate(0) iio.seek(0) oio.truncate(0) oio.seek(0) iio.write(tv.cipher) iio.seek(0) aes.decrypt(iio, oio, tv.key, tv.moo) oio.seek(0) self.assertEqual(tv.text.hex(), oio.read().hex())
def createFile(addr, sock, filename): with open(str(addr) + '_' + filename, 'wb') as f: while True: # The loop gets empty padLen and data before breaking out. padLen = aes.decrypt(sock.recv(BLOCK_SIZE)).decode() if padLen: data = aes.decrypt(sock.recv(BLOCK_SIZE), int(padLen)) else: data = aes.decrypt(sock.recv(BLOCK_SIZE)) if not data: break # Write data to the file f.write(data)
def printfiles(filename): print "database_name:"+str(request.args.get('dbname', '')) if not os.path.dirname(__file__) == '': os.chdir(os.path.dirname(__file__)) returnstring="" fname=request.args.get('fname', '').replace('..','').replace('////','//') if (request.args.get('getJSON', '') == 'true') : return getJSON(fname,'trace') elif (request.args.get('getTimeline', '') == 'true') : return getJSON(fname,'timeline') if (request.args.get('save', '') == 'true') : passcode=request.form['pass'] encrypted=request.form['code'] blocksize = 256 if (aes.decrypt( passcode, password, blocksize )) != "secret": return "Failed" #decrypt the code now that we know its the valid password decrypted = aes.decrypt( encrypted, password, blocksize ) now = datetime.datetime.now() print 'save fname:'+fname #first backup the original file backupname= '../../frontend/projects/backup/'+now.strftime("%Y-%m-%d")+'_'+str(now.hour)+'/'+fname if not os.path.exists(os.path.dirname(backupname)): os.makedirs(os.path.dirname(backupname)) shutil.copyfile('../../frontend/projects/'+fname, backupname) f = open('../../frontend/projects/'+fname, 'w') f.write(decrypted) f.close() return "saved at: "+str(datetime.datetime.now()) if fname == '': fname='.' if (not os.path.isdir('../../frontend/projects/'+fname)): extension = os.path.splitext(fname)[1] with open('../../frontend/projects/'+fname, 'r') as content_file: content = content_file.read() return render_template('visualize.html',extension=extension,content=content,fname=fname) #return render_template('syntaxEditor.html',extension=extension,content=content,fname=fname) #'<html><body><textarea>'+ content.replace('<','<').replace('>','>')+'</textarea></body></html>' for dirname, dirnames, filenames in os.walk('../../frontend/projects/'+fname): for subdirname in dirnames: returnstring+="<br><a href='/files/fname?fname="+ os.path.join(fname, subdirname)+"'>"+subdirname+"</a>" for filename in filenames: extension = os.path.splitext(filename)[1] if extension == '.c' or extension == '.cpp': returnstring+="<li><a href='/files/fname?fname="+ os.path.join(fname, filename)+"'>"+filename+"</a></li>" return render_template('visualize.html',extension='folder',content='folder',fname=fname,contents=returnstring,db_name=request.args.get('dbname', ''))#return '<html><body>'+returnstring+'</body></html>'
def _decrypt_and_select_url(urls, cell=0, password=''): """ urls - encrypted urls cell - index of url to be decrypted. Use 0 as default. password - password to decrypt url on the specified position. Use empty string (not None) as default. """ return aes.decrypt(str(urls[cell]), password, 256)
def decrypt_message(cipher): #cipher = 000800460162 if API_DEBUG: print 'recieved cipher: ' + cipher #Divide the message into blocks of 4 chars and turn each one into hex #messageblocks = ['0008', '0046', '0162'] messageblocks = list(map(''.join, zip(*[iter(cipher)] * 4))) #convert to hex messageblocks = map(lambda x: int(hex(int(str(x))), 16), messageblocks) if API_DEBUG: print 'messageblocks: ' + str(np.array(messageblocks)) totdeciphered = [] st = 0 end = 16 #send blocks 16 bytes to decipher while end <= len(messageblocks): deciphered = aes.decrypt(messageblocks[st:end]) if API_DEBUG: print "deciphered:" + str(np.array(deciphered)) totdeciphered = totdeciphered + deciphered #set the pointers to to the next block st = st + 16 end = end + 16 if API_DEBUG: print "total deciphered:" + str(np.array(totdeciphered)) combined = convert2ascii(totdeciphered) if API_DEBUG: print "final:" + combined return combined
def buildchunk(chunk,partnum,type,todir,doc): filename = os.path.join(todir, ('part%04d' % partnum)) if type=='w': fileobj = open(filename, 'wb') if type=='a': fileobj=open(filename, 'a+') fileobj.write(chunk) fileobj.close() if partnum==1: key=aes.getKey(doc.key1) aes.decrypt(key, filename) if partnum==2: key=int(doc.key2) trans.decrypt(filename,key) if partnum==3: blow.decrypt(filename,filename+"(decrypted)",doc.key3)
def dataReceived(self, data): global is_authenticated if is_authenticated: print str(datetime.utcnow()) + " -- Decrypting Message:" print data mac = data[-64:] data = data[:-64] data = aes.decrypt(data, str(k_s)) hmac = aes.hmac(data, str(k_s)) if mac == hmac: self.factory.app.print_message("Other: " + data) else: self.factory.app.print_message("Integrity Check fails") else: if mode == "Server": global is_client_initializing if is_client_initializing == False: connection = self.factory.app.connection rslt = server_reply(conn=connection,recvMsg=data) is_client_initializing = True; self.factory.app.print_message(str(datetime.utcnow()) + " -- Received \"ClientInit\",ClientNounce from client") connection.write(rslt) else: self.factory.app.print_message(str(datetime.utcnow()) + " -- Authentication is done") server_recv(data) is_authenticated = True is_client_initializing = False; else: connection = self.factory.app.connection rslt = client_reply(recvMsg=data) is_authenticated = True self.factory.app.print_message(str(datetime.utcnow()) + " -- Server Sent Nounce") self.factory.app.print_message(str(datetime.utcnow()) + " -- Authentication is done") connection.write(rslt)
def decrypt(file_path, key): """Decrypts data with given key.""" key = Key.load(key) offset = 0 while True: state = State.load(file_path, offset) if state is None: break aes.decrypt(state, key) state.dump(file_path, offset) offset += 4 * constants.NB padding.remove(file_path)
def dec(): try: f = open(open_filename_address, "r") text = f.readline() text = text[:len(text) - 1] aad = f.readline() aad = aad[5:] salt = f.readline() salt = salt[6:len(salt) - 1] nonce = f.readline() nonce = nonce[7:len(nonce) - 1] cipher_text = f.readline() cipher_text = cipher_text[13:len(cipher_text) - 1] ciphertext = aes.decrypt(entry_password.get(), text, aad) print(ciphertext) text_to_save = str(ciphertext) x = open(save_filename_address, 'w') x.write(text_to_save) x.write('Aad: ' + aad) x.close() messagebox.showinfo("Complete", 'Your text was decryped\n\nsalt: ' + salt + '\n\nnonce: ' + nonce + '\n\nciphertext: ' + cipher_text + '\n\nplinetext: ' + ciphertext) decrypt_win.destroy() win.deiconify() except exceptions.InvalidTag: messagebox.showerror("Error", 'Your data is inavlid') entry_password.delete(0, END)
def decrypt(file, passwdfile, passwd): assert str(type(file)) == '<class \'PIL.PngImagePlugin.PngImageFile\'>' assert str( type(passwdfile)) == '<class \'PIL.PngImagePlugin.PngImageFile\'>' width, height = file.size result = [] passwd_result = [] for i in range(passwdfile.size[1]): for j in range(passwdfile.size[0]): red, green, blue = passwdfile.getpixel((j, i)) if (blue | green | red) == 0: break passwd_result.append(chr((green << 8) + blue)) passwd_result_str = ''.join(passwd_result) for i in range(height): for j in range(width): red, green, blue = file.getpixel((j, i)) if (blue | green | red) == 0: break result.append(chr((green << 8) + blue)) result_str = ''.join(result) if hashlib.sha512(passwd.encode('utf-8')).hexdigest() == passwd_result_str: try: result_str = aes.decrypt(passwd, result_str) return_dict = {'content': result_str, 'success': 'yes'} except: return_dict = {'content': 'Failed!', 'success': 'no'} else: return_dict = {'content': 'Failed!', 'success': 'no'} return return_dict
def _decrypt_and_select_url(urls, cell = 0, password = ''): """ urls - encrypted urls cell - index of url to be decrypted. Use 0 as default. password - password to decrypt url on the specified position. Use empty string (not None) as default. """ return aes.decrypt(str(urls[cell]), password, 256)
def decrypt(receiverPrivateKeyFile, senderPublicKeyFile, encrypted, base64Decode=False): if base64Decode: encrypted = base64.b64decode(encrypted) # base64 decode the object First signature = encrypted[:128] signed_body = encrypted[128:] encrypted_aes_key = encrypted[128:256] aes_encrypted_message = encrypted[256:] # Verifies the signed hash senderPublicKeyObj = RSA.importKey(open(senderPublicKeyFile).read()) sha1_hash = SHA256.new(signed_body) verifier = PKCS1_v1_5.new(senderPublicKeyObj) if not verifier.verify(sha1_hash, signature): return None # decrypt to get the AES key # --------------------------------------------------- receiverPrivateKeyObj = RSA.importKey(open(receiverPrivateKeyFile).read()) cipher = PKCS1_OAEP.new(receiverPrivateKeyObj) aes_key_and_iv = cipher.decrypt(encrypted_aes_key) aes_key = aes_key_and_iv[:16] iv = aes_key_and_iv[16:] # decrypt the message with AES key and iv # --------------------------------------------------- message = aes.decrypt(aes_key, iv, aes_encrypted_message) return message
def pull_message(server,user,secret,messageid,bits=22): hc = hashcash.hashcash(user,messageid,bits) url = "https://%s/pull.php" % server post = {'hashcash':hc,'auth':''} retrived = curlhttp.http(url,post) if retrived != '' and retrived != False: retrived = find_jsonstr(retrived) if retrived == False: return False try: j = json.loads(retrived) # figure out the decrypt key. decrypt_key = hmac.HMAC(secret,j['keyseed'].strip(),hashlib.sha1).hexdigest() # do HMAC check wanted_hmac = hmac.HMAC(decrypt_key,j['message'],hashlib.sha1).hexdigest() #print "deckey: %s" % decrypt_key #print "hmac: %s" % wanted_hmac if wanted_hmac.strip().lower() == j['hmac'].strip().lower(): j['message'] = aes.decrypt(j['message'],decrypt_key,128) else: return False except: return False return j else: return False
def decrypt2(self, text): """Decrypts encrypted 'text' with a expanded key using implemented AES algorithm""" text = base64.b64decode(text) iv = text[:AES.block_size] key=aes.expand_key(self.key) plaintext = aes.decrypt(key,iv,text[AES.block_size:]) return plaintext.rstrip(b"\0")
def get_link(item): content = getUrl(item.get('url'),useCookies=True) link=re.compile('(http://www.[^\.]+.pw/(?!&#)[^"]+)', re.IGNORECASE + re.DOTALL + re.MULTILINE + re.UNICODE).findall(content) if link: link=re.sub(r'&#(\d+);', lambda x: chr(int(x.group(1))), link[0]) header = {'User-Agent':UA, 'Referer':item.get('url')} data = getUrl(link,header=header,useCookies=True) f=re.compile('.*?name="f"\s*value=["\']([^"\']+)["\']').findall(data) s=re.compile('.*?name="s"\s*value=["\']([^"\']+)["\']').findall(data) r=re.compile('[\'"]action[\'"][,\s]*[\'"](http.*?)[\'"]').findall(data) if s: s=aes.decode_hls(s[0]) sk=re.compile('"stkey":"(.*?)"').findall(s) sk = sk[0] if sk else '' if f and r: enc_data=json.loads(base64.b64decode(f[0])) ciphertext = 'Salted__' + enc_data['s'].decode('hex') + base64.b64decode(enc_data['ct']) src=aes.decrypt(item.get('key'),base64.b64encode(ciphertext)) src=src.replace('"','').replace(sk,'').encode('utf-8') print src href=aes.decode_hls(src) if href: href +='|Referer=%s&User-Agent=%s'%(urllib.quote(r[0]),UA) return href return ''
def read_license_file(): '''This module reads a encrypted license file, decrypts it and reads the data into the dictionary LICENSE_PARAMS''' global LICENSE_PARAMS # print bgcolors.WARNING + '\nRead license file' + bgcolors.ENDC if not os.path.isfile(LICENSE_FILE): logger.info('License file does not exists') return (False, 'License file not found') # Decrypt license file decrypted = decrypt(LICENSE_FILE, ENCRYPT_PASS) try: license_dict = json.loads(decrypted) except Exception as e: return (False, 'License file is corrupted') # print 'License file data:', license_dict # Update license dict with latest license params LICENSE_PARAMS['validity'] = license_dict['validity'] LICENSE_PARAMS['uuid'] = license_dict['uuid'] LICENSE_PARAMS['license_id'] = license_dict['license_id'] return (True, 'Success')
def login( self, event = None ): password = self.passin.get() if aes.check_pass( password ): data = {} config = {} if isfile(home+'/Dropbox/.pwman/data'): with open(home+'/Dropbox/.pwman/data') as f: datastring = aes.decrypt( f.read(), password ) if datastring.strip() != '': try: data,config = cPickle.loads( datastring ) except ValueError: data = cPickle.loads( datastring ) self.app.set_data( data, password, config ) self.app.change_state( mainMenu ) else: self.login_fail() return
def getStreams(url): myurl, ret = url.split('@') content = getUrl(myurl) #sources=re.compile('__showWindow\([\'"](.*?)[\'"]').findall(content) sources = re.compile( '<span id=["\']span_link_links[\'"] onClick="\w+\(\'(.*?)\'').findall( content) #s=sources[0] out = [] for i, s in enumerate(sources): enc_data = json.loads(base64.b64decode(s)) ciphertext = 'Salted__' + enc_data['s'].decode( 'hex') + base64.b64decode(enc_data['ct']) src = aes.decrypt(ret, base64.b64encode(ciphertext)) src = src.strip('"').replace('\\', '') title = 'Link %d' % (i + 1) out.append({ 'title': title, 'tvid': title, 'key': ret, 'url': src, 'refurl': myurl, 'urlepg': '' }) return out
def decrypt(privKeyPath, encfilename, keyfilename, outfilename=None, chunksize=24 * 1024): if not outfilename: outfilename = splitext(outfilename) with open(privKeyPath, 'rb') as f: privKey = RSA.import_key(f.read()) with open(keyfilename, 'r') as f: encKey = PEM.decode(f.read())[0] rsa_dec = PKCS1_OAEP.new(privKey) key = rsa_dec.decrypt(encKey) aes.decrypt(key, encfilename, outfilename, chunksize)
def test_256bit_key_decrypt(self): key = '603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4' block = 'f3eed1bdb5d2a03c064b5a7e3db181f8' decrypted = decrypt(block,key, format_='x') expected = '6bc1bee22e409f96e93d7e117393172a' self.assertEqual(decrypted, expected)
def test_192bit_key_decrypt(self): key = '8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b' block = 'bd334f1d6e45f25ff712a214571fa5cc' decrypted = decrypt(block,key, format_='x') expected = '6bc1bee22e409f96e93d7e117393172a' self.assertEqual(decrypted, expected)
def decrypt_message(message, key): ''' Decrypt a message using AES :param message: the message to be decrypted :param key: the decryption key to use :return: the decrypted message ''' return decrypt(message, int_key_to_n_char_arr(key))
def test_128bit_key_decrypt(self): key = '2b7e151628aed2a6abf7158809cf4f3c' block = '3ad77bb40d7a3660a89ecaf32466ef97' decrypted = decrypt(block,key, format_='x') expected = '6bc1bee22e409f96e93d7e117393172a' self.assertEqual(decrypted, expected)
def listenTracker(self, tracker): """ Método para escutar mensagens do tracker """ while True: cripted_data = tracker.recv(1024) data = aes.decrypt(self.simKey, cripted_data).decode() # caso possua prefixo -set, stá recebendo uma lista atualizada de peers if data[:5] == '-set ': peers = data[5:] # cria uma lista de dicionários a partir do arquivo json self.peers = json.loads(peers) print('[Client]>> Received Peers from Tracker:', self.peers) # se possuir prefixo -acc a solicitação de conexão com outro peer foi aceita elif data[:5] == '-acc ': contactInfo = data[5:] contactInfo = json.loads(contactInfo) if self.connection: print('You already have an active conection with ' + self.connection['user']) print('It will be terminated') msg = rsa.encrypt(self.connection['pKey'], b'-q') self.connection['conn'].send(msg) self.connection['conn'].close() self.connection = {} print('[Client]>> ' + contactInfo['user'] + ' accepted your invite.') print('Connecting...') # cria a nova conexão com o outro peer sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.connect((contactInfo['ip'], int(contactInfo['port']))) self.createConnHandshake(sock) # atualiza a conexão ativa self.connection['user'] = contactInfo['user'] self.connection['conn'] = sock # envia a essa nova conexão seu nome de usuário msg = rsa.encrypt(self.connection['pKey'], self.user.encode()) sock.send(msg) print('[Client]>> You are now connected to', contactInfo['user']) # cria a thread para escutar essa conexão lThread = threading.Thread(target=self.handler) lThread.daemon = True lThread.start()
def process_response(self, request, response): # ugly hack 2 # this takes the response from the logged in view, authenticates the user again based on token, # adds user session to memcache and sends a cookie back to browser. # This makes sure that the entire auth process is successful. token = request.GET.get('token', '') if request.META.get('HTTP_X_USER_TOKEN') and validate_token(request.body, request) == True: token = unicode(request.META.get('HTTP_X_USER_TOKEN','')) user = None if hasattr(request, 'user'): if request.user.is_authenticated(): return response if not token == '': try: key = cm_credentials('shared_secret')[0:16] token = aes.decrypt(token, key) user = User.objects.get(email=token) except: user = None if user is not None and user.is_active: try: # We do not log here, because we have a handler registered # to perform logging on successful logins. key = cm_credentials('shared_secret')[0:16] token = aes.decrypt(token, key) user = authenticate(email=token) login(request, user) request.session.set_expiry(604800) except Exception as e: raise max_age = 1209600 expires_time = time.time() + max_age expires = cookie_date(expires_time) response.set_cookie(settings.EDXMKTG_LOGGED_IN_COOKIE_NAME, 'true', max_age=max_age, expires=expires, domain=settings.SESSION_COOKIE_DOMAIN, path='/', secure=None, httponly=None) return response
def decrypt(readable, writable, d, n): """ Decrypt message from _readable_ to _writable_ using the private exponent _d_, the modulus _n_ and the AES algorithm """ import aes s = _bytesize(n) # read and decrypt the AES key using the RSA algorithm v = int.from_bytes(readable.read(s), byteorder='little', signed=False) b = pow(v, d, n) # the decrypted key used for the symmetric cipher encryption is invalid if _bytesize(b) != (AES_KEY_SIZE // 8): raise BadKeyError k = b.to_bytes(AES_KEY_SIZE // 8, byteorder='little') # decrypt the message from the input IO using AES aes.decrypt(readable, writable, k)
def load_store(nam, pwd): with open(fnam(nam), "r") as f: q = json.loads(f.read()) ciph = q["ciph"] tag = q["tag"] nonce = q["nonce"] mne, val = decrypt(ciph, tag, nonce, pwd) return mne, val
def send(self, ob, key): self.logger.info("Calling: %s" % ob) st = aes.encrypt(json.dumps(ob, cls=ComplexEncoder), key) self.socket.send(st) res = self.socket.recv() res = aes.decrypt(res, key) self.socket.close() self.context.destroy() return json.loads(res)
def processResponse(addr, sock, filename, rttStart): restype = aes.decrypt(sock.recv(BLOCK_SIZE)) # Round Trip time for the request is calculated when a response is obtained from the server. RTT = time.time() - rttStart # Simply print the error if response is a text, else make a file using the # bytes. if restype == b't': print( aes.decrypt(sock.recv(MAX_SVR_RESP_TXT_LEN)).decode().strip('\n')) elif restype == b'f': createFile(addr, sock, filename) print("File received from ({}) and successfully created!".format(addr)) else: print("Unknown response type...") print("Rount trip time =", RTT)
def tweets(): searchTerm = request.args.get('filter') #search term print 'searched for: ', searchTerm auth = request.args.get('auth') #encrypted access key, token passed from client app auth = auth.replace(' ', '+') access = aes.decrypt(auth).split() #access[0] is key, access[1] is secret auth = tweepy.OAuthHandler(consumer_token, consumer_secret) auth.set_access_token(access[0], access[1]) return Response(stream.streamTweets(auth, searchTerm))
def user_dsiplay(): auth_url = "yourproject_id" password = "******" project_id = "yourproject_id" user_id = "youruser_id" region_name = "your_region" conn = swiftclient.Connection(key=password, authurl=auth_url, auth_version='3', os_options={ "project_id": project_id, "user_id": user_id, "region_name": region_name }) container_name = 'original_folder' filename = request.form['display'] print filename downloaded = conn.get_object(container_name, filename) print downloaded print downloaded[0]['content-length'] print 'before this' f = open(filename, "w") f.write(downloaded[1]) f = open(filename) temp_content = f.read() temp_name = f.name print temp_content print temp_name # decrypt_name = f.name aes.decrypt(temp_name, "test", outputfile=None) f.close() f_f = open(filename[:-4]) f_content = f_f.read() f_f.close() os.remove(filename) return f_content
def Descripto(): s = Stegana() blocksize = 256 key = tkSimpleDialog.askstring('Criptografia AES', 'Digite a chave:') txt_descripto = aes.decrypt(s, key, blocksize) salva_text = tkFileDialog.asksaveasfile(mode='w', defaultextension=".txt") salva_text.write(txt_descripto) print 'O texto Descriptografado' print txt_descripto return Descripto
def get_streams(url,title): myurl,ret=url.split('@') content = getUrl(myurl) sources=re.compile('__showWindow\([\'"](.*?)[\'"]').findall(content) #s=sources[0] out=[] for s in sources: enc_data=json.loads(base64.b64decode(s)) ciphertext = 'Salted__' + enc_data['s'].decode('hex') + base64.b64decode(enc_data['ct']) src=aes.decrypt(ret,base64.b64encode(ciphertext)) src=src.strip('"').replace('\\','') out.append({'title':title,'tvid':title,'key':ret,'url':src,'refurl':myurl,'urlepg':''}) return out
def Descripto(): s = Stegana() blocksize = 256 key = tkSimpleDialog.askstring('Criptografia AES', 'Digite a chave:') txt_descripto = aes.decrypt(s , key, blocksize ) salva_text = tkFileDialog.asksaveasfile(mode='w', defaultextension=".txt") salva_text.write(txt_descripto) print 'O texto Descriptografado' print txt_descripto return Descripto
def getStreams(url): myurl,ret=url.split('@') content = getUrl(myurl) #sources=re.compile('__showWindow\([\'"](.*?)[\'"]').findall(content) sources=re.compile('<span id=["\']span_link_links[\'"] onClick="\w+\(\'(.*?)\'').findall(content) #s=sources[0] out=[] for i, s in enumerate(sources): enc_data=json.loads(base64.b64decode(s)) ciphertext = 'Salted__' + enc_data['s'].decode('hex') + base64.b64decode(enc_data['ct']) src=aes.decrypt(ret,base64.b64encode(ciphertext)) src=src.strip('"').replace('\\','') title = 'Link %d'%(i+1) out.append({'title':title,'tvid':title,'key':ret,'url':src,'refurl':myurl,'urlepg':''}) return out
def test_decrypt( self, add_round_key_mock, mix_columns_mock, shift_rows_mock, sub_bytes_mock ): """Tests decrypting State.""" for size in constants.ALLOWED_KEY_SIZES: rounds = constants.ROUNDS[size] key_ = key.Key(self._generate_data(size >> 3)) with self.subTest(size=size): add_round_key_mock.reset_mock() mix_columns_mock.reset_mock() shift_rows_mock.reset_mock() sub_bytes_mock.reset_mock() aes.decrypt(self.state, key_) self.assertEqual(rounds + 1, add_round_key_mock.call_count) self.assertEqual(rounds - 1, mix_columns_mock.call_count) self.assertEqual(rounds, shift_rows_mock.call_count) self.assertEqual(rounds, sub_bytes_mock.call_count)
def getChannelVideo(item): content = getUrl(item.get('url'), useCookies=True) links = re.compile('(http://www.[^\.]+.pw/(?!&#)[^"]+)', re.IGNORECASE + re.DOTALL + re.MULTILINE + re.UNICODE).findall(content) link = [x for x in links if '&#' in x] if link: link = re.sub(r'&#(\d+);', lambda x: chr(int(x.group(1))), link[0]) header = {'User-Agent': UA, 'Referer': item.get('url')} data = getUrl(link, header=header, useCookies=True) f = re.compile('.*?name="f"\s*value=["\']([^"\']+)["\']').findall(data) d = re.compile('.*?name="d"\s*value=["\']([^"\']+)["\']').findall(data) r = re.compile('.*?name="r"\s*value=["\']([^"\']+)["\']').findall(data) action = re.compile( '[\'"]action[\'"][,\s]*[\'"](http.*?)[\'"]').findall(data) srcs = re.compile('src=[\'"](.*?)[\'"]').findall(data) if f and r and d and action: payload = urllib.urlencode({'d': d[0], 'f': f[0], 'r': r[0]}) data2, c = getUrlc(action[0], payload, header=header, useCookies=True) link = re.compile( '\([\'"][^"\']+[\'"], [\'"][^"\']+[\'"], [\'"]([^"\']+)[\'"], 1\)' ).findall(data2) enc_data = json.loads(base64.b64decode(link[0])) ciphertext = 'Salted__' + enc_data['s'].decode( 'hex') + base64.b64decode(enc_data['ct']) src = aes.decrypt(item.get('key'), base64.b64encode(ciphertext)) src = src.replace('"', '').replace('\\', '').encode('utf-8') a, c = getUrlc(srcs[-1], header=header, useCookies=True) if srcs else '', '' a, c = getUrlc(src, header=header, useCookies=True) # print a if src.startswith('http'): href = src + '|Referer=%s&User-Agent=%s&X-Requested-With=ShockwaveFlash/22.0.0.209' % ( urllib.quote(action[0]), UA) #href =src+'|Referer=%s&User-Agent=%s'%(urllib.quote(action[0]),UA) #href = src print href return href, srcs[-1], header else: href = aes.decode_hls(src) if href: href += '|Referer=%s&User-Agent=%s&X-Requested-With=ShockwaveFlash/22.0.0.209' % ( urllib.quote(r[0]), UA) return href, srcs[-1], header return ''
def btn_decrypt_clicked(self): src_file_path = self.form.edit_line_src_file.text() dest_file_path = self.form.edit_line_dest_file.text() key = self.form.edit_line_key.text() if len(src_file_path) == 0: self.warning_box('请选择源文件') return if len(dest_file_path) == 0: self.warning_box('请选择解密后文件存放目录') return if len(key) == 0: self.warning_box('请输入密钥') return if not os.path.exists(src_file_path): self.warning_box('源文件不存在') return if not os.path.exists(dest_file_path): self.warning_box('解密后文件存放目录不存在') return with open(src_file_path, 'r') as f: try: enc = f.read() if len(enc) == 0: self.warning_box('源文件为空') return raw_back = decrypt(enc, key) if len(raw_back) == 0: self.warning_box('密钥错误') return self.write_dest_file( "%s/%s" % (dest_file_path, ntpath.basename(src_file_path)), raw_back) except ValueError: self.warning_box('源文件格式错误') return self.information_box('解密完成,请前往解密后文件存放目录查看')
def VIDEOLINK(url,name): req = urllib2.Request(url) req.add_header('User-Agent', _UserAgent_) response = urllib2.urlopen(req) httpdata = response.read() response.close() thumb = re.compile('<meta property="og:image" content="(.+?)" />').findall(httpdata) popis = re.compile('<meta property="og:description" content="(.+?)" />').findall(httpdata) config = re.compile('config.php?(.+?)"></script>', re.S).findall(httpdata) config = 'http://tn.nova.cz/bin/player/flowplayer/config.php'+config[0] try: desc = popis[0] except: desc = name req = urllib2.Request(config) req.add_header('User-Agent', _UserAgent_) response = urllib2.urlopen(req) httpdata = response.read() response.close() match = re.compile("'(.+?)';").findall(httpdata) key = 'EaDUutg4ppGYXwNMFdRJsadenFSnI6gJ' aes_decrypt = aes.decrypt(match[0],key,128).encode('utf-8') aes_decrypt = aes_decrypt.replace('\/','/') secret_token = re.compile('secret":"(.+?)"', re.S).findall(aes_decrypt) mediaid = re.compile('"mediaId":(.+?),').findall(aes_decrypt) datum = datetime.datetime.now() timestamp = datum.strftime('%Y%m%d%H%M%S') videoid = urllib.quote(nova_app_id + '|' + mediaid[0]) md5hash = nova_app_id + '|' + mediaid[0] + '|' + timestamp + '|' + secret_token[0] try: md5hash = hashlib.md5(md5hash) except: md5hash = md5.new(md5hash) signature = urllib.quote(base64.b64encode(md5hash.digest())) config = nova_service_url + '?t=' + timestamp + '&d=1&tm=nova&h=0&c='+videoid+ '&s='+signature req = urllib2.Request(config) req.add_header('User-Agent', _UserAgent_) response = urllib2.urlopen(req) httpdata = response.read() response.close() baseurl = re.compile('<baseUrl>(.+?)</baseUrl>').findall(httpdata) streamurl = re.compile('<media>\s<quality>(.+?)</quality>.\s<url>(.+?)</url>\s</media>').findall(httpdata) swfurl = 'http://voyo.nova.cz/static/shared/app/flowplayer/13-flowplayer.commercial-3.1.5-19-003.swf' for kvalita,odkaz in streamurl: rtmp_url = baseurl[0]+' playpath='+odkaz addLink(name,rtmp_url,thumb[0],desc)
def file_encryption(): """"File encryption/decryption using aes""" print("File encryption/decryption using aes\n\n") command = raw_input("Choose an action<Encrypt/Decrypt>: ") path = raw_input("Please type the file path: ") if os.path.exists(path): with open(path, "r") as file_to_read: text = file_to_read.read() if not text: print("File doesn't have content!") else: key = raw_input("Please type the key: ") paths_directory = os.path.dirname(path) rand_string = ''.join( random.choice(string.ascii_uppercase + string.digits) for _ in range(5)) file_extension = os.path.splitext(path)[1] if command.lower() == "encrypt": with open( "%s\encryption_%s%s" % (paths_directory, rand_string, file_extension), "w+") as file_to_write: encrypted_text = aes.encrypt(key, text.encode()) file_to_write.write(encrypted_text) print("Encryption completed successfully!") elif command.lower() == "decrypt": with open( "%s\decryption_%s%s" % (paths_directory, rand_string, file_extension), "w+") as file_to_write: decrypted_text = aes.decrypt(key, text) if decrypted_text: file_to_write.write(decrypted_text.decode()) print("Decryption completed successfully!") else: print("Command wasn't recognised!") else: print("File doesn't exists!") print("Closing...")
def getChannelVideo(item): content = getUrl(item.get('url'),useCookies=True) links=re.compile('(http://www.[^\.]+.pw/(?!&#)[^"]+)', re.IGNORECASE + re.DOTALL + re.MULTILINE + re.UNICODE).findall(content) link = [x for x in links if '&#' in x] if link: link=re.sub(r'&#(\d+);', lambda x: chr(int(x.group(1))), link[0]) header = {'User-Agent':UA, 'Referer':item.get('url')} data = getUrl(link,header=header,useCookies=True) f=re.compile('.*?name="f"\s*value=["\']([^"\']+)["\']').findall(data) d=re.compile('.*?name="d"\s*value=["\']([^"\']+)["\']').findall(data) r=re.compile('.*?name="r"\s*value=["\']([^"\']+)["\']').findall(data) action=re.compile('[\'"]action[\'"][,\s]*[\'"](http.*?)[\'"]').findall(data) srcs=re.compile('src=[\'"](.*?)[\'"]').findall(data) if f and r and d and action: payload=urllib.urlencode({'d':d[0],'f':f[0],'r':r[0]}) data2,c= getUrlc(action[0],payload,header=header,useCookies=True) link=re.compile('\([\'"][^"\']+[\'"], [\'"][^"\']+[\'"], [\'"]([^"\']+)[\'"], 1\)').findall(data2) enc_data=json.loads(base64.b64decode(link[0])) ciphertext = 'Salted__' + enc_data['s'].decode('hex') + base64.b64decode(enc_data['ct']) src=aes.decrypt(item.get('key'),base64.b64encode(ciphertext)) src=src.replace('"','').replace('\\','').encode('utf-8') a,c=getUrlc(srcs[-1],header=header,useCookies=True) if srcs else '','' a,c=getUrlc(src,header=header,useCookies=True) # print a if src.startswith('http'): href =src+'|Referer=%s&User-Agent=%s&X-Requested-With=ShockwaveFlash/22.0.0.209'%(urllib.quote(action[0]),UA) #href =src+'|Referer=%s&User-Agent=%s'%(urllib.quote(action[0]),UA) #href = src print href return href,srcs[-1],header else: href=aes.decode_hls(src) if href: href +='|Referer=%s&User-Agent=%s&X-Requested-With=ShockwaveFlash/22.0.0.209'%(urllib.quote(r[0]),UA) return href,srcs[-1],header return ''
def test_decrypt_2(self): ntk='00000000000000000000000000000000' ntc='66e94bd4ef8a2c3b884cfa59ca342b2e' ntp=aes.decrypt(ntk,ntc) self.assertEqual(ntp,'00000000000000000000000000000000',\ "sample decryption all 0 case")
def setUp(self): self.key = b'master key' self.message = b'secret message' # Lower workload then default to speed up tests. self.encrypt = lambda key, ciphertext: encrypt(key, ciphertext, 10000) self.decrypt = lambda key, ciphertext: decrypt(key, ciphertext, 10000)
from panda3d.core import * import aes import niraidata # Config prc = niraidata.CONFIG iv, key, prc = prc[:16], prc[16:32], prc[32:] prc = aes.decrypt(prc, key, iv) for line in prc.split('\n'): line = line.strip() if line: loadPrcFileData('nirai config', line) # Mount models.mf vfs = VirtualFileSystem.getGlobalPtr() vfs.mount('models.mf', '.', 0) # Run try: import main except SystemExit: pass except: raise
def test_decrypt_1(self): ntk='000102030405060708090a0b0c0d0e0f' ntc='69c4e0d86a7b0430d8cdb78070b4c55a' ntp=aes.decrypt(ntk,ntc) self.assertEqual(ntp,'00112233445566778899aabbccddeeff',\ "sample decryption from FIPS-197 Appendix C.1")
def decrypt_my_file(filename): with open(filename, 'r') as file_to_decrypt: decrypted = aes.decrypt(file_to_decrypt.read(), password, blocksize) with open(filename, 'w') as file_to_decrypt: file_to_decrypt.write(decrypted)
def parse_token(token): ''' 解析用户cookie内容 ''' return json.loads(aes.decrypt(aes.AES_KEY, urllib.unquote(token)))
def test_decrypt_0(self): ntk='2b7e151628aed2a6abf7158809cf4f3c' ntc='3925841d02dc09fbdc118597196a0b32' ntp=aes.decrypt(ntk,ntc) self.assertEqual(ntp,'3243f6a8885a308d313198a2e0370734',\ "sample decryption from FIPS-197 Appendix 2")
import aes import base64 from utils import chunkify, readfile if __name__ == '__main__': data = ''.join(readfile('testdata/7.txt')) data = base64.decode(data) data = chunkify(data,16) key = 'YELLOW SUBMARINE' decrypted = '' for d in data: decrypted += aes.decrypt(d, key) print(decrypted)