def sign(msg): m = bytes_to_long(msg) s = pow(m, d, n) return long_to_bytes(s)
def verify(s): s = bytes_to_long(s) v = pow(s, e, n) return long_to_bytes(v)
def welcome(): print("\nWelcome to command signer/executor.") print("Menu : 1. Verify and run a command") print(" 2. Sign a command") print(" 3. Exit")
while True: welcome() sel = input(" > ").strip() if sel == "1": sgn = input("Signed command: ").strip() sgn = b64decode(sgn) cmd = verify(sgn)
commands = ["ls -l", "pwd", "id", "cat flag"] if cmd.decode() in commands: system(cmd) else: print("Possible commands: ", commands)
elif sel == "2": cmd = input("Base64 encoded command to sign: ") cmd = b64decode(cmd) if cmd == "cat flag": print("It's forbidden.") else: print("Signed command:", b64encode(sign(cmd)).decode())
elif sel == "3": print("bye.") exit()
else: print("Invalid selection.")
我对代码的理解是:
1、引用了base64,crypto.util.number,os这三个库
2、随机生成两个512比特的大素数p和q,因此n的值随着每次运行而变化
3、定义了函数名为sign的函数,msg为参数,在函数体中m是把参数msg从bytes(字节串,以二进制存储)转为long整型,s=m^d^ mod n,返回的是s的bytes型,而v=s^e^ mod n,返回的也是v的bytes型。
n=0xbefe9a8bb0f6af7ea24a58eb2fc349749cb88cf1f27181f2125e387eed8eca9550c81b3f292dfdf0fabad04bbfa83195ea9c48b7d7d8eded8783b8a00b7310d4642cf34b5944acb259df89c3b2069168aa4a064c8cacfb521ddee9f261c579b1ab15762ebc8a34bd6e26e17289bcf8e8201b2bb54cfb9ec7a6b2e3cfcc0606a7 e = 0x10001 c=(m1*m2)%n c=long_to_bytes(c) c = b64encode(c) print(c)