def refresh_token(): global access_token data = { 'client_id': client_id, 'client_secret': client_secret, 'grant_type': 'refresh_token', 'refresh_token': utils.read_param('refresh_token'), 'scope': scope } udata = urllib.urlencode(data) req = urllib2.Request(token_url) resp = urllib2.urlopen(req, udata).read() if debug: print 'refresh_token resp:', resp a = json.loads(resp) utils.write_param('access_token', a['access_token']) utils.write_param('refresh_token', a['refresh_token']) access_token = utils.read_param('access_token')
def main(args): """ parse command line arguments""" tstart = time.clock() if not args.log: logging.basicConfig(level=args.loglevel or logging.INFO) else: logging.basicConfig(filename='log', filemode='w', level=logging.DEBUG) logger = logging.getLogger(__name__) """ read plasma parameters """ param = utils.read_param(args) """ iterate through wavenumber """ dk = (param['kend'][0] - param['kstart'][0]) / (param['ksteps'][0] - 1) #fzeta = np.empty(int(param['ksteps'][0]),dtype=complex) fzeta = np.empty((int(param['ntheta'][0]), int(param['ksteps'][0])), dtype=complex) wave_k = np.empty(int(param['ksteps'][0])) zeta_guess = complex(param['omega_r'][0], param['omega_i'][0]) theta_arr = np.linspace(param['thetai'][0], param['thetae'][0], int(param['ntheta'][0])) for i in range(len(theta_arr)): param['theta'][0] = theta_arr[i] for n in range(int(param['ksteps'][0])): if i > 0 and n == 0: #zeta_guess = complex(param['omega_r'][0],param['omega_i'][0]) zeta_guess = fzeta[i - 1][0] logger.info('%d th iteration in %d ksteps \n', n, param['ksteps'][0]) wave_k[n] = param['kstart'][0] + n * dk """ find dispersion relation root """ data = (args, param, wave_k[n]) try: sol = root(disp.det,(zeta_guess.real,zeta_guess.imag), \ args=data,method='lm',tol=param['sol_err'][0]) fzeta[i][n] = complex(sol.x[0], sol.x[1]) logger.info("solution: zeta= %1.1e +%1.1e i", fzeta[i][n].real, fzeta[i][n].imag) except ValueError: logger.info('ERROR in root finding: wave_k =%f', wave_k[n]) sys.exit() zeta_guess = fzeta[i][n] """ save results to output file """ param['wave_k'] = wave_k param['fzeta'] = fzeta param['theta'] = theta_arr if args.output: np.save(args.output + '.npy', param) else: np.save('output.npy', param) tend = time.clock() logger.info('\n Total time lapse: %1.2f\n', tend - tstart) return 0
def main(args): """ parse command line arguments""" tstart = time.clock() if not args.log: logging.basicConfig(level=args.loglevel or logging.INFO) else: logging.basicConfig(filename='log', filemode='w', level=logging.DEBUG) logger = logging.getLogger(__name__) """ read plasma parameters """ param = utils.read_param(args) """ iterate through wavenumber """ dk = (param['kend'][0] - param['kstart'][0]) / param['ksteps'][0] wave_k = np.empty(int(param['ksteps'][0])) for n in range(int(param['ksteps'][0])): wave_k[n] = param['kstart'][0] + n * dk param['wave_k'] = wave_k theta = np.linspace(param['thetamin'][0], param['thetamax'][0], int(param['ntheta'][0])) zeta_guess = complex(param['omega_r'][0], param['omega_i'][0]) """ parallizization, (increase # of threads may not improve peformance) """ pool = mp.Pool(len(theta)) zeta = [] for i in range(0, len(theta)): res = pool.apply_async(Loop, args=(i, args, param, theta[i], zeta_guess)) zeta.append(res) pool.close() pool.join() """ save results to output file """ fzeta = [] for dat in zeta: fzeta.append(np.array(dat.get())) param['fzeta'] = np.array(fzeta) param['theta'] = theta if args.output: np.save(args.output + '.npy', param) else: np.save('output.npy', param) tend = time.clock() logger.info('\n Total time lapse: %1.2f\n', tend - tstart) return 0
e = random.randint(2, n - 1) while sympy.gcd(e, n - 1) != 1 and e not in t: e = random.randint(2, n - 1) t.append(e) d = utils.inverse(e, n - 1) result.append([[e, n], [d, n]]) return result if __name__ == '__main__': step = int(sys.argv[2]) dont_crypt_deck = True debug = False if step == 1 or debug: # Создают пары public/private l = utils.read_param('l.txt', 'l') A_keys, B_keys, C_keys = create_keys(3, l) utils.save_param('Alice/A_sk.json', 'key', A_keys[0]) utils.save_param('A_ok.json', 'key', A_keys[1]) utils.save_param('Bob/B_sk.json', 'key', B_keys[0]) utils.save_param('B_ok.json', 'key', B_keys[1]) utils.save_param('Carroll/C_sk.json', 'key', C_keys[0]) utils.save_param('C_ok.json', 'key', C_keys[1]) if step == 2 or debug: # Alice step deck = create_deck() # _, deck = choose_card(deck, 52) A_ok = utils.read_param('A_ok.json', 'key') if dont_crypt_deck: for idx, item in enumerate(deck): utils.save_param('Alice/{}_ncrypt.json'.format(idx), 'card', item[0]) utils.save_param('Alice/{}_ncrypt.json'.format(idx), 'num', item[1])
def main(): # 322 страница протокол аутентификации m = int(sys.argv[1]) # int(input('m: ')) debug = False if m == 1: p, a, G, r = create_elliptic() save_param('curve.json', 'p', p) save_param('curve.json', 'a', a) save_param('curve.json', 'G', (G.x, G.y)) save_param('curve.json', 'r', r) if m == 2 or debug: Gp = read_param('curve.json', 'G') a = read_param('curve.json', 'a') p = read_param('curve.json', 'p') r = read_param('curve.json', 'r') assert 0 <= Gp[0] < p, 0 <= Gp[1] < p g = ep(p, Gp[0], Gp[1]) x, P, Q = key_generation(r, g, a, p) save_param('secret.json', 'x', x) save_param('P.json', 'P', (P.x, P.y)) save_param('Q.json', 'Q', (Q.x, Q.y)) if m == 3 or debug: M = open('file.txt', 'rb').read() Qp = read_param('Q.json', 'Q') a = read_param('curve.json', 'a') r = read_param('curve.json', 'r') p = read_param('curve.json', 'p') x = read_param('secret.json', 'x') Q = ep(p, Qp[0], Qp[1]) e, s, R = signature(M, Q, a, r, p, x) save_param('signature.json', 'e', e) save_param('signature.json', 's', s) save_param('signature.json', 'R', (R.x, R.y)) if m == 4 or debug: M = open('file.txt', 'rb').read() a = read_param('curve.json', 'a') r = read_param('curve.json', 'r') p = read_param('curve.json', 'p') s = read_param('signature.json', 's') e = read_param('signature.json', 'e') Qp = read_param('Q.json', 'Q') Rp = read_param('signature.json', 'R') Pp = read_param('P.json', 'P') Q = ep(p, Qp[0], Qp[1]) R = ep(p, Rp[0], Rp[1]) P = ep(p, Pp[0], Pp[1]) result = verify(M, P, Q, R, a, p, s, e, r) save_param('result.json', 'result', result)
def create_elliptic(): l, m = read_param('ln.json', 'ln'), 10 p, a, G, r = generator_elliptic_curve(l, m) return p, a, G, r
def main(): parser = argparse.ArgumentParser() parser.add_argument('-m', type=int, default=1) parser.add_argument('-b', type=int) parser.add_argument('--draw', action='store_true') parser = parser.parse_args() if parser.m == 1: # Пегги graph_size = utils.read_param('graph_size', 'size') edges, cycle = generate_graph(graph_size) utils.save_param('G_graph.param', 'edges', edges) utils.save_param('Peggy/G_cycle.param', 'cycle', cycle) if parser.draw: draw_graph(edges) elif parser.m == 2: # Пегги. генерация изоморфного графа edges = utils.read_param('G_graph.param', 'edges') cycle = utils.read_param('Peggy/G_cycle.param', 'cycle') g = Graph(edges, cycle) iso_graph, iso = create_iso_graph(g) utils.save_param('H_graph.param', 'edges', iso_graph.edges) utils.save_param('Peggy/H_cycle.param', 'cycle', iso_graph.cycle) utils.save_param('Peggy/H_iso.param', 'iso', iso) if parser.draw: draw_graph(iso_graph.edges) elif parser.m == 3: # Виктор b = random.randint(0, 1) if parser.b: b = parser.b utils.save_param('b.param', 'b', b) elif parser.m == 4: # Пегги исполняет просьбу исходя из b b = utils.read_param('b.param', 'b') if b == 0: iso = utils.read_param('Peggy/H_iso.param', 'iso') utils.save_param('iso_GH.param', 'iso', iso) elif b == 1: cycle = utils.read_param('Peggy/H_cycle.param', 'cycle') utils.save_param('cycle_in_H.param', 'cycle', cycle) elif parser.m == 5: # Виктор проверяет то что предоставила Пегги b = utils.read_param('b.param', 'b') if b == 0: iso = utils.read_param('iso_GH.param', 'iso') G = utils.read_param('G_graph.param', 'edges') H = utils.read_param('H_graph.param', 'edges') result = check_iso(G, H, iso) utils.save_param('result.txt', 'check iso', result) elif b == 1: cycle = utils.read_param('cycle_in_H.param', 'cycle') H = utils.read_param('H_graph.param', 'edges') result = check_gam_cycle(H, cycle) utils.save_param('result.txt', 'check cycle', result)
def main(): parser = argparse.ArgumentParser() parser.add_argument('-m', type=int, default=1) args = parser.parse_args(sys.argv[1:]) debug = False if args.m == 0: # Генерация эллиптическрй кривой ln = utils.read_param('ln.json', 'ln') p, a, Q, r = ec.generator_elliptic_curve(ln, 30) l = random.randint(1, r) P = ep.mul(Q, l, a, p) utils.save_param('l.json', 'l', l) utils.save_param('curve.json', 'p', p) utils.save_param('curve.json', 'Q', (Q.x, Q.y)) utils.save_param('curve.json', 'a', a) utils.save_param('curve.json', 'r', r) utils.save_param('P.json', 'P', (P.x, P.y)) utils.save_param('stat.json', 'stat', 0) if args.m == 1 or debug: # Alice if utils.read_param('stat.json', 'stat') == -1: raise Exception('Необходимо перегенерировать параметры') p = utils.read_param('curve.json', 'p') a = utils.read_param('curve.json', 'a') r = utils.read_param('curve.json', 'r') P = utils.read_param('P.json', 'P') l = utils.read_param('l.json', 'l') P = ep(p, P[0], P[1]) k1 = random.randint(2, r) k2 = k1 * l % r R = ep.mul(P, k1, a, p) utils.save_param('secret_key.json', 'k1', k1) utils.save_param('secret_key.json', 'k2', k2) utils.save_param('R.json', 'R', (R.x, R.y)) if args.m == 2 or debug: # Bob if utils.read_param('stat.json', 'stat') == -1: raise Exception('Необходимо перегенерировать параметры') p = utils.read_param('curve.json', 'p') a = utils.read_param('curve.json', 'a') r = utils.read_param('curve.json', 'r') R = utils.read_param('R.json', 'R') R = ep(p, R[0], R[1]) if ep.iszero(ep.mul(R, r, a, p)) and not ep.iszero(R): bit = random.randint(0, 1) print(bit) else: utils.save_param('stat.json', 'stat', -1) raise Exception('rR == Pinf and R is not be equal Pinf') utils.save_param('bit.json', 'bit', bit) if args.m == 3 or debug: # Alice if utils.read_param('stat.json', 'stat') == -1: raise Exception('Необходимо перегенерировать параметры') bit = utils.read_param('bit.json', 'bit') if bit == 0: k = utils.read_param('secret_key.json', 'k1') utils.save_param('k.json', 'k', k) elif bit == 1: k = utils.read_param('secret_key.json', 'k2') utils.save_param('k.json', 'k', k) if args.m == 4 or debug: if utils.read_param('stat.json', 'stat') == -1: raise Exception('Необходимо перегенерировать параметры') p = utils.read_param('curve.json', 'p') a = utils.read_param('curve.json', 'a') k = utils.read_param('k.json', 'k') R = utils.read_param('R.json', 'R') R = ep(p, R[0], R[1]) Q = utils.read_param('curve.json', 'Q') Q = ep(p, Q[0], Q[1]) P = utils.read_param('P.json', 'P') P = ep(p, P[0], P[1]) bitt = utils.read_param('bit.json', 'bit') if bitt == 0: if ep.mul(P, k, a, p) == R: gd = utils.read_param('stat.json', 'stat') gd += 1 log = 1 - 1 / pow(2, gd) utils.save_param('stat.json', 'stat', gd) print('Претендент подтвердил что вероятно знает логарифм') print('Знает логарифм с верояностью {}'.format(log)) else: utils.save_param('stat.json', 'stat', -1) print('Не верно') else: if ep.mul(Q, k, a, p) == R: gd = utils.read_param('stat.json', 'stat') gd += 1 log = 1 - 1 / pow(2, gd) utils.save_param('stat.json', 'stat', gd) print('Претендент подтвердил что вероятно знает логарифм') print('Знает логарифм с верояностью {}'.format(log)) else: utils.save_param('stat.json', 'stat', -1) print('Не верно')
def main(args): """ parse command line arguments""" tstart = time.clock() if not args.log: logging.basicConfig(level=args.loglevel or logging.INFO) else: logging.basicConfig(filename='log', filemode='w', level=logging.DEBUG) logger = logging.getLogger(__name__) """ read plasma parameters """ param = utils.read_param(args) """ iterate through wavenumber """ dk = (param['kend'][0] - param['kstart'][0]) / param['ksteps'][0] fzeta = np.empty(int(param['ksteps'][0]), dtype=complex) wave_k = np.empty(int(param['ksteps'][0])) zeta_guess = complex(param['omega_r'][0], param['omega_i'][0]) # eigen value and polaization iEx/Ey*(omega_r/abs(omega_r)) val = [] pol = [] for n in range(int(param['ksteps'][0])): logger.info('%d th iteration in %d ksteps \n', n, param['ksteps'][0]) wave_k[n] = param['kstart'][0] + n * dk """ find dispersion relation root """ data = (args, param, wave_k[n]) try: # use parallel dsp if theta<0.1 degree if (abs(param['theta'][0]) < 1.): sol = root(disp.det_para,(zeta_guess.real,zeta_guess.imag), \ args=data,method='hybr',tol=param['sol_err'][0]) fzeta[n] = complex(sol.x[0], sol.x[1]) else: sol = root(disp.det,(zeta_guess.real,zeta_guess.imag), \ args=data,method='hybr',tol=param['sol_err'][0]) fzeta[n] = complex(sol.x[0], sol.x[1]) logger.info("solution: k*di=%1.2e , omega/Omega_ci=%1.2e+%1.2ei\n", wave_k[n], fzeta[n].real, fzeta[n].imag) if (param['cal_pol'][0]): import pol as p val0, pol0 = p.pol(args, param, wave_k[n], fzeta[n]) val.append(val0) pol.append(pol0) if (fzeta[n].imag < 0): param['exp'][0] = 0 except ValueError: logger.info('ERROR in root finding: wave_k =%f', wave_k[n]) """ extrapolate previous solutions for next guess """ if (n > 3 and n < int(param['ksteps'][0]) - 1): zeta_guess = complex(interp(wave_k[n]+dk,wave_k[n-3:n],fzeta[n-3:n].real),\ interp(wave_k[n]+dk,wave_k[n-3:n],fzeta[n-3:n].imag)) else: zeta_guess = fzeta[n] """ save results to output file """ param['wave_k'] = wave_k param['fzeta'] = fzeta if args.output: np.save(args.output + '.npy', param) else: np.save('output.npy', param) tend = time.clock() logger.info('\n Total time lapse: %1.2f\n', tend - tstart) return 0
def main(): parser = argparse.ArgumentParser() parser.add_argument('-m', type=int, default=1) args = parser.parse_args(sys.argv[1:]) if args.m == 1: len_p = read_param('len_p.j', 'l') g, p = get_public_params(len_p) save_param('g.json', 'g', g) save_param('p.json', 'p', p) elif args.m == 2: # Шаг Алисы p = read_param('p.json', 'p') g = read_param('g.json', 'g') x, k = get_private_params_Alice(p, g) save_param('x.json', 'x', x) save_param('k.json', 'k', k) elif args.m == 3: # Шаг Боба p = read_param('p.json', 'p') g = read_param('g.json', 'g') y, d, z = get_private_params_Bob(p, g) save_param('y.json', 'x', y) save_param('d.json', 'd', d) save_param('z.json', 'z', z) elif args.m == 4: # Шаг Алисы d = read_param('d.json', 'd') p = read_param('p.json', 'p') x = read_param('x.json', 'x') m = pow(d, x, p) write_log('Алисой вычислен параметр m: {}'.format(m)) save_param('m.json', 'm', m) # m == X elif args.m == 5: z = read_param('z.json', 'z') m = read_param('m.json', 'm') p = read_param('p.json', 'p') k = pow(m, z, p) write_log('Бобом вычислен параметр k: {}'.format(k)) save_param('Bob_key.json', 'k', k) else: write_log('Bad args')
import json, os, urllib, urllib2, shutil, hashlib, time import utils # ==== constants =================================== client_id = "a332b9d61df7254dffdc81a260373f25592c94c9" client_secret = '744a52aff20ec13f53bcfd705fc4b79195265497' code_url = 'https://accounts.etvnet.com/auth/oauth/device/code' token_url = 'https://accounts.etvnet.com/auth/oauth/token' api_root = 'https://secure.etvnet.com/api/v3.0/' scope = 'com.etvnet.media.browse com.etvnet.media.watch com.etvnet.media.bookmarks com.etvnet.media.history \ com.etvnet.media.live com.etvnet.media.fivestar com.etvnet.media.comments com.etvnet.persons com.etvnet.notifications' # ================================================== # ==== params ===================================== access_token = utils.read_param('access_token') debug = False bitrate = 1200 # ================================================== def read_json(fname): f = open(fname) text = f.read() f.close() a = json.loads(text) return a def refresh_token(): global access_token
def main(): parser = argparse.ArgumentParser() parser.add_argument('-m', type=int, default=1) args = parser.parse_args(sys.argv[1:]) with open('file_to_signature.txt') as f: file = json.load(f) m = open(file['file'], 'rb').read() if args.m == 1: # публичные параметры len_p = read_param('len_p.j', 'l') p, q, g = get_public_params(len_p) save_param('p.json', 'p', p) save_param('q.json', 'q', q) save_param('g.json', 'g', g) elif args.m == 2: # частные парметры p = read_param('p.json', 'p') q = read_param('q.json', 'q') g = read_param('g.json', 'g') x, y = get_private_params(p, q, g) save_param('x.json', 'x', x) save_param('y.json', 'y', y) elif args.m == 3: # Алиса генерит k < q q = read_param('q.json', 'q') k = utils.get_big_prime(2, q) save_param('k.json', 'k', k) # elif args.m == 4: # Алиса подписывает g = read_param('g.json', 'g') k = read_param('k.json', 'k') p = read_param('p.json', 'p') q = read_param('q.json', 'q') x = read_param('x.json', 'x') r = pow(g, k, p) % q s = (utils.inverse(k, q) * (get_hash(m) + x * r)) % q save_param('signature.json', 'r', r) save_param('signature.json', 's', s) elif args.m == 4: # боб проверяет s = read_param('signature.json', 's') r = read_param('signature.json', 'r') q = read_param('q.json', 'q') p = read_param('p.json', 'p') g = read_param('g.json', 'g') y = read_param('y.json', 'y') w = utils.inverse(s, q) u1 = get_hash(m) * w % q u2 = r * w % q v = ((pow(g, u1, p) * pow(y, u2, p)) % p) % q save_param('v.json', 'v', v) if v == r: print("Подпись верна") input() else: print("Подпись не верна") # 2.3 else: write_log('Bad args')
def main(): # 322 страница протокол аутентификации m = int(input('m: ')) if m == 1: p, a, G, r = create_elliptic() save_param('curve.json', 'p', p) save_param('curve.json', 'a', a) save_param('curve.json', 'G', (G.x, G.y)) save_param('curve.json', 'r', r) elif m == 2: Gp = read_param('curve.json', 'G') a = read_param('curve.json', 'a') p = read_param('curve.json', 'p') r = read_param('curve.json', 'r') assert 0 <= Gp[0] < p, 0 <= Gp[1] < p G = ep(p, Gp[0], Gp[1]) k, A = key_generation(G, a, p, r) save_param('alice_secret_key.json', 'key', k) save_param('alice_public_key.json', 'Ax', A.x) save_param('alice_public_key.json', 'Ay', A.y) save_param('alice_public_key.json', 'p', A.p) elif m == 3: M = open('file.txt', 'rb').read() Gp = read_param('curve.json', 'G') a = read_param('curve.json', 'a') r = read_param('curve.json', 'r') p = read_param('curve.json', 'p') x = read_param('alice_secret_key.json', 'key') G = ep(p, Gp[0], Gp[1]) R, s = signature(M, G, a, r, p, x) save_param('signature.json', 'R', (R.x, R.y)) save_param('signature.json', 's', s) elif m == 4: M = open('file.txt', 'rb').read() Rp = read_param('signature.json', 'R') s = read_param('signature.json', 's') Ax = read_param('alice_public_key.json', 'Ax') Ay = read_param('alice_public_key.json', 'Ay') Gp = read_param('curve.json', 'G') a = read_param('curve.json', 'a') p = read_param('curve.json', 'p') r = read_param('curve.json', 'r') G = ep(p, Gp[0], Gp[1]) A = ep(p, Ax, Ay) R = ep(p, Rp[0], Rp[1]) result = verify(M, R, s, a, p, A, G, r) save_param('result.json', 'result', result)