简易的16进制大数模计算器:用于密码学计算
import binascii
import struct
def extendGcd(a, m):
if a < m:
a, m = m, a
x1, x2, x3 = 1, 0, a
y1, y2, y3 = 0, 1, m
while y3 != 0:
Q = x3 // y3
t1, t2, t3 = x1 - Q * y1, x2 - Q * y2, x3 - Q * y3
x1, x2, x3 = y1, y2, y3
y1, y2, y3 = t1, t2, t3
return x2
else:
x1, x2, x3 = 1, 0, a
y1, y2, y3 = 0, 1, m
while y3 != 0:
Q = x3 // y3
t1, t2, t3 = x1 - Q * y1, x2 - Q * y2, x3 - Q * y3
x1, x2, x3 = y1, y2, y3
y1, y2, y3 = t1, t2, t3
return x1
def str2int(strin):
in10t = int(strin, 16)
return in10t
def lcm(x, y):
m = max(x, y)
n = min(x, y)
while m % n:
m, n = n, m % n
return x * y // n
def main():
while 1:
print(
"【=====Calc 2.0 ————>>> 用于大数模计算=====】".center(45), "\n!【==输入的数据需要是16进制==】\n操作有以下四种:\n |① “+”\n |② "
"“-”\n |③ “*”\n |④ “-1” ("
"求对象与模m的乘法逆元)\n------------------------------------------------------------------------------\n"
"【SM2"
"默认模数为:FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123】\n请输入模数m(64位16进制数):(默认SM2模数按g/G)",
end='')
mod = input()
if mod == "g" or "G":
mod = str2int("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123")
else:
mod = str2int(mod)
print("模数为:", mod)
print("键入第一个数a:", end='')
num_a = input()
num_1 = str2int(num_a)
print("键入操作:", end='')
opration = input()
if opration == "+":
print("输入加数b:", end='')
num_b = input()
num_2 = str2int(num_b)
sum = hex((num_1 + num_2) % mod)
print("模加结果是:", sum)
if opration == "-":
print("输入减数b:", end='')
num_b = input()
num_2 = str2int(num_b)
sub = hex((num_1 - num_2) % mod)
print("模减结果是:", sub)
if opration == "*":
print("输入减数b:", end='')
num_b = input()
num_2 = str2int(num_b)
mut = hex((num_1 * num_2) % mod)
print("模乘结果是:", mut)
if opration == "-1":
divV = extendGcd(num_1, mod)
if divV < 0:
divv = hex((lcm(num_1, mod) + divV * num_1) // num_1)
print("模乘结果是:", divv)
else:
print("模乘结果是:", hex(divV))
else:
print("【==================已回到初始选单==============】")
print("============================这是单次运算分隔符=================================")
print("============================================================================")
print("\n")
if __name__ == '__main__':
main()
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/09d04caabd525ea510892f443a1a692f.png)