Skip to content

Instantly share code, notes, and snippets.

@omsobliga
Last active March 21, 2018 06:26
Show Gist options
  • Save omsobliga/e87c174d34413c7ae01e8a34eec7bac0 to your computer and use it in GitHub Desktop.
Save omsobliga/e87c174d34413c7ae01e8a34eec7bac0 to your computer and use it in GitHub Desktop.
对称加密 AES
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 参考资料:
# * https://en.wikipedia.org/wiki/Advanced_Encryption_Standard
# * https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation
#
# Show AES document:
# > from Crypto.Cipher import AES
# > help(AES)
from Crypto import Random
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
KEY_SIZE = 16
def generate_key(key_size=KEY_SIZE):
""" 生成随机密钥,默认长度为 128 bits
"""
return Random.new().read(key_size)
def encrypt(key, plaintext):
iv = Random.new().read(AES.block_size)
cipher = AES.new(key, AES.MODE_CFB, iv)
return iv + cipher.encrypt(plaintext)
def decrypt(key, ciphertext):
iv = ciphertext[:16]
cipher = AES.new(key, AES.MODE_CFB, iv)
return cipher.decrypt(ciphertext[16:])
if __name__ == '__main__':
key = generate_key()
plaintext = u'abc'
ciphertext = encrypt(key, plaintext)
plaintext = decrypt(key, ciphertext)
print plaintext
print ciphertext
# 计算出来的 ciphertext 是二进制,输出可转化成十六进制
print b2a_hex(ciphertext)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment