RSAPublic-Key Encryption and Signature Lab
1.推导RSA私钥
import gmpy2
p = 0xF7E75FDC469067FFDC4E847C51F452DF
q = 0xE85CED54AF57E53E092113E62F436F4F
e = 0x0D88C3
n = q * p
phi = (p - 1) * (q - 1)
d = gmpy2.invert(e, phi)
print("public key:(" + hex(e) + ',' + hex(n) + ")")
print("private key:" + hex(d))
2.用RSA加密一个消息
import gmpy2
n = 0xDCBFFE3E51F62E09CE7032E2677A78946A849DC4CDDE3A4D0CB81629242FB1A5
e = 0x010001
m = "A top secret!".encode("utf-8").hex()
m = int(m, 16)
c = gmpy2.powmod(m, e, n)
print(hex(c))
3.解密这个消息
C = 8C0F971DF2F3672B28811407E2DABBE1DA0FEBBBDFC7DCB67396567EA1E2493F
import gmpy2
n = 0xDCBFFE3E51F62E09CE7032E2677A78946A849DC4CDDE3A4D0CB81629242FB1A5
d = 0x74D806F9F3A62BAE331FFE3F0A68AFE35B3D2E4794148AACBC26AA381CD7D30D
C = 0x8C0F971DF2F3672B28811407E2DABBE1DA0FEBBBDFC7DCB67396567EA1E2493F
M = gmpy2.powmod(C, d, n)
m = str(hex(M))[2:]
print("M:" + bytes.fromhex(m).decode("utf-8"))
4.产生一个消息的数字签名
import gmpy2
n = 0xDCBFFE3E51F62E09CE7032E2677A78946A849DC4CDDE3A4D0CB81629242FB1A5
e = 0x010001
d = 0x74D806F9F3A62BAE331FFE3F0A68AFE35B3D2E4794148AACBC26AA381CD7D30D
msg = ["I owe you $2000", "I owe you $3000"]
for m in msg:
print(m)
m = int(m.encode("utf-8").hex(), 16)
c = gmpy2.powmod(m, d, n)
print(hex(c))
5.验证这个数字签名是否正确
import gmpy2
M = "Launch a missile."
Sorg = 0x643D6F34902D9C7EC90CB0B2BCA36C47FA37165C0005CAB026C0542CBDB6802F
Serr = 0x643D6F34902D9C7EC90CB0B2BCA36C47FA37165C0005CAB026C0542CBDB6802A
n = 0xAE1CD4DC432798D933779FBD46C6E1247F0CF1233595113AA51B450F18116115
e = 0x010001
sig = [Sorg, Serr]
for S in sig:
m = gmpy2.powmod(S, e, n)
m = str(hex(m))[2:]
try:
msg = bytes.fromhex(m).decode('utf-8')
print(msg)
if m == M:
print("signature valid!")
else:
print("signature invalid!")
except:
print(bytes.fromhex(m))
print("signature invalid!")
标签:powmod,gmpy2,RSAPublic,Encryption,hex,Lab,print,import
From: https://www.cnblogs.com/hjdssj/p/18655176