python-自动化篇-办公-文件-加解密

解说

要使⽤Python进⾏⽂件的加密和解密,可以使⽤第三⽅加密库,如cryptography或pycryptodome。
⼀个基本的⽰例,演⽰如何使⽤cryptography库对⽂件进⾏加密和解密:

  1. 安装cryptography库:
    pip install cryptography
    

  2. ⽂件加密: Encryption.py
    from cryptography.fernet import Fernet 
    
    # ⽣成加密密钥 
    key = Fernet.generate_key() 
    cipher_suite = Fernet(key) 
    
    # 读取要加密的⽂件 
    with open('plain_file.txt', 'rb') as file: 
    	plain_text = file.read()
    
    # 加密⽂件内容 
    cipher_text = cipher_suite.encrypt(plain_text) 
    
    # 将加密后的内容写⼊⽂件 
    with open('encrypted_file.txt', 'wb') as file: 
    	file.write(cipher_text) 
    
    # 保存密钥⽤于解密 
    with open('encryption_key.key', 'wb') as key_file: 
    	key_file.write(key)
    
  3. ⽂件解密: Decrypt.py
    from cryptography.fernet import Fernet 
    
    # 从⽂件中加载密钥 
    with open('encryption_key.key', 'rb') as key_file: 
    	key = key_file.read() 
    
    cipher_suite = Fernet(key) 
    
    # 读取要解密的⽂件 
    with open('encrypted_file.txt', 'rb') as file: 
    	cipher_text = file.read() 
    
    # 解密⽂件内容 
    plain_text = cipher_suite.decrypt(cipher_text) 
    
    # 将解密后的内容写⼊⽂件 
    with open('decrypted_file.txt', 'wb') as file: 
    	file.write(plain_text)
    

 创建文件:plain_file.txt

  加密:py.exe  Encryption.py

  解密:py.exe  Decrypt.py

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-05 20:30:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-05 20:30:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-02-05 20:30:02       82 阅读
  4. Python语言-面向对象

    2024-02-05 20:30:02       91 阅读

热门阅读

  1. vue3.x 英文转换成简体中文

    2024-02-05 20:30:02       51 阅读
  2. AI智能语音机器人安装方法

    2024-02-05 20:30:02       46 阅读
  3. 【CSS transition(过渡效果)——详解】

    2024-02-05 20:30:02       51 阅读
  4. Python 泛型

    2024-02-05 20:30:02       42 阅读
  5. OpenGL的着色器内存访问

    2024-02-05 20:30:02       51 阅读
  6. ES6-const

    2024-02-05 20:30:02       44 阅读
  7. 云数据库RDS云监控

    2024-02-05 20:30:02       42 阅读
  8. iOS面试题

    2024-02-05 20:30:02       52 阅读