# Simple algorithm实验吧

http://www.shiyanbar.com/ctf/737
simple algorithm:
The flag is encrypted by this code, can you decrypt it after finding the system?

#!/usr/bin/python
#>>>> "hello".encode('hex')
#LookupError: 'hex' is not a text encoding; use codecs.encode() to handle arbitrary codecs
#>>>> import codecs
#>>>> codecs.encode(b"hello", 'hex')
#b'68656c6c6f'
import codecs
flag = b'[censored]'
hflag = codecs.encode(flag,'hex')
iflag = int(hflag[2:], 16)#取hflag第二位以后16进制转10进制

def FAN(n, m):
i = 0
z = []
s = 0
while n > 0:
if n % 2 != 0:
z.append(2 - (n % 4))#0，1，2，3=>2,1,0,1
else:
z.append(0)
n = (n - z[i])/2
#print('n :'+str(n))
i = i + 1
z = z[::-1]#将整个tuple倒置你可以单独试试
l = len(z)
#print('l: '+str(l))
for i in range(0, l):
#2**3代表2的立方
s += z[i] * m ** (l - 1 - i)#不知道单独测测s最后就是一个数
return s

if __name__=='__main__':
i = 0
r = ''
while i < len(str(iflag)):
d = str(iflag)[i:i+2]
nf = FAN(int(d),3)
r += str(nf)
i += 2

print(r)

84.0244.0658.0730.0739.0645.0651.072.0242.0657.0235.0其实这是。
84.0 244.0 658.0 730.0 739.0 645.0 651.0 72.0 242.0 657.0 235.0。可以看出最大不超过
4位数。

#先从4个字符匹配直至1个字符
#python中s[i:i+2]不一定取到2个字符，
#如s="pcat",s[3:4]和s[3:5],甚至s[3:100]都是"t"
#此题中最后得到"09"，但也可能是"9"，故做下面的判断

import codecs

def FAN(n, m):
i = 0
z = []
s = 0
while n > 0:
if n % 2 != 0:
z.append(2 - (n % 4))
else:
z.append(0)
n = (n - z[i])/2
i = i + 1
z = z[::-1]
l = len(z)
for i in range(0, l):
s += z[i] * m ** (l - 1 - i)
return s

dic={} #字典
for k in range(0,100):
dic[FAN(kk, 3)]=kk
ff=open('C:/Users/zhoug_000/Desktop/enc.txt','r')
print(miwen)
str1=''
jj=0
while jj<len(miwen):
if int(miwen[jj:jj+4]) in dic:
str1+='%d'%(dic[int(miwen[jj:jj+4])])
jj+=4
elif int(miwen[jj:jj+3]) in dic:
str1+='%02d'%(dic[int(miwen[jj:jj+3])])
jj+=3
elif int(miwen[jj:jj+2]) in dic:
str1+='%02d'%(dic[int(miwen[jj:jj+2])])
jj+=2
elif int(miwen[jj:jj+1]) in dic:
str1+='%02d'%(dic[int(miwen[jj:jj+1])])
jj+=1
print(str1)
str2='%x'%(int(str1))
#最后注意bytes与string的转换
print('结果为： '+codecs.decode(str2,'hex').decode('ascii'))

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120