Path: blob/master/Elgamal-Encryption/Challenges/Megalal/megalal.py
1402 views
#!/usr/bin/env python212import binascii3import base644import random56from secrets import g, p, x, h, flag78def xgcd(b, n):9x0, x1, y0, y1 = 1, 0, 0, 110while n != 0:11q, b, n = b // n, n, b % n12x0, x1 = x1, x0 - q * x113y0, y1 = y1, y0 - q * y114return b, x0, y01516def modinv(b, n):17g, x, _ = xgcd(b, n)18if g == 1:19return x % n2021def enc(m):22M = int(binascii.hexlify(m), 16)23assert len(bin(M)) < len(bin(p)), 'm too long'2425y = random.SystemRandom().randint(0, p-1)26c1 = pow(g, y, p)27c2 = (M * pow(h, y, p) ) % p2829return c1, c23031def dec(c1, c2):32s = pow(c1, x, p)33M = (c2 * modinv(s, p)) % p3435return str(binascii.unhexlify('{:x}'.format(M)))3637def login():38c = raw_input('Please input your access token: ').split('_')39c1 = int(c[0], 16)40c2 = int(c[1], 16)41user, role = dec(c1, c2).split('#')42print('\nWelcome {}!'.format(user))43print('Your role is \'{}\'.\n'.format(role))44if role == 'overlord':45print('Here\'s your flag: {}'.format(flag))46print('That\'s all, nothing else happening here.')4748def register():49username = raw_input('Your username: ')50role = raw_input('Your role: ')5152if role == 'overlord':53print('nope, you\'re not the overlord...')54return55c = enc('%s#%s' % (username, role))56token = '{:x}_{:x}'.format(c[0], c[1])5758print('Here is your access token:\n{}'.format(token))5960if __name__ == '__main__':61print('What do you want to do?')62print('[1] Login')63print('[2] Register')64choice = raw_input('> ')65try:66if choice == '1':67login()68elif choice == '2':69register()70except:71print('something went wrong...')727374