我想用z3解决这种情况。输入的是10个字符串。输入的每个字符都是可打印字符(ASCII)。输入应为当以输入为参数调用calc2()函数时,结果应为:0x0009E38E1FB7629B。
在这种情况下如何使用z3py?
通常,我只是将独立方程式添加为z3的约束。在这种情况下,我不确定如何使用z3。
def calc2(input):
result = 0
for i in range(len(input)):
r1 = (result << 0x5) & 0xffffffffffffffff
r2 = result >> 0x1b
r3 = (r1 ^ r2)
result = (r3 ^ ord(input[i]))
return result
if __name__ == "__main__":
input = sys.argv[1]
result = calc2(input)
if result == 0x0009E38E1FB7629B:
print "solved"
更新:我尝试了以下操作,但它没有给我正确的答案:
from z3 import *
def calc2(input):
result = 0
for i in range(len(input)):
r1 = (result << 0x5) & 0xffffffffffffffff
r2 = result >> 0x1b
r3 = (r1 ^ r2)
result = r3 ^ Concat(BitVec(0, 56), input[i])
return result
if __name__ == "__main__":
s = Solver()
X = [BitVec('x' + str(i), 8) for i in range(10)]
s.add(calc2(X) == 0x0009E38E1FB7629B)
if s.check() == sat:
print(s.model())
答案 0 :(得分:1)
我希望这不是家庭作业,但这是解决问题的一种方法:
from z3 import *
s = Solver()
# Input is 10 character long; represent with 10 8-bit symbolic variables
input = [BitVec("input%s" % i, 8) for i in range(10)]
# Make sure each character is printable ASCII, i.e., between 0x20 and 0x7E
for i in range(10):
s.add(input[i] >= 0x20)
s.add(input[i] <= 0x7E)
def calc2(input):
# result is a 64-bit value
result = BitVecVal(0, 64)
for i in range(len(input)):
# NB. We don't actually need to mask with 0xffffffffffffffff
# Since we explicitly have a 64-bit value in result.
# But it doesn't hurt to mask it, so we do it here.
r1 = (result << 0x5) & 0xffffffffffffffff
r2 = result >> 0x1b
r3 = r1 ^ r2
# We need to zero-extend to match sizes
result = r3 ^ ZeroExt(56, input[i])
return result
# Assert the required equality
s.add(calc2(input) == 0x0009E38E1FB7629B)
# Check and get model
print s.check()
m = s.model()
# reconstruct the string:
s = ''.join([chr (m[input[i]].as_long()) for i in range(10)])
print s
此打印:
$ python a.py
sat
L`p:LxlBVU
好像您的秘密字符串是
“ L`p:LxlBVU”
我在程序中添加了一些注释,以帮助您了解如何在z3py中进行编码,但是请随时进行澄清。希望这会有所帮助!
要获取其他解决方案,只需循环并断言该解决方案不应为前一个解决方案。断言后可以使用以下while
循环:
while s.check() == sat:
m = s.model()
print ''.join([chr (m[input[i]].as_long()) for i in range(10)])
s.add(Or([input[i] != m[input[i]] for i in range(10)]))
当我运行它时,它一直在运行!您可能要过一会儿才能停止它。
答案 1 :(得分:0)
您可以在Z3中编码calc2。您需要将循环展开1,2,3,4,..,n次(因为n =预期的最大输入大小),仅此而已。 (您实际上不需要展开循环,可以使用z3py创建约束)