春节红包第三题解题记录
分析在前辈的帖子里https://www.52pojie.cn/thread-873265-1-1.html,我用python解了一下,需安装pycrypto库#!/usr/bin/python
#-*- coding:utf-8-*-
from Crypto.Cipher import AES
#from binascii import b2a_hex,a2b_hex
import base64,binascii,re,hashlib
class AESCBC:
def __init__(self, key):
self.key = key
self.mode = AES.MODE_CBC
self.bs = 16# block size
self.PADDING = lambda s: s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)
def encrypt(self, text):
generator = AES.new(self.key, self.mode,self.key)
try:
crypt = generator.encrypt(self.PADDING(text))
crypted_str = base64.b64encode(crypt)
result = crypted_str.decode()
except Exception:
result = '加密失败,请确认输入是否有误!'
return result
def decrypt(self, text):
generator = AES.new(self.key, self.mode,self.key)
text += (len(text) % 4) * '='
try:
decrpyt_bytes = base64.b64decode(text)
meg = generator.decrypt(decrpyt_bytes)
# 去除解码后的非法字符
result = re.compile('[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f\n\r\t]').sub('', meg.decode())
except Exception:
result = '解密失败,请确认输入是否有误!'
return result
def main():
name = input("input uid:")
sha1 = hashlib.sha1()
sha1.update(name.encode('utf8'))
#key = binascii.a2b_hex('8380cf291d73c51efb5351d7df0268cb89be530e'[:32])#秘钥的长度必须为16
key = binascii.a2b_hex(sha1.hexdigest()[:32])
result = 'HappyNewYearFrom52PoJie.Cn'
cryptor = AESCBC(key)#这里选用的是CBC模式
plainText = cryptor.encrypt(result)#解密函数
print((plainText))
if __name__=="__main__":
main()
这段加密、解密的示例代码很有用 本帖最后由 whyida 于 2020-3-24 21:27 编辑
楼主的代码运行不了,自己写了一段代码。
#python2.7
from Crypto.Util.Padding import pad, unpad
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
import base64
import base64,binascii,re,hashlib
data = '483032'
shab1 = hashlib.sha1()
shab1.update(bytes(data.encode('utf-8')))
key = binascii.a2b_hex(shab1.hexdigest()[:32])
result = 'HappyNewYearFrom52PoJie.Cn'
iv = key
cipher1 = AES.new(key, AES.MODE_CBC,iv)
ct = cipher1.encrypt(pad(result, AES.block_size))
ct1 = base64.b64encode(ct)
cipher2 = AES.new(key, AES.MODE_CBC)
print(ct1)
页:
[1]