from Crypto.Util.number import getPrime
from Crypto.Util.Padding import pad, unpad
from Crypto.Cipher import AES
import hashlib
import random
class Person(object):
def __init__(self, p):
self.p = p
self.g = 2
self.x = random.randint(2, self.p - 1)
def calc_key(self):
self.k = pow(self.g, self.x, self.p)
return self.k
def set_shared_key(self, k):
self.sk = pow(k, self.x, self.p)
print("sk : ",self.sk)
aes_key = hashlib.md5(str(self.sk).encode()).digest()
self.cipher = AES.new(aes_key, AES.MODE_ECB)
def encrypt(self, pt):
return self.cipher.encrypt(pad(pt, 16)).hex()
def decrypt(self, ct):
return unpad(self.cipher.decrypt(bytes.fromhex(ct)), 16)
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True
def primitive_root(p):
if p == 2:
return 1
p1 = 2
p2 = (p-1) // p1
while(p2 % p1 == 0):
p1 *= 2
p2 = (p-1) // p1
g = pow(2, p2, p)
while (pow(g, (p-1)//2, p) == 1):
g = pow(g, 2, p)
return g
flag = open("flag.txt", "r").read().encode()
prime = 16683502042145070731
print(f'prime : {prime}')
#exit()
alice = Person(prime)
bob = Person(prime)
alice_k = alice.calc_key()
print(f"Alice sends her key to Bob. Key: {alice_k}")
if alice_k == alice.g:
exit("Malicious key !!")
bob.set_shared_key(alice_k)
bob_k = bob.calc_key()
print(f"Bob sends his key to Alice. Key: {bob_k}")
if bob_k == bob.g:
exit("Malicious key !!")
alice.set_shared_key(bob_k)
print("They are sharing the part of flag")
print(f"Alice: {alice.encrypt(flag[:len(flag) // 2])}")
print(f"Bob: {bob.encrypt(flag[len(flag) // 2:])}")
공유키를 알려주고 있어서 해당 키 값으로 디크립트하면 됩니다.
$ nc goatwar.xyz 11000
prime : 16683502042145070731
Alice sends her key to Bob. Key: 4015290253982335710
sk : 9165507793789697032
Bob sends his key to Alice. Key: 4929127157915240762
sk : 9165507793789697032
They are sharing the part of flag
Alice: e479a9dcb605f253c39332a04ce5f726
Bob: 2e38b3ee0ec957aa62bdabd9e6b4ea42
from Crypto.Util.number import getPrime
from Crypto.Util.Padding import pad, unpad
from Crypto.Cipher import AES
import hashlib
import random
class Person(object):
def __init__(self, p):
self.p = p
self.g = 2
self.x = random.randint(2, self.p - 1)
def calc_key(self):
self.k = pow(self.g, self.x, self.p)
return self.k
def set_shared_key(self):
self.sk = 9165507793789697032
aes_key = hashlib.md5(str(self.sk).encode()).digest()
self.cipher = AES.new(aes_key, AES.MODE_ECB)
def encrypt(self, pt):
return self.cipher.encrypt(pad(pt, 16)).hex()
def decrypt(self, ct):
return unpad(self.cipher.decrypt(bytes.fromhex(ct)), 16)
prime = 16683502042145070731
alice = Person(prime)
bob = Person(prime)
bob.set_shared_key()
alice.set_shared_key()
print(f"Alice: {alice.decrypt('e479a9dcb605f253c39332a04ce5f726')}")
print(f"Bob: {bob.decrypt('2e38b3ee0ec957aa62bdabd9e6b4ea42')}")
Alice: b'G04T{d1ff13_h3'
Bob: b'11m4n_15_10v3}'