python加解密

# -*- coding: utf-8 -*-
'''
依赖库: 
pip install pycryptodome #linux 下安装
pip install pycryptodomex #windows 下安装

'''
import sys
import os
from Cryptodome.Cipher import AES
from binascii import b2a_hex, a2b_hex
 
class Prpcrypt():
    def __init__(self, key):
        self.key = self.pad(key)
        self.mode = AES.MODE_CBC

    def pad(self, text, length=16):
        if type(text) is str:
            text = bytes(text, encoding='utf-8')
        text += b' ' * (length - (len(text) % length))
        return text
     
    #加密函数,如果text不是16的倍数【加密文本text必须为16的倍数!】,那就补足为16的倍数
    def encrypt(self, text):
        cryptor = AES.new(self.key, self.mode, self.key)
        #这里密钥key 长度必须为16(AES-128)、24(AES-192)、或32(AES-256)Bytes 长度.目前AES-128足够用
        text = self.pad(text)
        self.ciphertext = cryptor.encrypt(text)
        #因为AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题
        #所以这里统一把加密后的字符串转化为16进制字符串
        return b2a_hex(self.ciphertext)
     
    #解密后,去掉补足的空格用strip() 去掉
    def decrypt(self, text):
        cryptor = AES.new(self.key, self.mode, self.key)
        plain_text = cryptor.decrypt(a2b_hex(text))
        return str(plain_text, encoding="utf-8")
 

def encrypt_file(file_name, key):
    print("encrypt file {}".format(file_name))
    with open(file_name, 'r') as fp:
        plain_text = fp.read()
        # print(plain_text)
    obj = Prpcrypt(key)
    cipher_text = obj.encrypt(plain_text)
    new_file_name = "{}.crypt".format(file_name)
    with open(new_file_name, 'bw') as fp:
        fp.write(cipher_text)
    print("save cipher text to file {}".format(new_file_name))

def decrypt_file(file_name, key):
    print("decrypt file {}".format(file_name))
    with open(file_name, 'rb') as fp:
        cipher_text = fp.read()
    obj = Prpcrypt(key)
    plain_text = obj.decrypt(cipher_text)
    # print(plain_text)
    new_file_name = "tmp.txt"
    with open(new_file_name, 'w') as fp:
        fp.write(plain_text)
    print("save plain text to file {}".format(new_file_name))

def main():
    file_name = os.path.join(os.getcwd(), sys.argv[2])
    # print(file_name)
    if sys.argv[1].upper() == "ENCRYPT":
        encrypt_file(file_name, sys.argv[3])
    elif sys.argv[1].upper() == "DECRYPT":
        decrypt_file(file_name, sys.argv[3])

def print_help():
    print("python encrypt.py <Action> <File> <Key>")
    print("  Action: encrypt or decrypt")
    print("  File: file name with path")
    print("  Key: personal key")

if __name__ == '__main__':
    if len(sys.argv) !=4:
        print(len(sys.argv))
        print_help()
    else:
        main()
posted @ 2019-06-09 00:44  木lin木  阅读(220)  评论(0编辑  收藏  举报