字符串加密与解密

常用的加密方法主要有两种:base64和pycrypto模块。

base64

>>> import base64
>>> encoded = base64.b64encode(b'data to be encoded')
>>> encoded
b'ZGF0YSB0byBiZSBlbmNvZGVk'
>>> data = base64.b64decode(encoded)
>>> data
b'data to be encoded'

使用base64加密方法非常简单,但安全性不是很高,在别人知道密文的情况下会很容易解密出明文。

  • 编码
    将3个字节转换成4个字节((3 X 8)=24=(4X6)),先读入3个字节,每读一个字节,左移8位,再右移四次,每次6位,这样就有4个字节了。
  • 解码
    将4个字节转换成3个字节,先读入4个6位(用或运算),每次左移6位,再右移3次,每次8位,这样就还原了。

pycrypto模块

from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex

from django.conf import settings


class Cryptography:
    """
    对称加密
    """
    # key使用settings中定义的一个常量
    def __init__(self, key=settings.PASSWORD_KEY):
        self.key = key
        self.mode = AES.MODE_CBC

    def encrypt(self, text):
        """加密操作"""
        cryptor = AES.new(self.key, self.mode, '0000000000000000')
        length = 16
        count = len(text)
        if count < length:
            add = (length - count)
            text = text + (' ' * add)
        elif count > length:
            add = (length - (count % length))
            text = text + (' ' * add)

        ciphertext = cryptor.encrypt(text)
        return b2a_hex(ciphertext).decode()

    def decrypt(self, text):
        cryptor = AES.new(self.key, self.mode, "0000000000000000")
        plain_text = cryptor.decrypt(a2b_hex(text)).decode()
        return plain_text.strip(' ')


if __name__ == '__main__':
    p = Cryptography("abcdefghi1234567")
    # 加密操作
    encrypt = p.encrypt('zxcvbn')  # 8b9b89c1322e891919d84d6b17d2e411
    print(encrypt)
    # 解密操作
    decrypt = p.decrypt(encrypt)  # zxcvbn
    print(decrypt)

注意:

  • 加密文本text长度必须为16的倍数,不足时要补全16位,在解密时要把补全的字符去掉
  • 这里密钥key的长度必须为16(AES-128)、24(AES-192)、或32(AES-256)Bytes 长度.目前AES-128足够用

参考链接:http://www.cnblogs.com/kaituorensheng/p/4501128.html

posted @ 2018-03-16 11:28  Suraer  阅读(1422)  评论(0编辑  收藏  举报