python - How safe is this code -


how safe code? can text/file decrypted without password?

from crypto.cipher import aes crypto import random import hashlib import base64 import os import struct   bs = 16 pad = lambda s: s + (bs - len(s) % bs) * chr(bs - len(s) % bs).encode() unpad = lambda s: s[:-ord(s[len(s)-1:])]  class aescipher(object):     def __init__(self, key, salt):         self.key = hashlib.pbkdf2_hmac('sha256', key.encode(), salt.encode(), 100000)  def encrypt(self, plaintext):     plaintext = pad(plaintext.encode())     iv = random.new().read(bs)     cipher = aes.new(key=self.key, mode=aes.mode_cbc, iv=iv)     enc = cipher.encrypt(plaintext)     return base64.b64encode(iv + enc).decode()  def decrypt(self, enc):     enc = base64.b64decode(enc)     iv = enc[:bs]     enc = enc[bs:]     cipher = aes.new(key=self.key, mode=aes.mode_cbc, iv=iv)     plaintext = cipher.decrypt(enc)     return unpad(plaintext).decode()  def encrypt_file(self, in_file_name, out_file_name=none, chunk_size=1024 * 64):     if not out_file_name:         out_file_name = in_file_name + '.enc'      iv = random.new().read(bs)     cipher = aes.new(key=self.key, mode=aes.mode_cbc, iv=iv)     file_size = os.path.getsize(in_file_name)      open(in_file_name, 'rb') in_file:         open(out_file_name, 'wb') out_file:             out_file.write(struct.pack('<q', file_size))             out_file.write(iv)              while true:                 chunk = in_file.read(chunk_size)                 if len(chunk) == 0:                     break                 elif len(chunk) % 16 != 0:                     chunk += b' ' * (16 - len(chunk) % 16)                  out_file.write(cipher.encrypt(chunk))  def decrypt_file(self, in_file_name, out_file_name=none, chunk_size=1024 * 64):     if not out_file_name:         out_file_name = os.path.splitext(in_file_name)[0]         if out_file_name == in_file_name:             out_file_name += '.decrypted'      open(in_file_name, 'rb') in_file:         open(out_file_name, 'wb') out_file:             orig_size = struct.unpack('<q', in_file.read(struct.calcsize('q')))[0]             iv = in_file.read(16)             cipher = aes.new(key=self.key, mode=aes.mode_cbc, iv=iv)              while true:                 chunk = in_file.read(chunk_size)                 if len(chunk) == 0:                     break                  out_file.write(cipher.decrypt(chunk))             out_file.truncate(orig_size) 

can use script encrypt data? use hashlib derivate key, maybe should use key derivation function pycrypto?


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -