zoukankan      html  css  js  c++  java
  • python AES 加密

    pad: ZeroPadding

    mode: cbc

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    # 这里使用pycrypto‎库
    # 按照方法:easy_install pycrypto‎

    from Crypto.Cipher import AES
    import base64


    class prpcrypt():

    def __init__(self, key, iv):
    self.key = key
    self.mode = AES.MODE_CBC
    self.iv = iv

    # 加密函数,如果text不足16位就用空格补足为16位,
    # 如果大于16当时不是16的倍数,那就补足为16的倍数。
    def encrypt(self, text):
    cryptor = AES.new('123454536f667445454d537973576562',
    self.mode, IV=self.iv)
    # 这里密钥key 长度必须为16(AES-128),
    # 24(AES-192),或者32 (AES-256)Bytes 长度
    # 目前AES-128 足够目前使用
    length = 16
    count = len(text)
    if count < length:
    add = (length - count)
    # backspace
    text = text + ('' * add)
    elif count > length:
    add = (length - (count % length))
    text = text + ('' * add)
    self.ciphertext = cryptor.encrypt(text)
    # 因为AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题
    # 所以这里统一把加密后的字符串转化为16进制字符串
    return base64.b64encode(self.ciphertext)

    # 解密后,去掉补足的空格用strip() 去掉
    def decrypt(self, text):
    cryptor = AES.new(self.key, self.mode, IV=self.iv)
    plain_text = cryptor.decrypt(base64.b64decode(text))
    return plain_text.rstrip('')


    if __name__ == '__main__':
    pc = prpcrypt('123454536f667445454d537973576562',
    '1234577290ABCDEF1264147890ACAE45'[0:16]) # 初始化密钥

    e = pc.encrypt('T10515') # 加密
    print "加密:", e

    d = pc.decrypt(e) # 解密
    print "解密:", d

    AES:

    pad pkcs7

    mode cbc

    # -*- coding: utf-8 -*-
    from Crypto.Cipher import AES
    import base64
    import os

    BS = AES.block_size
    pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
    unpad = lambda s: s[0:-ord(s[-1])]

    key = os.urandom(16) # the length can be (16, 24, 32)
    text = '123456'

    cipher = AES.new(key)
    cipher = AES.new('33b21adee1b8620a7ba81aea1a80c724',
    AES.MODE_CBC, IV='1234567812345678')

    encrypted = cipher.encrypt(pad(text))
    encrypted = base64.b64encode(encrypted)
    print encrypted # will be something like 'f456a6b0e54e35f2711a9fa078a76d16'

  • 相关阅读:
    spark 安装
    maven 常用配置
    矩阵SVD在机器学习中的应用
    机器学习—单变量线性回归
    Stanford机器学习
    Memcached 安装和客户端配置
    Lucene 学习之二:数值类型的索引和范围查询分析
    Go-errors第三方包学习
    Go日志库使用-logrus
    Go语言---小白入门-命令行库Cobra的使用
  • 原文地址:https://www.cnblogs.com/skying555/p/6344718.html
Copyright © 2011-2022 走看看