2021 XCTF Guesskey

Guess key

Download the attachment, is a piece of code, the analysis is as follows:

from random import randint
import os
from flag import flag
N=64
key=randint(0,2**N)  # 0到2的64次方中随机取一整数
print key
key=bin(key)[2:].rjust(N,'0')  # key取二进制,只取64位,左侧补0
count=0
while True:
	p=0
	q=0
	new_key=''
	zeros=[0]
	for j in range(len(key)):   
		if key[j]=='0':        #在key中筛选0
			zeros.append(j)    #如果有0,zeros列表就补上0的位置号,最大64,最小0
	p=zeros[randint(0,len(zeros))-1]    #在zeros列表中随机取一个字符串
	q=zeros[randint(0,len(zeros))-1]    #在zeros列表中随机取一个字符串
	try:
		mask=int(raw_input("mask:"))    #输入mask
	except:
		exit(0)
	mask=bin(mask)[2:]               # mask变成二进制
	if p>q:
		tmp=q
		q=p
		p=tmp          	#使p<q
	cnt=0
	for j in range(0,N):             # 在key中循环
		if j in range(p,q+1):        # 在p到q中循环
			new_key+=str(int(mask[cnt])^int(key[j]))    #如果j在p到q中,则newkey +=(mask中的值与key中的值异或)
		else:
			new_key+=key[j]          # 如果j不在p到q中,则直接将key赋值给newkey
		cnt+=1
		cnt%=len(mask)
	key=new_key
	try:
		guess=int(raw_input("guess:"))
	except:
		exit(0)
	if guess==int(key,2):
		count+=1
		print 'Nice.'
	else:
		count=0
		print 'Oops.'
	if count>2:
		print flag

In the following piece of code:

for j in range(0,N):             # 在key中循环
		if j in range(p,q+1):        # 在p到q中循环
			new_key+=str(int(mask[cnt])^int(key[j]))    #如果j在p到q中,则newkey +=(mask中的值与key中的值异或)
		else:
			new_key+=key[j]          # 如果j不在p到q中,则直接将key赋值给newkey

It is found that only when j is between p and q, the newkey will be different from the original key. And the transformation mechanism is determined by our input, so we have to control our input and minimize changes as much as possible.
It is found that when we make the mask "0", the newkey is consistent with the original key. Moreover, when I connect with nc, the original key will be fed back to us. In this way, we can get the flag.

Insert picture description here

Guess you like

Origin blog.csdn.net/Crazy198410/article/details/112851943