· 7 years ago · Feb 19, 2018, 01:16 PM
1# -*- coding:utf-8 -*-
2import os
3from Crypto.Cipher import AES
4from Crypto import Random
5from binascii import b2a_hex,a2b_hex
6
7 # 生æˆåˆå§‹IVã€Keyã€plaintext
8SECRET_KEY = os.urandom(8).encode('hex').upper()
9IV = Random.new().read(16)
10plaintext = 'hello,Pegasus.X!'
11print plaintext
12
13 #进行AES CBC模å¼åР坆
14aes = AES.new(SECRET_KEY, AES.MODE_CBC, IV)
15length = 16
16count = len(plaintext)
17add = length - (count % length)
18plaintext = plaintext + ('\0' * add)#å¡«å……
19ciphertext = IV + aes.encrypt(plaintext)
20print b2a_hex(ciphertext)
21
22 # 这里,我们修改第10ä½ï¼ˆå·¦èµ·ç¬¬ä¸€ä¸º0ä½ï¼‰ä¸ºM
23ciphertext = list(ciphertext)
24ciphertext[10] = chr(ord(ciphertext[10]) ^ ord(plaintext[10]) ^ ord('M'))
25ciphertext = ''.join(ciphertext)
26print b2a_hex(ciphertext)
27
28 # 解密
29IV = ciphertext[:16]
30ciphertext = ciphertext[16:]
31aes = AES.new(SECRET_KEY, AES.MODE_CBC, IV)
32plaintext = aes.decrypt(ciphertext)
33plaintext = plaintext.rstrip('\0')
34print plaintext