Hướng dẫn python encrypt pickle file

I have a ml model that uses a vectorizer. This vectorizer contains sensitive data and is stored using pickle as a .pkl file.

How can I encrypt this pkl file, so that it requires a key to decrypt?

I tried using the below code for encryption.

def encrypt_file(filepath, key):
    f = Fernet(key)
    with open(filepath, "rb") as file:
        # read all file data
        file_data = file.read()

    # encrypt data
    encrypted_data = f.encrypt(file_data)

    with open(filepath, "wb") as file:
        file.write(encrypted_data)


def decrypt_file(filepath, key):
    f = Fernet(key)
    with open(filepath, "rb") as file:
        encrypted_data = file.read()
        
    decrypted_data = f.decrypt(encrypted_data)
    return decrypted_data

When I use the function on a txt file it works. The problem is that the pkl file does not seems to be encrypted, as it can still be used without decryption.

asked Sep 19, 2021 at 10:38

DarioDario

515 bronze badges

5

I couldn't get it to properly encrypt/decrypt a pickle file neither. It gave me distorted data on decryption.

So I did the next thing, switch libraries. pyAesCrypt does exactly what you want, so you don't have to reinvent the wheel.

See this sample code:

import pickle
import pyAesCrypt


def create_pickle(picklefile):
    data = {"data": "random"}
    with open(picklefile, "wb") as outfile:
        pickle.dump(data, outfile)


password = "please-use-a-long-and-random-password"
picklefile = "somefile.pkl"
picklefile_enc = f"{picklefile}.aes"
jsonfile = "tmp.json"
create_pickle(picklefile)

# encrypt
pyAesCrypt.encryptFile(picklefile, picklefile_enc, password)
# decrypt
pyAesCrypt.decryptFile(picklefile_enc, f"2_{picklefile}", password)

with open(f"2_{picklefile}", "rb") as infile:
    print(pickle.load(infile))

output

{'data': 'random'}

answered Sep 20, 2021 at 16:17

Hướng dẫn python encrypt pickle file

Edo AkseEdo Akse

3,3132 gold badges9 silver badges18 bronze badges

I need the pickle package installed under my Python 3.9 under Windows 10.

Nội dung chính

  • What I tried
  • Not the answer you're looking for? Browse other questions tagged python python-3.x windows pip pickle or ask your own question.
  • Mã ví dụ về dưa chua bằng Python
  • Những điều cần nhớ về dưa chua

What I tried

When trying with pip install pickle I was getting:

ERROR: Could not find a version that satisfies the requirement pickle (from versions: none) ERROR: No matching distribution found for pickle

Then I tried the solution suggested in this question using pip install pickle5 but got the following error:

error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/

I then tried to install the Tool suggested by the error but got same error message after trying again pip install pickle5.

Question

Which is the correct way to install pickle package under Python 3.9 in Windows 10?

UPDATE

There is no need to install pickle module as it comes already installed along with Python 3.x. Just needed to do import pickle and voila!

asked Jul 29, 2021 at 20:21

Cedric ZoppoloCedric Zoppolo

3,8295 gold badges28 silver badges48 bronze badges

2

Cedric UPDATED answer is right. Pickle exists within Python 3.9. You don't need pip install pickle. Just use it.

import pickle

answered Aug 19, 2021 at 18:03

1

I found a way that I'm not sure it's the optimal but it works.

I did pip install pickle4

And then in the script just

import pickle4 as pickle

UPDATE

There is no need to install pickle as it's already within Python 3.9. Just needed to import pickle and voila!

answered Jul 29, 2021 at 20:21

Cedric ZoppoloCedric Zoppolo

3,8295 gold badges28 silver badges48 bronze badges

For Generalized Summary, for almost all Python versions, you never need to worry for installing 'pickle' as it comes already installed with the python interpreter.
Hence, simple import works:

import pickle

In case this doesn't work, refer to Pickle Install Problems on Stack Overflow.
Another suggested way is to run: pip install pickle-mixin

For other Queries and Info, refer to Python Pickle Documentation.

answered Oct 24, 2021 at 5:02

Not the answer you're looking for? Browse other questions tagged python python-3.x windows pip pickle or ask your own question.

Pickle, là một phần của thư viện Python theo mặc định, là một mô-đun quan trọng bất cứ khi nào bạn cần sự bền bỉ giữa các phiên người dùng. Là một mô-đun, pickle cung cấp khả năng lưu các đối tượng Python giữa các quy trình.

Cho dù bạn đang lập trình cho cơ sở dữ liệu , trò chơi, diễn đàn hoặc một số ứng dụng khác phải lưu thông tin giữa các phiên, pickle rất hữu ích để lưu số nhận dạng và cài đặt. Mô-đun pickle có thể lưu trữ những thứ như kiểu dữ liệu như boolean, chuỗi và mảng byte, danh sách, từ điển, hàm, v.v.

Lưu ý:  Khái niệm tẩy rửa còn được gọi là nối tiếp, sắp xếp và làm phẳng. Tuy nhiên, điểm luôn giống nhau — lưu một đối tượng vào tệp để truy xuất sau này. Pickling hoàn thành điều này bằng cách ghi đối tượng dưới dạng một dòng byte dài. 

Mã ví dụ về dưa chua bằng Python

Để ghi một đối tượng vào tệp, bạn sử dụng mã theo cú pháp sau:

import pickle 
object = Object ()
filehandler = open (filename, 'w')
pickle.dump (object, filehandler)

Đây là cách một ví dụ trong thế giới thực trông như thế nào:

import pickle 
import math
object_pi = math.pi
file_pi = open ('filename_pi.obj', 'w')
pickle.dump (object_pi, file_pi)

Đoạn mã này ghi nội dung của object_pi vào file_pi của trình xử lý tệp , đến lượt nó được liên kết với tệp filename_pi.obj trong thư mục thực thi.

Để khôi phục giá trị của đối tượng vào bộ nhớ, hãy tải đối tượng từ tệp. Giả sử rằng dưa chua chưa được nhập để sử dụng, hãy bắt đầu bằng cách nhập nó:

import pickle 
filehandler = open (filename, 'r')
object = pickle.load (filehandler)

Đoạn mã sau khôi phục giá trị của số pi:

import pickle 
file_pi2 = open ('filename_pi.obj', 'r')
object_pi2 = pickle.load (file_pi2)

Đối tượng sau đó đã sẵn sàng để sử dụng một lần nữa, lần này là object_pi2 . Tất nhiên, bạn có thể sử dụng lại các tên ban đầu, nếu bạn thích. Ví dụ này sử dụng các tên riêng biệt để rõ ràng.

Những điều cần nhớ về dưa chua

Hãy ghi nhớ những điều này khi sử dụng mô-đun dưa chua:

  • Giao thức pickle dành riêng cho Python - nó không được đảm bảo là tương thích với nhiều ngôn ngữ. Rất có thể bạn không thể chuyển thông tin để làm cho nó hữu ích bằng Perl, PHP, Java hoặc các ngôn ngữ khác.
  • Cũng không có gì đảm bảo về khả năng tương thích giữa các phiên bản Python khác nhau. Sự không tương thích tồn tại bởi vì không phải mọi cấu trúc dữ liệu Python đều có thể được tuần tự hóa bởi mô-đun.
  • Theo mặc định, phiên bản mới nhất của giao thức dưa chua được sử dụng. Nó vẫn như vậy trừ khi bạn thay đổi nó theo cách thủ công.

Mẹo:  Ngoài ra, hãy tìm hiểu  cách sử dụng giá đỡ để lưu các đối tượng trong Python  cho một phương pháp khác để duy trì tính liên tục của đối tượng.