关于python:python使用Crypto库实现加密解密

5次阅读

共计 1521 个字符,预计需要花费 4 分钟才能阅读完成。

一:crypto 库装置

pycrypto,pycryptodome 是 crypto 第三方库,pycrypto 曾经进行更新三年了,所以不倡议装置这个库;pycryptodome 是 pycrypto 的延长版本,用法和 pycrypto 是截然不同的;所以只须要装置 pycryptodome 就能够了

pip install pycryptodome

二:python 应用 crypto

1:crypto 的加密解密组件 des.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

from Crypto.Cipher import DES
from binascii import b2a_hex, a2b_hex
class MyDESCrypt: #本人实现的 DES 加密类
    def __init__(self, key = ''):
        #密钥长度必须为 64 位,也就是 8 个字节
        if key is not '':
            self.key = key.encode('utf-8')
        else:
            self.key = '12345678'.encode('utf-8')
        self.mode = DES.MODE_CBC
    # 加密函数,如果 text 有余 16 位就用空格补足为 16 位,# 如果大于 16 过后不是 16 的倍数,那就补足为 16 的倍数。def encrypt(self,text):
        try:
            text = text.encode('utf-8')
            cryptor = DES.new(self.key, self.mode, self.key)
            # 这里密钥 key 长度必须为 16(DES-128),
            # 24(DES-192), 或者 32(DES-256)Bytes 长度
            # 目前 DES-128 足够目前应用
            length = 16   #lenth 能够设置为 8 的倍数
            count = len(text)
            if count < length:
                add = (length - count)
                # \0 backspace
                # text = text + ('\0' * add)
                text = text + ('\0' * add).encode('utf-8')
            elif count > length:
                add = (length - (count % length))
                # text = text + ('\0' * add)
                text = text + ('\0' * add).encode('utf-8')
            self.ciphertext = cryptor.encrypt(text)
            # 因为 DES 加密时候失去的字符串不肯定是 ascii 字符集的,输入到终端或者保留时候可能存在问题
            # 所以这里对立把加密后的字符串转化为 16 进制字符串
            return b2a_hex(self.ciphertext)
        except:
            return ""
    # 解密后,去掉补足的空格用 strip() 去掉
    def decrypt(self, text):
        try:
            cryptor = DES.new(self.key, self.mode, self.key)
            plain_text = cryptor.decrypt(a2b_hex(text))
            # return plain_text.rstrip('\0')
            return bytes.decode(plain_text).rstrip('\0')
        except:
            return ""

2:crypto 组件应用

from . import des
msg = "password is 961223"
key = "12345678"  #key 值可传可不传
des1 = des.MyDESCrypt()
#加密
cipherTxt = des1.encrypt(msg)  #返回值为 bytes 型
print(cipherTxt)
#解密
decTxt = des1.decrypt(cipherTxt);  #返回值为 str 型
print(decTxt)
正文完
 0