1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| from Crypto.PublicKey import ElGamal from Crypto.Random import get_random_bytes, random from Crypto.Util.number import * from random import * from secret import flag
def generate_elgamal_keypair(bits=512): p = getPrime(bits)
for _ in range(1000): g = getRandomRange(2, 5) if pow(g, (p - 1) // 2, p) != 1: break
x = randrange(2, p - 1) y = pow(g, x, p)
return p, g, y, x
# 生成密钥对 key = generate_elgamal_keypair(bits=512) p, g, y, x = key
print("=== 公钥 (p, g, y) ===") print("p =", p) print("g =", g) print("y =", y) print()
# 加密 k = randrange(1, p - 2) m = bytes_to_long(flag) c1 = pow(g, k, p) c2 = (m * pow(y, k, p)) % p
print("=== 密文 (c1, c2) ===") print("c1 =", c1) print("c2 =", c2)
# 不小心泄露了私钥 print("x =", x)
''' p =11540963715962144951763578255357417528966715904849014985547597657698304891044841099894993117258279094910424033273299863589407477091830213468539451196239863 g = 2 y =8313424783366011287014623582773521595333285291380540689467073212212931648415580065207081449784135835711205324186662482526357834042013400765421925274271853 === 密文 (c1, c2) === c1 =6652053553055645358275362259554856525976931841318251152940464543175108560132949610916012490837970851191204144757409335011811874896056430105292534244732863 c2 =2314913568081526428247981719100952331444938852399031826635475971947484663418362533363591441216570597417789120470703548843342170567039399830377459228297983 x =8010957078086554284020959664124784479610913596560035011951143269559761229114027738791440961864150225798049120582540951874956255115884539333966429021004214 '''
|