def time_scalar_mul(): import time, pprint G = EcGroup() d = G.parameters() a, b, p = d["a"], d["b"], d["p"] g = G.generator() x, y = g.get_affine() scalars = G.order().hex() results = [] for i in range(0, len(scalars), 3): r = Bn.from_hex(scalars[:i+1]) start = time.clock() point_scalar_multiplication_double_and_add(a, b, p, x, y, r) elapsed = (time.clock() - start) results.append((r, elapsed)) pp = pprint.PrettyPrinter(indent=2, width=160) pp.pprint(results) for i in range(0, len(scalars), 3): r = Bn.from_hex(scalars[:i+1]) start = time.clock() point_scalar_multiplication_montgomerry_ladder(a, b, p, x, y, r) elapsed = (time.clock() - start) results.append((r, elapsed)) pp = pprint.PrettyPrinter(indent=2, width=160) pp.pprint(results)
def time_scalar_mul(): # setup curve G = EcGroup(713) # NIST curve d = G.parameters() a, b, p = d["a"], d["b"], d["p"] g = G.generator() gx0, gy0 = g.get_affine() order = G.order() r = order.random() gx2, gy2 = (r * g).get_affine() # First a value with low hamming weight scalar_1 = Bn.from_hex('11111111111111111111111111111111111111111') # The second scalar value with a much higher hamming weight scalar_2 = Bn.from_hex('FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF') # Scalar values with higher hamming weight will take longer to # compute the multiplication of. t1 = time.clock() x2, y2 = point_scalar_multiplication_double_and_add( a, b, p, gx0, gy0, scalar_1) t2 = time.clock() runtime = t2 - t1 print("Runtime for scalar 1: " + str(runtime)) t1 = time.clock() x2, y2 = point_scalar_multiplication_double_and_add( a, b, p, gx0, gy0, scalar_2) t2 = time.clock() runtime = t2 - t1 print("Runtime for scalar 2: " + str(runtime))
def report(): frank = request.form['frank'].split(DELIMITER) sender = request.form['sender'] reporter = request.form['reporter'] msg = request.form['message'] test = request.form['test'] db = get_db() sig = str_to_frank(frank, G) if test == "True": with open("test.txt", "rb") as file: data = file.read() info = data.split(DELIMITER.encode('ascii')) pk_s = EcPt.from_binary(info[0], G) pk_r = EcPt.from_binary(info[2], G) else: sender_kb = db.execute( 'SELECT keybase FROM user WHERE twitter = ?', (sender, )).fetchone()['keybase'] reporter_kb = db.execute( 'SELECT keybase FROM user WHERE twitter = ?', (reporter, )).fetchone()['keybase'] r = requests.get("https://" + sender_kb + ".keybase.pub/amf/amf_pk.txt") pk_s = EcPt.from_binary( binascii.a2b_base64(r.text.encode('ascii')), G) r = requests.get("https://" + reporter_kb + ".keybase.pub/amf/amf_pk.txt") pk_r = EcPt.from_binary( binascii.a2b_base64(r.text.encode('ascii')), G) db = get_db() g_db = db.execute('SELECT g FROM judge_keys').fetchone()['g'] o_db = db.execute('SELECT o FROM judge_keys').fetchone()['o'] sk_j_db = db.execute('SELECT sk_j FROM judge_keys').fetchone()['sk_j'] g = EcPt.from_binary(g_db, G) o = Bn.from_hex(o_db.decode('ascii')) sk_j = Bn.from_hex(sk_j_db.decode('ascii')) aux = (g, o) if not dmf.Judge(pk_s, pk_r, sk_j, msg, sig, aux): return "Message could not be authenticated by judge." else: prob = call_perspective_api(msg, ["TOXICITY"], PERSPECTIVE_KEY) if prob["TOXICITY"] > TOXICITY_THRESHOLD: db.execute('INSERT INTO blacklist VALUES (?)', (sender, )) db.commit() return sender + " has been added to the blacklist." else: return "Message not judged to be abusive."
def verifyK(self,pi,P,Q): # c是内部的?C也是内部的?r也是内部的?不用不用,pi传入了 # 预处理 n = len(Q) (C,c,r) = pi # 得到c_,同样分为(1),(2),(3),(4)四步 # (1)得到P,Qi,C各自的二进制表示P_,Q_[],C_,Sigma_(1,n){ri*Qi+r_{n+1}*P+c*C}_ P_ = P.export() Q_ = [] for i in range(n): Q_.append(Q[i].export()) C_ = C.export() # 求点Sigma的位置: Sigma = r[n] * P + c * C for i in range(n): Sigma += r[i] * Q[i] # 将点Sigma转换成byte形式 Sigma_ = Sigma.export() # (2)将P_,Q_[],C_,Sigma_(1,n){ri*Qi+r_{n+1}*P+c*C}顺次拼接在一起,得到二进制串bytestr bytestr = P_ for i in range(n): bytestr += Q_[i] bytestr += C_ + Sigma_ # (3)将二进制串bytestr转换成字符串str0 str0 = str(bytestr) # (4)调用hashlib中的md5函数,将str0映射成为十六进制数字c_,再进一步转换为Bn类型的大整数对象c_ c_ = hashlib.md5(str0.encode('utf8')).hexdigest() c_ = Bn.from_hex(str(c_)) return c_==c
def verifyDL(self,pi,Q): # 预处理 n = len(Q) (C,c,r) = pi # 得到c_,同样分为(1),(2),(3),(4)四步 # (1)得到{Qi},C,Sigma_(1,n){ri*Qi+c*C}各自的二进制表示Q_[],C_,Sigma_ Q_ = [] for i in range(n): Q_.append(Q[i].export()) C_ = C.export() # 求点Sigma的位置: Sigma = c * C for i in range(n): Sigma += r[i] * Q[i] # 将点Sigma转换成byte形式 Sigma_ = Sigma.export() # (2)将Q_[],C_,Sigma_顺次拼接在一起,得到二进制串bytestr bytestr = Q_[0] for i in range(1,n): bytestr += Q_[i] bytestr += C_ + Sigma_ # (3)将二进制串bytestr转换成字符串str0 str0 = str(bytestr) # (4)调用hashlib中的md5函数,将str0映射成为十六进制数字c_,再进一步转换为Bn类型的大整数对象c_ c_ = hashlib.md5(str0.encode('utf8')).hexdigest() c_ = Bn.from_hex(str(c_)) return c_==c
def load_store_list(self, w, d, store_dict): counter = 0 for i in range(d): for j in range(w): contents = store_dict[str(counter)] try: self.store[i][j] = Ct( EcPt.from_binary(binascii.unhexlify(contents['pub']), G), EcPt.from_binary(binascii.unhexlify(contents['a']), G), EcPt.from_binary(binascii.unhexlify(contents['b']), G), Bn.from_hex(contents['k']), Bn.from_hex(contents['m'])) counter += 1 except Exception as e: print "Exception while loading sketch store matrix: " + str( e) traceback.print_exc()
def H_hat(pi_NIZK, phi, otsvk): X_ = otsvk[0].export() Y_ = otsvk[1].export() X_str = str(X_) Y_str = str(Y_) str0 = pi_NIZK + phi + X_str + Y_str c_ = hashlib.md5(str0.encode('utf8')).hexdigest() c_ = Bn.from_hex(str(c_)) return c_
def stage3(): # super annoying that gI have to do this reset_dict_keys() session["challenges"] = {} for i in session["candidates"]: if i != session["chosen"]: session["challenges"][i] = request.form["challenge" + str(i)] # else: # session["challenges"][i] = None # print(session["challenges"]) R = genvote.order.random() rc, masks, rb = genvote.genRealCommitments(session["chosen"], genvote.K, R) commitments, randoms = genvote.genFakeCommitments(session["challenges"], genvote.K, session["chosen"], R) randoms[session["chosen"]] = rb commitments[session["chosen"]] = masks cmt_list = [] for sk in sorted(commitments): cmt_list.append(commitments[sk]) everything = genvote.challengeHash( ''.join(map(str, [rc] + list(chain(cmt_list)))), genvote.K) rx = genvote.order.random() x = genvote.commit(Bn.from_hex(everything), rx) # print("gCHECKING THAT ENCODE AND DECODE WORK!") # eR = encode(R) # ueR = decode(eR) # print("R: ", type(R), type(eR), type(ueR), R == ueR) persist_tricky_objects(R, rc, masks, rb, commitments, randoms, cmt_list, everything, rx, x, answers=None, receipt=None) # NOW WE NEED TO PRINT THE TWO LINES BEHIND THE SHIELD #os.system('echo "' + genvote.EcPtToStr(x) + '" | lpr') print_text(genvote.EcPtToStr(x)) return render_template("stage3.html", candidates=session["candidates"], cand_dict=session["rev_d"], chosen=session["chosen"], challenges=session["challenges"], voter_id=session["voter_id"])
def dec(self, priv, cipher): """Decrypts an encrypted group element""" #print("CSEnc: Dec") u1, u2, e, v = cipher x1, x2, y1, y2, z = priv H = sha256() H.update(u1.export() + u2.export() + e.export()) a = Bn.from_hex(H.hexdigest()) if v.eq((x1 + y1 * a) * u1 + (x2 + y2 * a) * u2): return 1, e + (-1 * z) * u1 else: print("Decryption error") return 0, -1
def castVote(voter_id, candidate): DC = {} R = order.random() for non_vote in filter(lambda l: l != candidate, candidates): DC[non_vote] = ' '.join([getRandomWord() for i in range(4)]) rc, masks, rb = genRealCommitments(candidate, K, R) commitments, randoms = genFakeCommitments(DC, K, candidate, R) randoms[candidate] = rb commitments[candidate] = masks cmt_list = [] for sk in sorted(commitments): cmt_list.append(commitments[sk]) everything = challengeHash(''.join(map(str, [rc] + list(chain(cmt_list)))), K) #alphabetize this rx = order.random() x = commit(Bn.from_hex(everything), rx) DC[candidate] = ' '.join([getRandomWord() for i in range(4)]) #random challenge real vote answers = answerChallenges(DC, randoms, K, R) verifyCommitment(x, rc, cmt_list, rx) challenge_dict = { candidate: { 'challenge': DC[candidate], 'answer': list(map(str, answers[candidate])), 'proof': commitments[candidate] } for candidate in DC } receipt = serializeEcPts({ 'voter_id': voter_id, 'challenges': challenge_dict, 'vote_commitment': rc, 'rx': str(rx), 'commitment_to_everything': x }) sig = do_ecdsa_sign(G, sig_key, EcPtToStr(x).encode('utf-8'), kinv_rp) signed_cmt = '_'.join((EcPtToStr(x), hex(sig[0])[2:], hex(sig[1])[2:])) qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=4, border=4, ) qr.add_data(signed_cmt) qr.make() img = qr.make_image() img.save('qrcodes/to_print.png') return (candidate, rc, R, everything, str(x), answers, receipt)
def enc(self, params, pub, m): """Encrypts the values of a group element""" #print("CSEnc: Enc") o, G, g1, g2 = params c, d, h = pub r = o.random() u1, u2 = r * g1, r * g2 e = r * h + m H = sha256() H.update(u1.export() + u2.export() + e.export()) a = Bn.from_hex(H.hexdigest()) v = r * c + (a * r) * d return [u1, u2, e, v], [r, a]
def proveK(self,m,s,P,Q): # 得到C n = len(m) C = s * P # i = [0,n-1] for i in range(n): C += Q[i] * m[i] # 得到{wi} w = [] for i in range(n + 1): w.append(Bn().from_decimal(str(self.p)).random()) # 得到W W = w[n] * P # w_{n+1}*P for i in range(n): W += Q[i] * w[i] # 得到c,分为(1),(2),(3),(4)四步 # (1)得到P,Qi,C,W各自的二进制表示P_,Q_[],C_,W_ P_ = P.export() Q_ = [] for i in range(n): Q_.append(Q[i].export()) C_ = C.export() W_ = W.export() print("W_为",W_) # (2)将P_,Q_[],C_,W_顺次拼接在一起,得到二进制串bytestr bytestr = P_ for i in range(n): bytestr += Q_[i] bytestr += C_ + W_ # (3)将二进制串bytestr转换成字符串str0 str0 = str(bytestr) # (4)调用hashlib中的md5函数,将str0映射成为十六进制数字c,再进一步转换为Bn类型的大整数对象 c = hashlib.md5(str0.encode('utf8')).hexdigest() c = Bn.from_hex(str(c)) # 得到ri r = [] for i in range(n): r.append(w[i]-c*m[i]) # 得到r_{i+1},存放在r[n]位置 r.append(w[n] - c * s) # 返回pi pi = (C,c,r) return pi
def proveDL(self,m,Q): n = len(m) # 得到C C = m[0] * Q[0] for i in range(1,n): C += m[i] * Q[i] # 得到{wi} w = [] for i in range(n): w.append(Bn().from_decimal(str(self.p)).random()) # 得到W W = w[0] * Q[0] for i in range(1,n): W += w[i] * Q[i] # 得到c,分为(1),(2),(3),(4)四步 # (1)得到{Qi},C,W各自的二进制表示Q_[],C_,W_ Q_ = [] for i in range(n): Q_.append(Q[i].export()) C_ = C.export() W_ = W.export() # (2)将Q_[],C_,W_顺次拼接在一起,得到二进制串bytestr bytestr = Q_[0] for i in range(1,n): bytestr += Q_[i] bytestr += C_ + W_ # (3)将二进制串bytestr转换成字符串str0 str0 = str(bytestr) # (4)调用hashlib中的md5函数,将str0映射成为十六进制数字c,再进一步转换为Bn类型的大整数对象 c = hashlib.md5(str0.encode('utf8')).hexdigest() c = Bn.from_hex(str(c)) # 得到ri r = [] for i in range(n): r.append(w[i]-c*m[i]) # 返回pi pi = (C,c,r) return pi
def build_fiat_shamir_challenge(stmt_prehash, *args, message=""): """Generate a Fiat-Shamir challenge. >>> prehash = sha256(b"statement id") >>> commitment = 42 * EcGroup().generator() >>> isinstance(build_fiat_shamir_challenge(prehash, commitment), Bn) True Args: prehash: Hash object seeded with the proof statement ID. args: Items to hash (e.g., commitments) message: Message to make it a signature PK. """ # Start building the complete hash for the challenge for elem in args: if not isinstance(elem, bytes) and not isinstance(elem, str): encoded = encode(elem) else: encoded = elem stmt_prehash.update(encoded) stmt_prehash.update(message.encode()) return Bn.from_hex(stmt_prehash.hexdigest())
def str_to_frank(l, G): elem1 = EcPt.from_binary(binascii.a2b_base64(l[0].encode('ascii')), G) elem2 = EcPt.from_binary(binascii.a2b_base64(l[1].encode('ascii')), G) elem3 = EcPt.from_binary(binascii.a2b_base64(l[2].encode('ascii')), G) elem4 = EcPt.from_binary(binascii.a2b_base64(l[3].encode('ascii')), G) elem5 = EcPt.from_binary(binascii.a2b_base64(l[4].encode('ascii')), G) elem6 = Bn.from_hex(l[5]) elem7 = Bn.from_hex(l[6]) elem8 = Bn.from_hex(l[7]) elem9 = Bn.from_hex(l[8]) elem10 = Bn.from_hex(l[9]) elem11 = Bn.from_hex(l[10]) elem12 = EcPt.from_binary(binascii.a2b_base64(l[11].encode('ascii')), G) elem13 = EcPt.from_binary(binascii.a2b_base64(l[12].encode('ascii')), G) elem14 = EcPt.from_binary(binascii.a2b_base64(l[13].encode('ascii')), G) elem15 = EcPt.from_binary(binascii.a2b_base64(l[14].encode('ascii')), G) return ((((elem1, elem2), ((elem3, elem4), elem5)), ((elem6, elem7, elem8), \ (elem9, elem10, elem11))), elem12, elem13, elem14, elem15)
def load_store_list(self, w, d, store_dict): counter = 0 for i in range(d): for j in range(w): contents = store_dict[str(counter)] try: self.store[i][j] = Ct(EcPt.from_binary(binascii.unhexlify(contents['pub']),G), EcPt.from_binary(binascii.unhexlify(contents['a']),G), EcPt.from_binary(binascii.unhexlify(contents['b']),G), Bn.from_hex(contents['k']), Bn.from_hex(contents['m'])) counter += 1 except Exception as e: print "Exception while loading sketch store matrix: " + str(e) traceback.print_exc()
def generateData(): params = setup(4) (G, o, g1, hs, g2, e) = params hex_m_priv1 = "24ABEE7D59CA09122391B3ECCBEBE0FA79EB9954D0E9F139A2A6E129445F1208" hex_m_priv2 = "1B4A6A9A72935D4D3CBCDEA5143480C543E9F3F0C91787605220BF54EC4E6078" hex_m_pub1 = "1D70206E93922A266B6F522CB1EC8AA72F908AC87EED1E43C641BFAF3C82AC32" hex_m_pub2 = "0F6EE88081A8A94677A8993F85245C30106B1A8E794496276B1452915F4BB708" hex_x = "076501B5E73FA81B28FAB06EE3F6929E6AE4DB9461A49930C49EF1B28A625DD2" hex_y0 = "0CE30F26C29ADBE06AE98D9B49DB3FF323C8100072298E9A58AC347E9BE59F36" hex_y1 = "09BD32C15ED60E7C9E5EC7FD2D3294D712DDC0AE510071D3AD9CE3DE0F1F23C1" hex_y2 = "0CF37DAD7889F0959E571D79532CD1E3AE74BD2B26C78D68251EDB7685782B9E" hex_y3 = "07712709AED9F065B553E08267EA9A5C75D0B4F62DE110569BF350E8BDC0F980" hex_h = "021c1dbf7bdc24be8d2b5c56d7a3162a9a1ef824134c3a95b6d306ecd8ce90c193" # (random * g1) (for Pointcheval) hex_d = "1CF5133799A1CB2A1A46DD3FA5CB1EA9069D022236747F1CCA77401A265CEA33" hex_r = "24338A5F29CAB6BD573F87D5E2E6DDCFFB55CDB55D03A40A828A061E0E9957CE" hex_k1 = "077CA2D8137CA54B12011E564BA9B4204ADECA64499D07EE02DE6420E8B058A8" hex_k2 = "12B9BD2873FD1BA68D0B61A9B6840CA920C493D54CE85E8C2143C12F144C3B26" hex_wr = "1D7A898A391A664BAF3146F7ACA1FC0E954ED426ACD2D50146997A94053DCF6A" hex_wk1 = "0AF5628DF706A6CF503237499F793ABBDF4379DE3EF2D3DE777F4AB32B3147BD" hex_wk2 = "0E093B9EE3273CFB42C2765A0D78EF4EBD40126DC1703A921680EAA4CF50814D" hex_wm1 = "1DA762D767AD63BD4226CC6E859FC376CA03A047E47B82AFE8574D93DF39B5BB" hex_wm2 = "11A4B4BF934A3709F9E7A54324AACF0ED13BCAAA0CC2AD2791437363A64E404C" hex_wm3 = "096EB6930E70DEE0ACC0093A23A3586217C20FD6FD1ECB9923B2EDCE288F961F" hex_wm4 = "131CCECB6386CA3A773C898193116B76A2D6BD34D3BB4A7BC7143E494B7C69D9" hex_t = "0ADE8E2E5EC8806EC1B873B0F5735A9EB7FCA8D7DA3AC8D965487E0982C75F68" hex_wm1_v = "05E8CB173C636A190CC628803768833123A9FC54A92224D97155E87EF7E3F3C4" hex_wm2_v = "124052CD6EB215D98B20F343348E3898E65AC82A43AA57D0720311259D05D3DA" hex_wt = "0E7BF9EAD25C09716291E864B99DD063EC911ABCD26CBF682DE9B7C4E95D126F" # elgamal keypair d = Bn.from_hex(hex_d) gamma = g1 * d # attributes to sign private_m = [Bn.from_hex(hex_m_priv1), Bn.from_hex(hex_m_priv2)] public_m = [Bn.from_hex(hex_m_pub1), Bn.from_hex(hex_m_pub2)] # coconut keys x = Bn.from_hex(hex_x) y = [ Bn.from_hex(hex_y0), Bn.from_hex(hex_y1), Bn.from_hex(hex_y2), Bn.from_hex(hex_y3) ] beta = [g2 * y[0], g2 * y[1], g2 * y[2], g2 * y[3]] sk = (x, y) vk = (g2, g2 * x, beta) r = Bn.from_hex(hex_r) ks = [Bn.from_hex(hex_k1), Bn.from_hex(hex_k2)] # create the witnesses wr = Bn.from_hex(hex_wr) wk = [Bn.from_hex(hex_wk1), Bn.from_hex(hex_wk2)] wm = [ Bn.from_hex(hex_wm1), Bn.from_hex(hex_wm2), Bn.from_hex(hex_wm3), Bn.from_hex(hex_wm4) ] witnesses = (wr, wk, wm) (cm, c, pi_s) = prepare_blind_sign_r(r, ks, witnesses, params, gamma, private_m, public_m=public_m) sigma_tilde = blind_sign(params, sk, cm, c, gamma, pi_s, public_m=public_m) sigma = unblind(params, sigma_tilde, d) # sigma = randomize(params, sig) # multiplication by a constant factor is consistent so there's no need of testing randomization t = Bn.from_hex(hex_t) # create the witnesses wm = [Bn.from_hex(hex_wm1_v), Bn.from_hex(hex_wm2_v)] wt = Bn.from_hex(hex_wt) witnesses = (wm, wt) (kappa, nu, pi_v) = show_blind_sign_t(t, witnesses, params, vk, sigma, private_m) assert blind_verify(params, vk, sigma, kappa, nu, pi_v, public_m=public_m)
def verifyCommitment(x, vote, commitments, rx): everything = challengeHash(''.join( map(str, [vote] + list(chain(commitments)))), K) #alphabetize this result = commit(Bn.from_hex(everything), rx) assert (result == x)
##################################################### # TASK 6 -- Time EC scalar multiplication # Open Task. # # - Time your implementations of scalar multiplication # (use time.clock() for measurements)for different # scalar sizes) # - Print reports on timing dependencies on secrets. # - Fix one implementation to not leak information. from pytest import raises from time import clock from petlib.ec import EcGroup, EcPt R1 = Bn.from_hex( "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" ) R2 = Bn.from_hex( "100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001" ) def time_scalar_mul(): G = EcGroup(713) # NIST curve d = G.parameters() a, b, p = d["a"], d["b"], d["p"] g = G.generator() gx0, gy0 = g.get_affine() def average_time(func, scalar_name, samples=20): scalar = globals()[scalar_name]
def read_sk(): with open("messages.cfg", "rb") as file: data = file.read() info = data.split(DELIMITER.encode('ascii')) sk = Bn.from_hex(info[2].decode('ascii')) return sk
def get_aux(): response = requests.get(ADDRESS + "get_aux") info = response.text.split(DELIMITER) g = EcPt.from_binary(binascii.a2b_base64(info[0].encode('ascii')), G) o = Bn.from_hex(info[1]) return (g, o)
def test_uuid_to_hex(self): uuid = uuid4().hex bn = Bn.from_hex(uuid) print(bn)