python的Crypto模块实现AES加密实例代码

yipeiwu_com6年前Python基础

本文主要探索的是python的Crypto模块实现AES加密,分享了具体实现代码,下面看看具体内容。

学了使用Crypto模块的AES来加密文件,现在记录下来便于后边儿查看。

在刚开始知道这个模块的时候,连基本的Crypto模块的安装都花了很多很多时间来搞,也不知道什么情况反正是折腾很久了才安装起的,记得是包安装起来了,但使用的时候始终提示找不到Crypto.Cipher模块。然后怎么解决的呢?

一、把我的python换成了64位的,本来电脑就是64位的也不知道之前是啥情况安装成32位的了。(O(∩_∩)O哈哈~)
二、安装了VCForPython27.msi
三、在cmd中执行:

pip install pycrypto -i http://mirrors.aliyun.com/pypi/simple/

经过上边儿的几个步骤,我是能够成功执行

from Crypto.Cipher import AES

现在上一个实例代码:

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

'''

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

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

  def myencrypt(self, text):
    length = 16
    count = len(text)
    print count
    if count < length:
      add = length - count
      text= text + ('\0' * add)

    elif count > length:
      add = (length -(count % length))
      text= text + ('\0' * add)

    # print len(text)
    cryptor = AES.new(self.key, self.mode, b'0000000000000000')
    self.ciphertext = cryptor.encrypt(text)
    return b2a_hex(self.ciphertext)

  def mydecrypt(self, text):
    cryptor = AES.new(self.key, self.mode, b'0000000000000000')
    plain_text = cryptor.decrypt(a2b_hex(text))
    return plain_text.rstrip('\0')

if __name__ == '__main__':
  mycrypt = MyCrypt('abcdefghjklmnopq')
  e = mycrypt.myencrypt('hello,world!')
  d = mycrypt.mydecrypt(e)
  print e
  print d

在cmd中执行结果:

总结

以上就是本文关于python的Crypto模块实现AES加密实例代码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

相关文章

python3连接kafka模块pykafka生产者简单封装代码

1.1安装模块 pip install pykafka 1.2基本使用 # -* coding:utf8 *- from pykafka import KafkaClient...

对Python正则匹配IP、Url、Mail的方法详解

如下所示: """ Created on Thu Nov 10 14:07:36 2016 @author: qianzhewoniuqusanbu """ import re...

pandas系列之DataFrame 行列数据筛选实例

pandas系列之DataFrame 行列数据筛选实例

一、对DataFrame的认知 DataFrame的本质是行(index)列(column)索引+多列数据。 为了简化理解,我们不妨换个思路… 现实中,为了简化对一件事物的描述,我们会...

Python socket模块实现的udp通信功能示例

本文实例讲述了Python socket模块实现的udp通信功能。分享给大家供大家参考,具体如下: socket介绍 socket(简称 套接字) 是进程间通信的一种方式,它与其他进程间...

Python3基础之list列表实例解析

通常来说Python中任何值都是一个对象,因此任何类型(int、str、list…)都是一个类。而类就必然有它的方法或属性,我们要记下这么多类的所有方法显然是不可能的,对此本文介绍两个小...