常见的只是ECB,CBC,其他一般用于掩饰(OFB,CTR),代码长,逻辑简单,但是很常出 ECB 基础知识: 明文分组同意密钥加密得到密文分组,特征就是若密文相同,则对应的明文也相同,AES-ECB一组长度16 ECB中间受难攻击 题干:
#使用 AES-256 ECB 模式,对一条消息 连续加密两次,使用两个密钥 k1 和 k2
#两把密钥都是 32 字节(256 bit)
#但题目给出简化条件:
#👉 密钥前 29 字节全为 0,只有最后 3 字节未知使用 AES-256 ECB 模式,对一条消息 连续加密两次,使用两个密钥 k1 和 k2
#两把密钥都是 32 字节(256 bit)
#双加密则是:C=Ek2(Ek1(M))
WP: 攻击:用所有可能的 key1 对 message1 加密 → 得到中间态 T1 用所有可能的 key2 对其第二阶段密文 decrypt → 得到中间态 T2 查询 T1=T2的时候的key1,key2 ,就是解 同时在学一下字典
from Crypto.Cipher import AES
ciphertext=input("输入密文:").encode()
key_lack=input("输入缺少的密钥:").encode()#encode()处理字符,bytes.处理字节(或它的ASCII数字)
search={}
def solve(ciphertext,cipher_lack):
for a in range(256):
for b in range(256):
for c in range(256):
guess1=bytes([a,b,c])#新的字符爆破方法(printable要的循环太多)
key1=(guess1+cipher_lack)
aes1=AES.new(key1,AES.MODE_ECB)
flag1=aes1.decrypt(ciphertext[:16])
search[flag1]=key1#字典的填充(表=里)
print("[+] 已生成 key1 字典,共", len(search), "项")
for e in range(256):
for f in range(256):
for g in range(256):
guess2=bytes([e,f,g])
key2=(guess2+cipher_lack)
aes2=AES.new(key2,AES.MODE_ECB)
flag2=aes2.encrypt(ciphertext[:16])
if flag2 in search:#找相同的表
key1_true = search[flag2]
key2_true = key2
tmp = AES.new(key2_true, AES.MODE_ECB).decrypt(ciphertext)
flag = AES.new(key1_true, AES.MODE_ECB).decrypt(tmp)
return flag
print(solve(ciphertext,cipher_lack))
ECB分块爆破 题干:
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad
from os import urandom,environ
import uuid
import signal
flag = environ.get('FLAG',f'0xGame{{{uuid.uuid4()}}}')
if __name__=='__main__':
signal.alarm(35) # Marblue awa
print(f'[+] Delightful infinite encryption-only orcale...')
key = urandom(16)
aes = AES.new(key,AES.MODE_ECB)
while input('[-] Continue encryption(y/[n])?') == 'y':
try:
msg = bytes.fromhex(input('[-] Plaintext(in hex):')) + flag.encode()
cp = aes.encrypt(pad(msg,16))
print(f'[+] Ciphertext: {cp.hex()}')
except:
break
WP: 题干:可以输入nonce,后面就是flag,自己选择加密信息,反馈结果 漏洞出在这个nonce上,可以卡分组的墙角 回顾AES.MODE_ECB:分组,一一加密,容易被攻击 我的处理是集中为块爆破,16一组,使用第一组,b’1’*15剩下的一个就是flag的第一字节 ,爆破,之后b’1’*14+known+爆破下一位,依此爆破(如果len(flag)>16,那改用别的吧) 之所以用这个是因为这个是我想出的,我叫他逼至墙角法 更细节的处理在脚本里面
from pwn import *
import string#爆破
addr="nc1.ctfplus.cn 114514".strip()
io=remote(addr[0],int(addr[1]))
#part1根据填充勘测跳跃得到len(flag)
lengths=[]
for i in range(0,48):
base_try='A'*i
io.recvuntil("[-] Continue encryption(y/[n])?")
io.sendline("y")
io.recvuntil("[-] Plaintext(in hex):")
io.sendline(try_key)
cipher_length=len(bytes.fromhex(io.recvline().strip()).decode())
lengths.append((i,cipher_length))
base_length=lengths[0][1]#获得基准长度:flag+padding
for j,length in lengths:
if(length>base_length):
#即发生突变,即加入后正好为16的倍数,padding突变
flag_length=(length-base_length)//16*16-i#处理成1块,减去i*‘A’,剩
#下的是flag的长度
#part2逐字符爆破
known=""
for pos in range(flag_length):
decrypted_index=15-pos%16
block_size=hex(b'A'*15)
io.recvuntil([-] Plaintext(in hex):)
io.sendline('y')
io.recvuntil([-] Plaintext(in hex):)
io.sendline(block_size)
target_block=bytes.fromhex(io.recvline(b":").decode().split()[1].strip()).decode('utf-8')
block_start=0*16
aim_block=target_block[block_start:block_start+16]#在第一块中逼至最后一位
for char in printable.string:
text_data=("A"*decrypted_index+char+known)
io.sendlineafter("[-] Continue encryption(y/[n])?","y")
io.sendlineafter("[-] Plaintext(in hex):",text_data)
text_get=io.recvline("f'[+] Ciphertext: {cp.hex()}'").decode().split(":").strip()
if(text_get[block_start:block_start+16]==aim_block[block_start:block_start+16]):
known+=char
break
print(known)
ECB重排攻击 重新排列组合,以达到混淆加密的效果 如:admin=0;username=pan 这里的加密块为8/块(DES——ECB):(admin=0; username =pan@@@@(填充到8) ) 这里我想要让我有admin,即admin=1 我们可以自己输入名字 输入pan@@@@admin=1;(即加密块为=pan@@@@ admin=1;) 后面一块单独加密,我们进入服务器面板得到后1块的加密结果覆盖admin=0 有个更简单的例子: 我直接用用户名替代密钥,这样我不需要知道密码也可以登录 CBC 先回顾CBC模式: 先是IV,IV与明文块1xor再加密得到密文块1,密文块1在与明文块2xor之后加密得到密文块2,循环 CBC结构操控 题干:
#!/usr/local/bin/python
from Crypto.Cipher import AES
from secret import flag
import os
from base64 import b64decode, b64encode
def encrypt():
plaintext = b64decode(input("Enter 48-byte plaintext in Base64: "))
assert len(plaintext) == 48, "Plaintext must be 48 bytes long."
cipher = AES.new(key, AES.MODE_CBC, IV)
ciphertext = cipher.encrypt(plaintext)
return ciphertext
MENU = """
This is a AES CBC encrypt machine (only for 48-byte plaintext XD).
To get flag, you need to make ciphertext like C-B-C, and make another ciphertext like C-C-B to get the flag.
0. Get IV
1. Encrypt
2. Get flag
"""
print(MENU)
key = os.urandom(16)
IV = os.urandom(16)
while True:
try:ab
choice = input("Your option: ")
if choice == '0':
print(f"IV in Base64: {b64encode(IV).decode()}")
elif choice == '1':
ciphertext = encrypt()
print(f"Ciphertext in Base64: {b64encode(ciphertext).decode()}")
elif choice == '2':
print("Make C-B-C ciphertext.")
ciphertext = encrypt()
C, B, C_ = ciphertext[:16], ciphertext[16:32], ciphertext[32:48]
if C == C_ and C != B:
print("Make C-C-B ciphertext.")
ciphertext = encrypt()
if ciphertext[:16] == ciphertext[16:32] == C and ciphertext[32:48] == B:
print("Congratulations! It's your flag!")
print(f"Flag: {flag}")
break
print("Invalid ciphertext format.")
else:
print("Invalid choice. Please try again.")
except Exception as e:
print(f"Error: {e}")
WP: 学习xor处理的思路 明白攻击模式,要的反推回去 如使c1=b1,就要使c1=b1 xor c0=b1=a1 xor b0 最好控制最后的输入,这样不会对前面的加密产生影响 即b1 xor c0=a1 xor b0最好控制c0,即c0=(a1 xor b0) xor b1
from pwn import *
import base64
addr="nc.ctfplus.cn 114541".spilt()
io=remote.(addr[0],int(addr[1]))
io.recvuntil("Your option: ")
io.sendline("0")
IV=base64.b64decode(io.recvuline().strip().encode())
io.recvuntil("plaintext in base64:")
io.sendline("1")
biao=base64.b64encode((b"1"*48).encode())
io.sendline(biao)
basic_text=base64.b64(io.recvline().strip().encode())#随便取一个模板
def xor(a,b):
return bytes([x^y for x,y in zip[a.b]])#逐字节对应
message1=b"1"*32+xor(basic_text[16:32],(IV xor b"1"*16))
message2=b"1"*16+(xorxor(basic_text[:16],b"1"*16),basic_text[:16])+b"1"*16
io.sendlineafter("Your option: ","2")
io.senflineafter("Make C-B-C ciphertext.",message1)
io.sendlineafter("Make C-C-B ciphertext.",message2)
print(io.recvline().strip())
io.interactive()
CBC位置控制 题干:
Good job!
####*####*####*####Game Start####*####*####*####
# '#' for conditions
# '@' for questions
####@####
# c1=aes_cbc_encode(password,iv,m1)
# c1.encode('base64')=cHtNHbeZs4hMvPY1I3U/H5Xw9dTAYiQbNxi6hhKpD8fG+9XHS1y3vurJv+8n/eJS30zwAyUB/hZx
+jrgTG6oYaUoxrlMnDhdtblJMiI0SXpUYkEFTzON+v5v0kKBtlY/7deS+nhRWlWm1AEfLLFx6N0z
q22s9F0r2/HDEGTEdsiLnogqVO/f7e/GtLO7Kl6e++GQnpaKasa2KFDCaocMj7V5LfEh/Nha6N9E
Y6zMelUIEpy56YeeZBYctJ+CT8jeNZ6lXNOEO+ZD0KNeh9xyB7++PDgwhoeumGiJIh3S+EgZ/y2U
0vgtJ0JC6/5v27Km3btyV/dDEIGhIvx9pe1wCA==
# m1.encode('base64')=UUxjWW9QRm1SYXhCWG9WdVhtU1JXemtza3dJR0V4ZkpDaVNMZWJ2dmVGaWhoQ0V4Slp2cHhLU2VT
WkdLck1YY1ZCZmZPYkRmdWltWUdaTWdCcHhzaVZhYVBhWmtrd0xTbmNmY3pzeGpVRUNab0lWYkh4
T1J2UHlRWXhlaFZqQnVWRkxHaVJDYk5FVGRxQUZjU0Vld0pRZkplZXZEUVpxc3JvUWx2WmFqVmZF
YmVVbXdnaExXWG5iSXRHTG1WeURxQldlQWJtZnZiUEhNWVBVa2RGdmtSRU5EbldYY3NqRHhiR2tr
b2hySHFKY3hyUENVV0tFRURBYVlCRkN3T3hvRw==
# m2=aes_cbc_decode(password,iv,c2)
# m2[31]=n
# m2[54]=E
# m2[82]=C
# m2[117]=A
# m2[145]=H
# m2[189]=c
# m2[216]=i
# m2[248]=t
WP: 如题上所述,要控制2,4等相间的block中的特定字符(即PN(INDEX)),我们只知道一组C,P part1:如何利用已知的C,P: 由CBC的解密可得:C0 XOR D(C1)=P1即D(C1)=P1 XOR C0,这时我们得到一个中间量S=D(C1) part2:控制特定位置: P(N)=C(N-1) XOR D(C(N)),我想通过S来控制C(N),即令C1=CN,同时解:D(C1)=D(CN) 即S=D(CN),带会得到P(N)=C(N-1) XOR S 加入INDEX控制,就是CN(INDEX)=PN(INDEX) XOR S(INDEX)
from pwn import *
import hashlib
import base64
import re
from collections import defaultdict
context.log_level = "info"
BLOCK_SIZE = 16
HOST = "47.107.168.16"
PORT = 42057
# ================== 工具函数 ==================
def xor_bytes(a: bytes, b: bytes) -> bytes:
return bytes(x ^ y for x, y in zip(a, b))
def solve_pow(prefix: str) -> bytes:
"""
题目:x = chr(rand(0,0xff)) + chr(rand(0,0xff)) + chr(rand(0,0x1f))
sha256(x).hexdigest()[0:8] == prefix
暴力枚举,返回 x(bytes,长度 3)
"""
log.info(f"[*] Solving PoW for prefix {prefix} ...")
target = prefix.lower()
for b0 in range(256):
for b1 in range(256):
for b2 in range(0x20): # 0x00 ~ 0x1f
x = bytes([b0, b1, b2])
h = hashlib.sha256(x).hexdigest()
if h.startswith(target):
log.success(f"Found x = {x.hex()} (sha256={h})")
return x
raise RuntimeError("No PoW solution found (should not happen).")
def build_c2(c1_b64: str, m1_b64: str, constraints):
"""
根据已知的 c1, m1 和 m2 的若干位置约束自动构造 c2。
constraints: [(index, char), ...] 例如 [(31,'n'), (54,'E'), ...]
返回: (c2_bytes, c2_base64_str)
"""
c1 = base64.b64decode(c1_b64)
m1 = base64.b64decode(m1_b64)
assert len(c1) == len(m1), "c1 和 m1 长度不一致,检查一下题目数据"
assert len(c1) % BLOCK_SIZE == 0, "长度不是 16 的倍数?"
nblocks = len(c1) // BLOCK_SIZE
C1 = [c1[i*BLOCK_SIZE:(i+1)*BLOCK_SIZE] for i in range(nblocks)]
P1 = [m1[i*BLOCK_SIZE:(i+1)*BLOCK_SIZE] for i in range(nblocks)]
# 选 C1[1] 作为参考块:S = D(C1[1]) = P1[1] XOR C1[0]
src_block_index = 1
assert nblocks > 1, "至少需要两个块才行"
S = xor_bytes(P1[src_block_index], C1[src_block_index - 1])
src_cipher_block = C1[src_block_index]
# 把约束按块分组:block_index -> [(offset, ord(ch)), ...]
by_block = defaultdict(list)
for pos, ch in constraints:
if pos < BLOCK_SIZE:
raise ValueError(
f"题目在第 0 块位置 {pos} 上给了约束,目前构造没处理第 0 块"
)
block_idx = pos // BLOCK_SIZE
offset = pos % BLOCK_SIZE
by_block[block_idx].append((offset, ord(ch)))
if not by_block:
raise ValueError("没有任何约束?")
max_block = max(by_block.keys())
num_blocks2 = max_block + 1 # 0-based
# 检查是否存在连续的约束块(例:3 和 4 同时有约束,会冲突)
constrained_blocks = sorted(by_block.keys())
for i in range(len(constrained_blocks) - 1):
if constrained_blocks[i] + 1 == constrained_blocks[i + 1]:
raise ValueError(
f"连续约束块 {constrained_blocks[i]} 和 {constrained_blocks[i+1]},"
"当前构造策略会冲突,需要手动改算法。"
)
# 初始化 C2,全 0
C2 = [bytearray(BLOCK_SIZE) for _ in range(num_blocks2)]
# 所有有约束的块,都设置为 src_cipher_block
for b in constrained_blocks:
C2[b][:] = src_cipher_block
# 根据每个受约束块,反推出"前一块"的对应字节
for b, items in by_block.items():
if b == 0:
raise ValueError("不应该出现 b == 0 的约束(前面已经检查过)")
prev_b = b - 1
for offset, ch_ord in items:
# P2[b][offset] = ch_ord
# P2[b] = S XOR C2[prev_b]
# => C2[prev_b][offset] = S[offset] XOR ch_ord
need = S[offset] ^ ch_ord
if C2[prev_b][offset] != 0 and C2[prev_b][offset] != need:
raise ValueError(
f"冲突:块 {prev_b} 偏移 {offset} 之前已为 "
f"{C2[prev_b][offset]}, 现在需要 {need}"
)
C2[prev_b][offset] = need
c2 = b"".join(bytes(block) for block in C2)
c2_b64 = base64.b64encode(c2).decode()
return c2, c2_b64
def parse_and_solve_round(text):
"""
从一轮题目文本中解析 c1, m1, 约束,并构造 c2
返回: (c2_bytes, c2_b64) 或 None(解析失败)
"""
# 解析 c1
m_c1 = re.search(
r"c1\.encode\('base64'\)=([A-Za-z0-9+/=\s]+?)#\s*m1\.encode\('base64'\)=",
text, re.S
)
if not m_c1:
return None
c1_b64_raw = m_c1.group(1).strip().replace("\n", "").replace("\r", "").replace(" ", "")
# 解析 m1
m_m1 = re.search(
r"m1\.encode\('base64'\)=([A-Za-z0-9+/=\s]+?)#\s*m2=",
text, re.S
)
if not m_m1:
return None
m1_b64_raw = m_m1.group(1).strip().replace("\n", "").replace("\r", "").replace(" ", "")
# 解析约束 m2[xxx]=c
constraints = []
for idx, ch in re.findall(r"m2\[(\d+)\]=(.)", text):
pos = int(idx)
constraints.append((pos, ch))
if not constraints:
return None
log.info(f"c1_b64 length = {len(c1_b64_raw)}")
log.info(f"m1_b64 length = {len(m1_b64_raw)}")
log.info(f"Parsed constraints: {constraints}")
try:
c2_bytes, c2_b64 = build_c2(c1_b64_raw, m1_b64_raw, constraints)
return c2_bytes, c2_b64
except Exception as e:
log.error(f"build_c2 failed: {e}")
return None
# ================== 主攻击逻辑 ==================
def main():
io = remote(HOST, PORT)
# ---------- 1. 读取 PoW 提示,解析前缀 ----------
data = io.recvuntil(b"x.encode('hex')=")
text = data.decode(errors="ignore")
log.info("PoW banner:\n" + text)
m = re.search(r"hexdigest\(\)\[0:8\]=='([0-9a-fA-F]{8})'", text)
if not m:
log.error("无法从题面解析出 PoW 前缀")
return
prefix = m.group(1)
x = solve_pow(prefix)
# 发送 x.encode('hex')
io.sendline(x.hex().encode())
round_num = 0
accumulated_text = ""
while True:
round_num += 1
log.info(f"========== Round {round_num} ==========")
# 读取本轮题目,直到出现 @c2.encode('base64')=
try:
data = io.recvuntil(b"@c2.encode('base64')=", timeout=10)
text = data.decode(errors="ignore")
log.info(f"Round {round_num} text:\n{text}")
except EOFError:
log.warning("EOF received, checking for flag...")
break
except Exception as e:
log.warning(f"Exception while receiving: {e}")
break
# 解析并构造 c2
result = parse_and_solve_round(text)
if result is None:
log.error("Failed to parse round, trying interactive...")
io.interactive()
return
c2_bytes, c2_b64 = result
log.success(f"Sending c2 (base64): {c2_b64[:80]}... (len={len(c2_b64)})")
io.sendline(c2_b64.encode())
# 读取响应,检查是否成功
try:
response = io.recvuntil(b"Good job!", timeout=5)
log.success(f"Round {round_num} passed!")
except:
# 可能是最后一轮或者出错了
log.info("No 'Good job!' received, checking remaining output...")
try:
remaining = io.recv(timeout=2)
log.info(f"Remaining data: {remaining.decode(errors='ignore')}")
if b"flag" in remaining.lower() or b"FLAG" in remaining or b"{" in remaining:
log.success(f"Possible flag found!")
except:
pass
break
# 最后尝试获取所有剩余输出
try:
io.settimeout(3)
final = io.recvall(timeout=3)
log.info(f"Final output: {final.decode(errors='ignore')}")
except:
pass
io.interactive()
if __name__ == "__main__":
main()