概述
HackTheBox 网站CTF靶场密码学相关题目BabyEncryption,题目地址https://app.hackthebox.eu/challenges/babyencryption
题目
下载附件并解压,得到chall.py和msg.enc两个文件
chall.py的内容
import string
from secret import MSG
def encryption(msg):
ct = []
for char in msg:
ct.append((123 * char + 18) % 256)
return bytes(ct)
ct = encryption(MSG)
f = open('./msg.enc','w')
f.write(ct.hex())
f.close()
是一个加密过程的源代码
- 明文的每位乘以123加上18,求模得到密文
- 密文转为字节并16进制编码写入msg.enc文件
要想从密文得到明文,需要先得到123对256的逆元,可以手工使用辗转相除法或使用gmpy2的python库。
辗转相除法求逆元
则123模256的逆元为256-77=179
gmpy2求逆元
import gmpy2
print(gmpy2.invert(123,256))
解题代码
import gmpy2
plain = ""
d = gmpy2.invert(123,256)
cipher = open('./msg.enc','rb').read().decode('hex')
for c in cipher:
plain += chr((ord(c) - 18) * d % 256)
print(plain)