def decrypt(filename, password): print("Decrypting {0}".format(filename)) chunksize = 64 * 1024 nonce = 1 outFile, outFile_extension = path.splitext(filename) with open(filename, "rb") as infile: with open(outFile, "wb") as outfile: salt = infile.read(16) key = KDF.scrypt(password, salt, 32, N, r, p) while True: tag = infile.read(16) rchunk = infile.read(chunksize) if len(rchunk) == 0: # print('{} chunks used'.format(nonce)) break try: cipher = AES.new(key, AES.MODE_GCM, bytes(nonce)) outChunk = cipher.decrypt_and_verify(rchunk, tag) outfile.write(outChunk) nonce += 1 except ValueError: print(Fore.RED + "Integrity verification failed. " + "The password is wrong or the file " + "has been modified without authorization. " ) input("Press ENTER and try again.") outfile.close() remove(outFile) sys.exit()
def encrypt(filename, password): print("Encrypting {0}".format(filename)) chunksize = 64 * 1024 nonce = 1 salt = get_random_bytes(16) key = KDF.scrypt(password, salt, 32, N, r, p) outFile = filename + extension with open(filename, "rb") as infile: with open(outFile, "wb") as outfile: outfile.write(salt) while True: chunk = infile.read(chunksize) if len(chunk) == 0: # print('{} chunks used'.format(nonce)) break cipher = AES.new(key, AES.MODE_GCM, bytes(nonce)) outChunk, tag = cipher.encrypt_and_digest(chunk) outfile.write(tag) outfile.write(outChunk) nonce += 1
def Password(self, psw: str, saltIn: bytes = get_random_bytes(16)): self.__salt = saltIn self.__key = KDF.scrypt(psw, self.__salt, 32, 16384, 8, 1)