Python uses pyexcel to encrypt and decrypt spreadsheet files
Preparation for environmental construction:
1. Ensure that Python is installed (recommended version 3.6 and above).
2. Use PIP to install the required class libraries and tools.
$ pip install pyexcel pyexcel-xls pyexcel-xlsx pyexcel-ods3 pycrypto
Dependent class libraries:
1. 'pyexcel' - used to read and write spreadsheet files.
2. 'pyexcel xls' - used to process spreadsheet files in XLS format.
3. 'pyexcel xlsx' - used to process spreadsheet files in XLSX format.
4. 'pyexcel ods3' - used to process spreadsheet files in ODS format.
5. 'pycrypto' - used to encrypt and decrypt spreadsheet files.
Complete sample code:
python
import pyexcel as pe
from pyexcel._compact import BytesIO
from Crypto.Cipher import AES
def encrypt_file(file_path, key):
#Read Spreadsheet File
content = pe.get_array(file_name=file_path)
#Convert spreadsheet contents to strings
content_str = "".join(str(row) for row in content)
#Encrypted String
cipher = AES.new(key, AES.MODE_EAX)
nonce = cipher.nonce
ciphertext, tag = cipher.encrypt_and_digest(content_str.encode())
#Save encrypted content to a new spreadsheet file
encrypted_file_path = file_path + ".encrypted"
with open(encrypted_file_path, "wb") as file:
file.write(nonce)
file.write(tag)
file.write(ciphertext)
Print ("File encrypted and saved as:"+encrypted_file_path)
def decrypt_file(file_path, key):
#Read encrypted spreadsheet file
with open(file_path, "rb") as file:
nonce = file.read(16)
tag = file.read(16)
ciphertext = file.read()
#Decrypting content
cipher = AES.new(key, AES.MODE_EAX, nonce=nonce)
content_str = cipher.decrypt_and_verify(ciphertext, tag).decode()
#Convert string to spreadsheet content
content_list = eval(content_str)
#Extract the original file name
original_file_name = file_path.replace(".encrypted", "").replace(".xls", "").replace(".xlsx", "").replace(".ods", "")
#Save the decrypted content to a new spreadsheet file
decrypted_file_path = original_file_name + ".decrypted.xls"
pe.save_as(array=content_list, dest_file_name=decrypted_file_path)
Print ("File decrypted and saved as:"+decrypted_file_path)
#Testing
file_path = "example.xls"
Key=b "MySecretKey123456" # Encryption key (16 bytes)
#Encrypt files
encrypt_file(file_path, key)
#Decrypting files
decrypt_file(file_path + ".encrypted", key)
Summary:
The above example shows how to use pyexcel and pycrypto libraries to encrypt and decrypt spreadsheet files. By reading the content of the file and converting it into a string, then encrypting it using the AES algorithm and saving it to a new file. The decryption process is the opposite, reading the contents of the encrypted file, decrypting the string and converting it back to the spreadsheet format, and finally saving it as the decrypted file.
Please note that the encryption key should be 16 bytes of binary data. In the example, we used b "MySecretKey123456" as the key, and you can use your own key to encrypt and decrypt files.