Example #1
0
    def verify(self, message, sig):
        """ Verify the message and the signature """

        assert len(message) == 32
        lr, r, ls, s = unpack("H32sH32s", sig)
        sig = Bn.from_binary(r[:lr]), Bn.from_binary(s[:ls])
        return do_ecdsa_verify(self.G, self.pub, sig, message)
Example #2
0
def gen_key():
    """Example naive RSA key generation"""
    p = Bn.get_prime(512)
    q = Bn.get_prime(512)
    m = p * q
    phi = (p - 1) * (q - 1)
    e = Bn(2**16 + 1)
    d = e.mod_inverse(phi)
    pub = (e, m)
    priv = (d,)
    return pub, priv
Example #3
0
def point_add(a, b, p, x0, y0, x1, y1):
    """Define the "addition" operation for 2 EC Points.

    Reminder: (xr, yr) = (xq, yq) + (xp, yp)
    is defined as:
        lam = (yq - yp) * (xq - xp)^-1 (mod p)
        xr  = lam^2 - xp - xq (mod p)
        yr  = lam * (xp - xr) - yp (mod p)

    Return the point resulting from the addition. Raises an Exception if the points are equal.
    """
    xr, yr = None, None

    if not all([x0, y0, x1, y1]):
        # Either is origin; inf is "(0,0)"
        xr = x0 or x1
        yr = y0 or y1
    elif (x0 == x1 and y0 == y1):
        # Point doubling
        #xr, yr = point_double(a, b, p, x0, y0)
        # NOTE: asked to raise exact exception
        raise Exception("EC Points must not be equal")
    elif (y0 + y1) % p == Bn(0):
        # Negation, checking y coord, return origin
        pass
    else:
        inv = (x1 - x0).mod_inverse(p)
        lam = ((y1 - y0) * inv) % p
        xr = (lam**2 - x0 - x1) % p
        yr = (lam * (x0 - xr) - y0) % p
    
    return (xr, yr)
Example #4
0
 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
Example #5
0
 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
Example #6
0
def layer_C1_4(gk, Chi_share, Chi, g1_chipows, g1_polyhats, n, mpc):
    print("\n Layer C1.4")
    g2_chipows = [gk.g2]
    g1_beta_chipows = []
    g1_betahat_polyhats = []

    share_chi = Chi_share.chi
    share_beta = Chi_share.beta
    share_betahat = Chi_share.betahat

    g2_chi = Chi.g2_chi

    share_chi_pow = Bn(1)
    md_list_x = []
    md_list_bx = [MD_Elems(gk, share_beta, 1, g1_chipows[0])]
    md_list_bp = []
    q = gk.q
    share_chi = Chi_share.chi
    for i in range(1, n + 1):
        md_list_x.append(MD_Elems(gk, share_chi_pow, 1, g2_chi))
        share_chi_pow = share_chi * share_chi_pow % q

        md_list_bx.append(MD_Elems(gk, share_beta, 1, g1_chipows[i]))
        md_list_bp.append(MD_Elems(gk, share_betahat, 1, g1_polyhats[i - 1]))

    g2_chipows.extend(mpc.parallel_md(md_list_x))
    g1_beta_chipows.extend(mpc.parallel_md(md_list_bx))
    g1_betahat_polyhats.extend(mpc.parallel_md(md_list_bp))

    return g2_chipows, g1_beta_chipows, g1_betahat_polyhats
Example #7
0
def test_bbsplus_and_range():
    from zksk.primitives.rangeproof import RangeStmt
    from zksk.utils import make_generators

    mG = BilinearGroupPair()
    keypair = BBSPlusKeypair.generate(mG, 9)

    pk, sk = keypair.pk, keypair.sk
    generators, h0 = keypair.generators, keypair.h0

    creator = BBSPlusSignatureCreator(pk)
    msg_val = Bn(30)
    lhs = creator.commit([msg_val])
    presignature = sk.sign(lhs.com_message)
    signature = creator.obtain_signature(presignature)
    e, s, m = Secret(signature.e), Secret(signature.s), Secret(msg_val)

    p1 = BBSPlusSignatureStmt([e, s, m], pk, signature)

    g, h = make_generators(2, mG.G1)
    randomizer = Secret(value=mG.G1.order().random())
    com = m * g + randomizer * h
    p2 = RangeStmt(com.eval(), g, h, 18, 9999, m, randomizer)

    stmt = p1 & p2
    proof = stmt.prove()
    assert stmt.verify(proof)
Example #8
0
def test_randomize():
    params = setup()
    sk, pk = keygen(params)

    from petlib.bn import Bn
    from hashlib import sha256

    m = Bn.from_binary(sha256("Hello World!").digest())
    signature = sign(params, sk, m)

    signature = randomize(params, signature)

    assert verify(params, pk, m, signature)

    m2 = Bn.from_binary(sha256("Other Hello World!").digest())
    assert not verify(params, pk, m2, signature)
Example #9
0
    def __init__(self, name, ip, port, prvk, cascade=1, layered=1):
        print "Mix: init", name, ip, port, prvk, cascade, layered

        #Mix initialization
        self.name = name  # Name of the mix
        self.port = port  # Port of the mix
        self.ip = ip  # IP of the mix

        #Mix keys
        self.G = EcGroup(713)
        self.o = self.G.order()
        self.g = self.G.generator()
        self.o_bytes = int(
            math.ceil(math.log(float(int(self.o))) / math.log(256)))
        self.s = (self.G, self.o, self.g, self.o_bytes)
        self.prvk = Bn.from_binary(
            base64.b64decode(
                "/m8A5kOfWNhP4BMcUm7DF0/G0/TBs2YH8KAYzQ=="))  #mix private key
        self.pubk = self.prvk * self.g  #mix public key
        self.setup = (self.G, self.o, self.g, self.o_bytes, self.prvk,
                      self.pubk)

        self.sessions = {}  # Eviction session
        self.sessionlock = threading.Lock(
        )  #lock for accessing any information
Example #10
0
def enc(pub, plaintext):
    """Naive RSA encryption"""
    e, m = pub
    plain = Bn.from_binary(plaintext)
    assert 1 < plain < m
    cipher = pow(plain, e, m)
    return cipher.binary()
Example #11
0
    def get_prover(self, secrets_dict=None):
        """
        Get a prover for the current proof statement.

        Args:
            secrets_dict: Optional mapping from secrets or secret names to their values.

        Returns:
            :py:class:`DLRepProver` or None: Prover object if all secret values are known.
        """
        if secrets_dict is None:
            secrets_dict = {}

        # First we update the dictionary we have with the additional secrets, and process it
        self.secret_values.update(secrets_dict)
        secrets_dict = self.secret_values
        # If missing secrets or simulation parameter set, return now
        if (self.set_simulated() or secrets_dict == {}
                or any(sec not in secrets_dict.keys()
                       for sec in set(self.secret_vars))):
            # TODO: Make this raise:
            # raise IncompleteValuesError(self.secret_vars)
            return None

        # We check everything is indeed a big number, else we cast it
        for name, sec in secrets_dict.items():
            if not isinstance(sec, Bn):
                secrets_dict[name] = Bn(sec)

        return DLRepProver(self, secrets_dict)
Example #12
0
    def CommitG1(self, x):
        try:
            ttype = x["type"]
            if ttype == "unt":
                return self.G1unt()
            elif ttype == "bas":
                return self.G1bas()

            value = x["value"]

            if type(value) == G1Elem:
                if ttype == "pub":
                    return self.G1pub(value)
                elif ttype == "enc":
                    return self.G1enc(value)
                elif ttype == "com":
                    return self.G1com(value)

            if type(value) == Bn or type(value) == int:
                if type(value) == int:
                    value = Bn(value)
                if ttype == "sca":
                    return self.G1sca(value)

        except Exception as e:
            print("Error G1 commit", e)
Example #13
0
def BL_check_signature(params, issuer_pub, signature, db, keys):
    (_, q, g, h, z, _) = params
    (y_issuer, ) = issuer_pub
    (m, zet, zet1, zet2, om, omp, ro, ro1p, ro2p, mu) = signature

    #load this service's public key
    y_verifier = keys[1]

    if y_issuer != y_verifier:
        print "This verifier didn't issue this key"
        return False

    lhs = (om + omp) % q
    rhs_h = [
        zet, zet1, ro * g + om * y_verifier, ro1p * g + omp * zet1,
        ro2p * h + omp * zet2, mu * z + omp * zet
    ]

    Hstr = list(map(EcPt.export, rhs_h)) + [m]
    Hhex = b"|".join(map(b64encode, Hstr))
    rhs = Bn.from_binary(sha256(Hhex).digest()) % q

    #Check the database to see if this hash already exists!
    coinExists = database.checkDB_coinExists(rhs, db)

    if rhs == lhs and coinExists == False:
        database.insert2DB_Coin(rhs, db)
        return m
    else:
        return False
Example #14
0
    def prove_knowledge(self, pparam, prand, values):
        """ A non-interactive proof of knowledge of opening an commitment.

        Args:
            pparam (CommitPram): prameters
            prand (PedersenRand): commitment's secret
            values (Bn[]): commitment's values

        Returns:
            (PedersenProof)
        """
        # sigma protocol's commitment phase
        r_h = pparam.q.random()
        r_vs = [pparam.q.random() for _ in range(len(values))]
        R = r_h * pparam.H
        R += pparam.group.wsum(r_vs, pparam.HS[:len(r_vs)])

        # sigma protocol's challenge: Fiat-Shamir
        chash = sha256(self.commit.export() + R.export()).digest()
        e = Bn.from_binary(chash) % pparam.q

        # sigma protocol's response phase
        s_h = r_h - prand * e
        s_vs = [r - x * e for (x, r) in zip(values, r_vs)]
        return PedersenProof(e, (s_h, s_vs))
Example #15
0
def BL_user_validation(user_state, issuer_pub, msg_to_user, message=b''):
    (G, q, g, h, z, hs) = user_state.params
    # (z1, gam, zet, zet1, zet2, tau, eta) = user_private_state
    (a, a1p, a2p) = msg_to_user
    (y, ) = issuer_pub

    assert G.check_point(a)
    assert G.check_point(a1p)
    assert G.check_point(a2p)

    t1, t2, t3, t4, t5 = [q.random() for _ in range(5)]
    alph = a + t1 * g + t2 * y
    alph1 = user_state.gam * a1p + t3 * g + t4 * user_state.zet1
    alph2 = user_state.gam * a2p + t5 * h + t4 * user_state.zet2

    # Make epsilon
    H = [user_state.zet, user_state.zet1, alph, alph1, alph2, user_state.eta]
    Hstr = list(map(EcPt.export, H)) + [message]
    Hhex = b"|".join(map(b64encode, Hstr))
    epsilon = Bn.from_binary(sha256(Hhex).digest()) % q

    e = epsilon.mod_sub(t2, q).mod_sub(t4, q)

    user_state.ts = [t1, t2, t3, t4, t5]
    user_state.message = message

    msg_to_issuer = e
    return msg_to_issuer
Example #16
0
def BL_user_validation(user_state, idp_pub, msg_to_user, message=b''):
    (G, q, g, h, z, hs) = user_state.params
     # (z1, gam, zet, zet1, zet2, tau, eta) = user_private_state
    (a, a1p, a2p) = msg_to_user
    (y,) = idp_pub

    assert G.check_point(a)
    assert G.check_point(a1p)
    assert G.check_point(a2p)

    t1,t2,t3,t4,t5 = [q.random() for _ in range(5)]
    alph = a + t1 * g + t2 * y
    alph1 = user_state.gam * a1p + t3 * g + t4 * user_state.zet1
    alph2 = user_state.gam * a2p + t5 * h + t4 * user_state.zet2

    # Make epsilon
    H = [user_state.zet, user_state.zet1, alph, alph1, alph2, user_state.eta]
    Hstr = list(map(EcPt.export, H)) + [message]
    Hhex = b"|".join(map(b64encode, Hstr))
    epsilon = Bn.from_binary(sha256(Hhex).digest()) % q

    e = epsilon.mod_sub(t2,q).mod_sub(t4, q)

    user_state.ts = [t1, t2, t3, t4, t5]
    user_state.message = message

    msg_to_issuer = e
    return msg_to_issuer
Example #17
0
def cred_show_check(params, publics, secrets, creds, sig, cred_show_proof=cred_show_proof, xenv={}):

    # Parse the inputs
    G, g, h, _ = params
    sk, _ = secrets
    Cx0, iparams = publics
    (u, Cmis, Cup) = creds

    n = len(iparams)

    ## Recompute a V
    V = sk[0] * u + (- Cup)
    for xi, Cmi in zip(sk[1:], Cmis):
        V = V + xi * Cmi

    # Define the proof, and instanciate it with variables
    zk = cred_show_proof(params, n)

    env = ZKEnv(zk)
    env.u = u
    env.g, env.h = g, h
    env.V = V
    env.minus1 = -Bn(1)

    env.Xi = iparams
    env.Cmi = Cmis

    if xenv:
        xenv(env)

    # Return the result of the verification
    return zk.verify_proof(env.get(), sig)
Example #18
0
def test_range_proof_big_range():
    x = Secret(value=7)
    lo = 0
    hi = Bn(2) ** 65
    stmt = RangeOnlyStmt(lo, hi, x)
    nizk = stmt.prove()
    assert stmt.verify(nizk) == True
Example #19
0
def point_scalar_multiplication_double_and_add(a, b, p, x, y, scalar):
    """
    Implement Point multiplication with a scalar:
        r * (x, y) = (x, y) + ... + (x, y)    (r times)

    Reminder of Double and Multiply algorithm: r * P
        Q = infinity
        for i = 0 to num_bits(P)-1
            if bit i of r == 1 then
                Q = Q + P
            P = 2 * P
        return Q

    """
    assert Bn.is_prime(p)
    Q = (None, None)
    P = (x, y)

    for i in range(scalar.num_bits()):
        if scalar.is_bit_set(i):
            Q = point_add(a, b, p, P[0], P[1], Q[0], Q[1])
        else:
            # Wasteful point addition, added to prevent side channel attack
            W = point_add(a, b, p, P[0], P[1], Q[0], Q[1])
        P = point_double(a, b, p, P[0], P[1])
    return Q
Example #20
0
def create_tumbler_checker(inputs, reference_inputs, parameters, outputs, returns, dependencies):
    try:
        # retrieve ID list
        spent_list = loads(outputs[1])
        # retrieve vvk & sig
        packed_vvk = spent_list['vvk']
        sig = pet_unpack(parameters[0])

        # check format
        if len(inputs) != 1 or len(reference_inputs) != 0 or len(outputs) != 2 or len(returns) != 0:
            return False 

        # check types
        if loads(inputs[0])['type'] != 'TToken' or loads(outputs[0])['type'] != 'TToken': return False
        if spent_list['type'] != 'TList': return False

        # verify that the spent list is empty
        if spent_list['list']: return False

        # verify signature
        bp_params = bp_setup()
        hasher = sha256()
        hasher.update(outputs[1].encode('utf8'))
        m = Bn.from_binary(hasher.digest())
        vvk = (unpackG2(bp_params,packed_vvk[0]), unpackG2(bp_params,packed_vvk[1]), unpackG2(bp_params,packed_vvk[2]))
        if not verify(bp_params, vvk, m, sig): return False

        # otherwise
        return True

    except (KeyError, Exception):
        return False
Example #21
0
	def enc(self, params, pub, m):
		"""Encrypts the values of a group element"""
		print("CCA2EG: Enc")
		G, g1, o = params

		r1 = o.random()
		r2 = o.random()
		c11 = r1 * pub[0] + m
		c21 = r2 * pub[1] + m
		c12 = r1 * g1
		c22 = r2 * g1

		d = o.random() * g1
		s1 = o.random()
		s2 = o.random()
		e11 = s1 * pub[0] + d
		e21 = s2 * pub[1] + d
		e12 = s1 * g1
		e22 = s2 * g1

		state = [g1, pub[0], pub[1], c11, c21, c12, c22, e11, e21, e12, e22]
		hash_c = self.challenge(state)
		c = Bn.from_binary(hash_c) % o
		z = c*m +d
		z1 = (r1 * c + s1) % o
		z2 = (r2 * c + s2) % o

		return ((c11, c12), (c21, c22), (e11, e12), (e21, e22), c, z, z1, z2)
Example #22
0
    def CommitG2(self, y):
        try:
            ttype = y["type"]

            if ttype == "bas":
                return self.G2bas()
            elif ttype == "unt":
                return self.G2unt()

            value = y["value"]

            if type(value) == G2Elem:
                if ttype == "pub":
                    return self.G2pub(value)
                elif ttype == "enc":
                    return self.G2enc(value)
                elif ttype == "com":
                    return self.G2com(value)

            if type(value) == Bn or type(value) == int:
                if type(value) == int:
                    value = Bn(value)
                if ttype == "sca":
                    return self.G2sca(value)

        except Exception as e:
            print("Error G2 commit", e)
Example #23
0
def dec(pub, priv, ciphertext):
    """Naive RSA decryption. NOT const. time."""
    _, m = pub
    d, = priv
    cipher = Bn.from_binary(ciphertext)
    assert 1 < cipher < m
    plain = pow(cipher, d, m)
    return plain.binary()
Example #24
0
 def keygen(self, p):
     # 调用petlib.bn中的Bn,生成(0,p)的随机数,作为私钥sk
     self.x = Bn().from_decimal(str(self.p)).random()
     # 将私钥x与g2做标量乘法,得到公钥X
     self.X = self.x * self.g2
     sk = (self.x)
     vk = (self.X)
     return sk, vk
Example #25
0
    def from_roots_opt(roots, modulo):
        """
                Calculate polynomial from roots, optimally

                Example:
                    >>> a = Polynomial.from_roots_opt([Bn.from_num(1), Bn.from_num(1)], Bn.from_num(7))
                    >>> a.eval(1)
                    0

                    >>> a = Polynomial.from_roots_opt([1, 2, 3, 3, 4, 5], Bn.from_num(7))
                    >>> a.coefficients
                    [3, 3, 4, 3, 4, 3, 1]
                    >>> a.eval(3)
                    0
                    >>> a.eval(5)
                    0
                    >>> a.eval(6)
                    3
                    >>> order = Bn.from_decimal("52137169930799554717614356857506293818498877974737694294258188871929297414763123103907744062376810056827189091305705434921846346757741920691072816664704800302679217118985586829201265273391676324053123901757229727135241424267879269925766038354395247471758947327023181961662857375240340094119735806654078071568415490759313899749642836086369437285822445537863499850137938649445050574793896418443324129366783154447555359885480360150449533448644540185781810834062108093885074870413486811350157518533438291933078172819638193255100503198570696887787567964374981238663391668092217407521167528524716096503249760795640678745829")
                    >>> roots = [Bn.from_decimal('24328626682289136570751536147321521934883276496444403637200791710959330225351187858816284221467749949170967552592192324486105274675745073644298833869379510880054061897691638487850358168087009962101666739301242027780261176000688299869458451077243785452946211728488732020837306283402441986288004713904032620106051702880664181957060410226643578290964003019109479261826859822942513350862756778747973875209750342357933539552875979843312957639435564366361012366291495216191958522420513908595748516389774971404368853339932587005401457667821996489027145786706555858193202229433265835452932244580820310037045608574782179678733') for _ in range(4)]
                    >>> big_poly = Polynomial.from_roots_opt(roots, order)
                    >>> big_poly.eval(roots[0])
                    0

                    >>> Polynomial.from_roots_opt([1, 2, 3, 3, 4, 5], Bn.from_num(1000)).coefficients
                    [360, 58, 949, 520, 130, 982, 1]
                """
        if type(modulo) == int:
            modulo = Bn.from_num(modulo)
        if type(roots[0]) == int:
            roots = [Bn.from_num(a) for a in roots]

        degree_poly = len(roots)
        polynomial = [0] * degree_poly
        polynomial[0] = 1
        for i in range(degree_poly):
            new_poly = []
            new_poly.append((-polynomial[0] * roots[i]).mod(modulo))
            for j in range(1, i + 1):
                new_poly.append(
                    (-polynomial[j] * roots[i] + polynomial[j - 1]).mod(modulo)
                )
            new_poly.append(1)
            polynomial = new_poly

        return Polynomial(polynomial, modulo)
Example #26
0
def sum_bn_array(arr, modulus):
    """
    Sum an array of big numbers under a modulus.

    >>> a = [Bn(5), Bn(7)]
    >>> m = 10
    >>> sum_bn_array(a, m)
    2
    """
    if not isinstance(modulus, Bn):
        modulus = Bn(modulus)
    res = Bn(0)
    for elem in arr:
        if not isinstance(elem, Bn):
            elem = Bn(elem)
        res = res.mod_add(elem, modulus)
    return res
Example #27
0
 def sign(self, sk, m):
     # 输入类型检测,要求m属于Zp
     try:
         m = Bn.from_decimal(str(m))
         if m < 0 or m > self.p:  # if not a positive int print message and ask for input again
             print(
                 "m is out of range, please ensure m to be an integer in [0,p)"
             )
     except ValueError:
         print("m is not an int, please ensure m to be an integer in [0,p)")
     # 把这个整数类型的信息m转化为字符串类型,便于使用hashG1函数
     # while语句使得x + m != 0
     if self.x + m == 0:
         print("x有问题")
     theta = (Bn.from_decimal(str(self.x + m)).mod_inverse(self.G.order()) *
              self.g1)
     return theta
Example #28
0
    def __init__(self, arch, enc, el1, el2, el3, el4, ports):
	print("CF: init")
	self.done = Deferred()
	self.c_proto = None
	
	self.G = EcGroup(713)
	self.o = self.G.order()
	self.g = self.G.generator()
	self.o_bytes = int(math.ceil(math.log(float(int(self.o))) / math.log(256)))
	self.data = ["STT", int(urandom(2).encode('hex'),16), [ Actor("DB", "127.0.0.1", 8000, ""), 3]]
	if arch:
	    if enc:
		self.data[2].extend([["", Bn.from_binary(base64.b64decode(el2))]])
		
	    else:
		self.data[2].extend([[Bn.from_binary(base64.b64decode(el2)), Bn.from_binary(base64.b64decode(el2))]])
	else:
	    if enc:
		self.data[2].extend([["", Bn.from_binary(base64.b64decode(el2))],[["", Bn.from_binary(base64.b64decode(el4))]]])
	    else:
		self.data[2].extend([ [Bn.from_binary(base64.b64decode(el1)), Bn.from_binary(base64.b64decode(el2))], [Bn.from_binary(base64.b64decode(el3)), Bn.from_binary(base64.b64decode(el4))]])
	actors=[]
	for i in range(len(ports)):
		    actors.extend([Actor("M"+str(i), "127.0.0.1", 8001+i, "")])
	self.data[2].extend([[actors]])
Example #29
0
def proof_pkuv(gsp, X, Y):
    res = []
    B = []
    A = []
    C = []
    for i in range(len(X)):
        row = []
        for j in range(len(Y)):
            row.append(Bn(0))
        C.append(row)
    C[6][0] = Bn(1)  # pk_uv
    C[5][1] = Bn(-1)  # - h_v^sku
    success, result = gsp.Prove_aggreg("MC1", X, B, A, Y, C, G1Elem.inf(gsp.G))
    verify = 0
    if success:
        eq_type, X, Y, C, T_eq, pi2_v1, pi2_w1, pi1_v2, pi1_w2 = result
        #verify = gsp.Verify(eq_type, X, Y, C, pi2_v1, pi2_w1, pi1_v2, pi1_w2)
        #if verify:
        res = [C, [pi2_v1, pi2_w1, pi1_v2, pi1_w2]]
    #print("Do we successfully create a proof?", success)
    #print("Does the proof successfully verify?", verify)

    print("\n----pk uv")
    for i in range(len(res[1])):
        for j in range(2):
            if type(res[1][i][j]) == G1Elem:
                print(i, j, type(res[1][i][j]),
                      res[1][i][j].eq(G1Elem.inf(gsp.G)))
            else:
                print(i, j, type(res[1][i][j]),
                      res[1][i][j].eq(G2Elem.inf(gsp.G)))

    b = challenge(result)
    for i in range(len(res[0])):
        for j in range(len(res[0][0])):
            if res[0][i][j] != 0:
                res[0][i][j] = b * res[0][i][j]
    for i in range(len(res[1])):
        for j in range(len(res[1][i])):
            res[1][i][j] = b * res[1][i][j]

    #verify = gsp.Verify("ME1", X, Y, C, res[1][0], res[1][1], res[1][2], res[1][3])
    #print("Does the (aggregate) proof verify?", verify)

    return res
Example #30
0
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 challenge(self, elements):
     """Packages a challenge in a bijective way"""
     elem = [len(elements)] + elements
     elem_str = map(str, elem)
     elem_len = map(lambda x: "%s||%s" % (len(x), x), elem_str)
     state = "|".join(elem_len)
     H = sha256()
     H.update(state.encode("utf8"))
     return Bn.from_binary(H.digest()) % self.o
Example #32
0
def challenge(elements):
    """Packages a challenge in a bijective way"""
    elem = [len(elements)] + elements
    elem_str = list(map(str, elem))
    elem_len = list(map(lambda x: "%s||%s" % (len(x) , x), elem_str))
    state = "|".join(elem_len)
    H = sha256()
    H.update(state.encode("utf8"))
    return Bn.from_binary(H.digest())
Example #33
0
def test_sign():
    params = setup()
    sk, pk = keygen(params)

    from petlib.bn import Bn
    from hashlib import sha256

    m = Bn.from_binary(sha256("Hello World!").digest())
    sign(params, sk, m)
Example #34
0
 def sign(self, sk, m):
     # 输入类型检测,要求m属于Zp
     try:
         m = Bn.from_decimal(str(m))
         if m < 0 or m > self.p:  # if not a positive int print message and ask for input again
             print(
                 "m is out of range, please ensure m to be an integer in [0,p)"
             )
     except ValueError:
         print("m is not an int, please ensure m to be an integer in [0,p)")
     # while语句使得x + r*y + m != 0
     while self.x + self.r * self.y + m == 0:
         self.r = Bn().from_decimal(str(self.p)).random()
     self.theta_prime = (Bn.from_decimal(
         str(self.x + self.r * self.y + m)).mod_inverse(
             self.G.order())) * self.g1
     theta = (self.theta_prime, self.r)
     return theta
Example #35
0
def verify(params, h, g, proof, m=""):
    """Verify the statement ZK(x ; h = g^x)"""
    G, _, o = params
    c, r = proof
    W = (r * g + c * h)

    state = ['schnorr', G.nid(), g, h, m, W]
    hash_c = challenge(state)
    c2 = Bn.from_binary(hash_c) % o
    return c == c2
Example #36
0
 def __init__(self, key_bytes, public=True):
     """ Make a key given a public or private key in bytes """
     self.G = _globalECG
     if public:
         self.sec = None
         self.pub = EcPt.from_binary(key_bytes, self.G)
         self.optim = None
     else:
         self.sec = Bn.from_binary(sha256(key_bytes).digest())
         self.pub = self.sec * self.G.generator()
         self.optim = do_ecdsa_setup(self.G, self.sec)
Example #37
0
def mix_operate(message, triplet, setup):
    mname, mpub, msec = triplet
    elem, forward, backwards = message
    G, o, g, o_bytes = setup

    aes = Cipher("AES-128-CTR")

    # Derive first key
    k1 = KDF((msec * elem).export())

    # Derive the blinding factor
    b = Bn.from_binary(k1.b) % o
    new_elem = b * elem

    # Check the forward MAC
    mac1 = hmac.new(k1.kmac, forward[20:], digestmod=sha1).digest()
    assert forward[:20] == mac1

    # Decrypt the payload
    enc = aes.dec(k1.kenc, k1.iv)        
    pt = enc.update(forward[20:])
    pt += enc.finalize()

    # Parse the forward message
    xfrom, xto, the_bs, new_forw = pt[:4], pt[4:8], pt[8:8+o_bytes], pt[8+o_bytes:]
    old_bs = Bn.from_binary(the_bs)

    # Now encrypt the return part
    k2 = KDF(((msec * old_bs) * elem).export())


    new_bs = old_bs.mod_inverse(o).binary()
        
    enc = aes.enc(k2.kenc, k2.iv)
    new_back_body = enc.update(xto + xfrom + new_bs + backwards)
    new_back_body += enc.finalize()
    mac2 = hmac.new(k2.kmac, new_back_body, digestmod=sha1).digest()

    new_back = mac2 + new_back_body

    return ((xfrom, xto), (new_elem, new_forw, new_back) )
Example #38
0
def prove(params, h, g, x, m=""):
    """Schnorr proof of the statement ZK(x ; h = g^x)"""
    assert x * g == h
    G, _, o = params
    w = o.random()
    W = w * g

    state = ['schnorr', G.nid(), g, h, m, W]
    hash_c = challenge(state)
    c = Bn.from_binary(hash_c) % o
    r = (w - c * x) % o
    return (c, r)
Example #39
0
def ext_hook(code, data):

    if code==0:
        num = Bn.from_binary(data[1:])
        if data[0] == ord("-") or data[0] == "-":
            return -num
        return num
    elif code==1:
        nid = msgpack.unpackb(data)
        return EcGroup(nid)
    elif code == 2:
        nid, ptdata = msgpack.unpackb(data)
        return EcPt.from_binary(ptdata, EcGroup(nid))
    return msgpack.ExtType(code, data)
Example #40
0
    def build_proof(self, env, message=""):
        """Generates a proof within an environment of assigned public and secret variables."""

        self._check_env(env)

        # Do sanity check on the proofs
        if __debug__:
            for base, expr in self.proofs:
                xGen = base.val(env)
                xExpr = expr.val(env)
                try:
                    assert xGen == xExpr
                except:
                    raise Exception("Proof about '%s' does not hold." % base.name)

        G = self.G
        order = G.order()

        ## Make a list of all the public state
        state = ['ZKP', G.nid(), message]

        for v in sorted(self.Const.keys()):
            state += [env[v]]
        for v in sorted(self.Pub.keys()):
            state += [env[v]]

        ## Set witnesses for all secrets
        witnesses = dict(env.items())
        for w in self.Sec.keys():
            assert w in witnesses
            witnesses[w] = order.random()

        ## Compute the first message and add it to the state
        for base, expr in self.proofs:
            Cw = expr.val(witnesses)
            state += [Cw]

        ## Compute the challenge using all the state
        hash_c = challenge(state)
        c = Bn.from_binary(hash_c) % order

        ## Compute all the resources
        responses = dict(env.items())
        for w in self.Sec.keys():
            responses[w] = (witnesses[w] - c * env[w]) % order
         
        for v in self.Const:
           del responses[v]

        return (c, responses)
Example #41
0
def BL_check_signature(params, issuer_pub, signature):
    (G, q, g, h, z, hs) = params
    (y,) = issuer_pub
    (m, zet, zet1, zet2, om, omp, ro, ro1p, ro2p, mu) = signature

    lhs = (om + omp) % q
    rhs_h = [zet, zet1,
             ro * g + om * y,
             ro1p * g + omp * zet1,
             ro2p * h + omp * zet2,  ## problem
             mu * z + omp * zet]

    Hstr = list(map(EcPt.export, rhs_h)) + [m]
    Hhex = b"|".join(map(b64encode, Hstr))
    rhs = Bn.from_binary(sha256(Hhex).digest()) % q

    if rhs == lhs:
        return m
    else:
        return False
Example #42
0
    def verify_proof(self, env, sig, message="", strict=True):
        """Verifies a proof within an environment of assigned public only variables."""

        ## Select the constants for the env
        env_l = [(k,v) for  k,v in env.items() if k in self.Const]
        
        if __debug__ and strict:
            env_not = [k for k,v in env.items() if k not in self.Const]
            if len(env_not):
                raise Exception("Did not check: " + (", ".join(env_not)))

        c, responses = sig
        responses = dict(list(responses.items()) + env_l)

        ## Ensure all variables we need are here
        self._check_env(responses)

        ## Define the maths group we work in
        G = self.G
        order = G.order()

        ## Make a list of all the public state
        state = ['ZKP', G.nid(), message]
        for v in sorted(self.Const.keys()):
            state += [responses[v]]
        for v in sorted(self.Pub.keys()):
            state += [responses[v]]

        ## Compute the first message and add it to the state
        for base, expr in self.proofs:
            Cr = expr.val(responses)
            Cx = base.val(responses)
            Cw = Cr + c * Cx
            state += [Cw]
         
        ## Compute the challenge using all the state
        hash_c = challenge(state)
        c_prime = Bn.from_binary(hash_c) % order

        ## Check equality
        return (c == c_prime)
Example #43
0
def BL_verify_age(params, issuer_pub, num_attributes, signature, sig, gam_hs, zet1p, gam_g):
    m = BL_check_signature(params, issuer_pub, signature)
    assert m != False

    (G, q, g, h, z, hs) = params
    (m, zet, zet1, zet2, om, omp, ro, ro1p, ro2p, mu) = signature

    zk = BL_show_zk_proof(params, num_attributes) #we get this from the user

    env = ZKEnv(zk)

    # Constants
    env.g = g
    env.z = z
    env.zet = zet
    env.zet1 = zet1p
    env.hs = gam_hs[:num_attributes + 1]

    ## Extract the proof
    res = zk.verify_proof(env.get(), sig)
    assert res

    lhs = (om + omp) % q
    rhs_h = [zet, zet1,
             ro * g + om * y,
             ro1p * g + omp * zet1,
             ro2p * h + omp * zet2,  ## problem
             mu * z + omp * zet]

    Hstr = list(map(EcPt.export, rhs_h)) + [m]
    Hhex = b"|".join(map(b64encode, Hstr))
    rhs = Bn.from_binary(sha256(Hhex).digest()) % q

    # Check the (future) ZK proof
    # assert rnd * gam_g + R * gam_hs[0] + L1 * gam_hs[1] + L2 * gam_hs[2] == zet1
    assert rnd * gam_g + R * gam_hs[0] + L1 * gam_hs[1] == zet1 - Age * gam_hs[2]

    return m
Example #44
0
def VerifyOneOfN(ck, cis, proof, message = ""):
    """ Verify the ring signature on message """

    n = int(math.ceil(math.log(len(cis)) / math.log(2)))
    (G, g, h, o) = ck

    (Celi, Cai, Cbi, cdi, fi, zai, zbi, zd) = proof

    ## Check all parts of the proof are in the right groups
    assert 0 <= zd < o
    for k in range(n):
        assert 0 <= fi[k] < o
        assert 0 <= zai[k] < o
        assert 0 <= zbi[k] < o
        
        assert G.check_point(Celi[k])
        assert G.check_point(Cai[k])
        assert G.check_point(Cbi[k])
        assert G.check_point(cdi[k])

    # Recompute the challenge
    x = challenge(list(ck) + cis + Celi + Cai + Cbi + cdi + [ message ])


    ret = True

    for i in range(n):
        ret &= x * Celi[i] + Cai[i] == Com(ck, fi[i], zai[i])
        ret &= (x - fi[i]) * Celi[i] + Cbi[i] == Com(ck, Bn(0), zbi[i])

    # acc = G.infinite()

    bases = []
    expons = []

    for idx, ci in enumerate(cis):
        idx = Bn(idx)
        idxi = [Bn(int(idx.is_bit_set(i))) for i in range(n)]

        acc_exp = Bn(1)
        for k, ij in enumerate(idxi):
            if ij == 0:
                acc_exp = acc_exp.mod_mul(x - fi[k], o)
            else:
                acc_exp = acc_exp.mod_mul(fi[k], o)

        bases += [ ci ]
        expons += [ acc_exp ]

        # acc = acc + acc_exp * ci

    for k in range(n):
        expi = (- pow(x,k,o))
        # acc = acc + expi * cdi[k]
        bases += [ cdi[k] ]
        expons += [ expi ]

    # assert G.wsum(expons, bases) == acc
    acc = G.wsum(expons, bases)

    ret &= acc == Com(ck, 0, zd)

    return ret
Example #45
0
def test_protocol():
    # Parameters of the BL schemes
    G = EcGroup(713)
    q = G.order()

    g = G.hash_to_point(b"g")
    h = G.hash_to_point(b"h")
    z = G.hash_to_point(b"z")
    hs = [G.hash_to_point(("h%s" % i).encode("utf8")) for i in range(100)]

    # Inputs from user
    R = q.random()
    L1 = 10
    L2 = 20 #age
    C = R * hs[0] + L1 * hs[1] + L2 * hs[2]
    m = b"Hello World!"

    # Inputs from the Issuer
    # TODO: check ZK on C
    x = q.random()
    y = x * g

    # Preparation
    rnd = q.random()
    z1 = C + rnd * g
    z2 = z + (-z1)

    ## Send: (rnd,) to user
    if rnd % q == 0:
        raise

    z1 = C + rnd * g
    gam = q.random()
    zet = gam * z
    zet1 = gam * z1
    zet2 = zet + (-zet1)
    tau = q.random()
    eta = tau * z

    # Validation: Issuer
    u, r1p, r2p, cp = [q.random() for _ in range(4)]
    a = u * g
    a1p = r1p * g + cp * z1
    a2p = r2p * h + cp * z2

    ## Send(a, ap = (a1p, a2p))
    # User side

    assert G.check_point(a)
    assert G.check_point(a1p)
    assert G.check_point(a2p)

    t1, t2, t3, t4, t5 = [q.random() for _ in range(5)]
    alph = a + t1 * g + t2 * y
    alph1 = gam * a1p + t3 * g + t4 * zet1
    alph2 = gam * a2p + t5 * h + t4 * zet2

    # Make epsilon
    H = [zet, zet1, alph, alph1, alph2, eta]
    Hstr = list(map(EcPt.export, H)) + [m]
    Hhex = b"|".join(map(b64encode, Hstr))
    epsilon = Bn.from_binary(sha256(Hhex).digest()) % q

    e = epsilon.mod_sub(t2, q).mod_sub(t4, q)

    ## Send: (e,) to Issuer
    c = e.mod_sub(cp, q)
    r = u.mod_sub((c * x), q)

    ## Send: (c,r, cp, rp = (r1p, r2p)) to User
    ro = r.mod_add(t1, q)
    om = c.mod_add(t2, q)
    ro1p = (gam * r1p + t3) % q
    ro2p = (gam * r2p + t5) % q
    omp = (cp + t4) % q
    mu = (tau - omp * gam) % q

    signature = (m, zet, zet1, zet2, om, omp, ro, ro1p, ro2p)

    gam_hs = [gam * hsi for hsi in hs]
    zet1p = zet1 - L2 * gam_hs[2]

    # Check verification equation
    lhs = (om + omp) % q
    rhs_h = [zet, zet1p,
             ro * g + om * y,
             ro1p * g + omp * zet1p,
             ro2p * h + omp * zet2,  ## problem
             mu * z + omp * zet]

    Hstr = list(map(EcPt.export, rhs_h)) + [m]
    Hhex = b"|".join(map(b64encode, Hstr))
    rhs = Bn.from_binary(sha256(Hhex).digest()) % q

    # Check the (future) ZK proof
    assert zet == gam * z
    gam_hs = [gam * hsi for hsi in hs]
    gam_g = gam * g
    #assert rnd * gam_g + R * gam_hs[0] + L1 * gam_hs[1] + L2 * gam_hs[2] == zet1
    assert rnd * gam_g + R * gam_hs[0] + L1 * gam_hs[1] == zet1 - L2 * gam_hs[2]

    print(rhs == lhs)
Example #46
0
def ProveOneOfN(ck, cis, el, r, message = ""):
    """ NIZK Proof that Com(0; r) is within Cis. 
        The fact that it is the el'th commitmtnet is not revealed. 
        + Ring signature on "message". """
    n = int(math.ceil(math.log(len(cis)) / math.log(2)))
    assert Com(ck, 0, r) == cis[el]
    (G, g, h, o) = ck

    ## Commit to the bits of the index
    el = Bn(el)
    eli = [Bn(int(el.is_bit_set(i))) for i in range(n)]
    
    ri  = [o.random() for i in range(n)]
    ai  = [o.random() for i in range(n)]
    si  = [o.random() for i in range(n)]
    ti  = [o.random() for i in range(n)]

    Celi = [Com(ck, elix, rix) for elix, rix in zip(eli, ri)]
    Cai = [Com(ck, a, s) for a, s in zip(ai, si)]
    Cbi = [Com(ck, l * a , s) for l, a, s in zip(eli, ai, ti)]

    # Compute p_idxi(x)
    p_idx_i = []
    for idx in range(len(cis)):
        idx = Bn(idx)
        idxi = [Bn(int(idx.is_bit_set(i))) for i in range(n)]

        p = [Bn(1)]
        for j, idxi_j in enumerate(idxi):
            if idxi_j == 0:
                p = poly_mul(o, p, [ -ai[j] , - eli[j] + 1] )
            else:
                p = poly_mul(o, p, [ ai[j] , eli[j] ])

        p_idx_i += [p]
        
    # Compute all Cdi's
    roi = []
    cdi = []
    for i in range(n):
        roi_i = o.random()
        roi += [ roi_i ]
        # cdi_i = Com(ck, 0, roi_i)

        wis = []

        for idx, cidx in enumerate(cis):
            wis += [ p_idx_i[idx][i] ]
            # cdi_i += p_idx_i[idx][i] * cidx

        # assert G.wsum(wis, cis) + Com(ck, 0, roi_i) == cdi_i
        cdi_i = G.wsum(wis, cis) + Com(ck, 0, roi_i)

        cdi += [ cdi_i ]

    ## The challenge
    x = challenge(list(ck) + cis + Celi + Cai + Cbi + cdi + [ message ])

    ## The responses
    fi = [(elj * x + aj) % o for elj, aj in zip(eli, ai)]
    zai = [(rj * x + sj) % o for rj, sj in zip(ri, si)]
    zbi = [(rj * (x - fj) + tj) % o for rj, fj, tj in zip(ri, fi, ti)]

    zd = r * pow(x, n, o) % o
    for k in range(n):
        zd = (zd - roi[k] * pow(x, k, o)) % o

    proof = (Celi, Cai, Cbi, cdi, fi, zai, zbi, zd)

    return proof
Example #47
0
def mix_operate(message, triplet, setup, generate_return_message=False):
    ''' Operate a Mix with a received message, and its keys. '''


    mname, mpub, msec = triplet
    elem, forward, backwards = message
    G, o, g, o_bytes = setup

    aes = Cipher("AES-128-CTR")

    # Derive first key
    k1 = KDF((msec * elem).export())

    # Derive the blinding factor
    b = Bn.from_binary(k1.b) % o
    new_elem = b * elem

    # Check the forward MAC
    mac1 = hmac.new(k1.kmac, forward[20:], digestmod=sha1).digest()
    if not (forward[:20] == mac1):
        raise Exception("Wrong MAC1")

    # Decrypt the payload
    enc = aes.dec(k1.kenc, k1.iv)        
    pt = enc.update(forward[20:])
    pt += enc.finalize()

    # Parse the forward message
    xcode = pt[0]
    if not (xcode == "0" or xcode == "1"):
        raise Exception("Wrong routing code")

    pt = pt[1:]

    if xcode == "0":

        xfrom, xto, the_bs, new_forw = pt[:4], pt[4:8], pt[8:8+o_bytes], pt[8+o_bytes:]
        old_bs = Bn.from_binary(the_bs)

        # Now package the return part
        k2 = KDF(((msec * old_bs) * elem).export())
            
        enc = aes.enc(k2.kenc, k2.iv)
        new_back_body = enc.update("1" + xto + xfrom + backwards)
        new_back_body += enc.finalize()
        mac2 = hmac.new(k2.kmac, new_back_body, digestmod=sha1).digest()

        new_back = mac2 + new_back_body

        if generate_return_message:
            ret_elem = old_bs * elem
            ret_forw = new_back
            ret_back = None
            
            return ((xto, xfrom), (ret_elem, ret_forw, ret_back) )            

    else:

        xfrom, xto, new_forw = pt[:4], pt[4:8], pt[8:]

        # Returns do not need to build returns
        if not (backwards == None):
            raise Exception("Backwards header should be None")

        new_back = None

    return ((xfrom, xto), (new_elem, new_forw, new_back) )
Example #48
0
def mix_package(sender, receiver, triplets):
    ''' Package a message through a mix-net. '''

    aes = Cipher("AES-128-CTR")

    Bs = []

    _, ypub, y = sender
    pubs = [ ypub ]

    round_trip = triplets + [ receiver ] + list(reversed(triplets))

    secrets = []
    prod_bs = Bn(1)
    for i, (mname, mpub, msec) in enumerate(round_trip):
        xysec2 = (y * prod_bs) * mpub
        secrets += [ xysec2 ]

        if __debug__ and msec is not None:
            xysec1 = (msec *  prod_bs) * ypub
            assert xysec2  == xysec1

        # Blinding factor
        k = KDF(xysec2.export())
        b = Bn.from_binary(k.b) % o
        Bs += [ b ]
        # y = (b * y) % o
        prod_bs = (b * prod_bs) % o
        #ypub = b * ypub
        pubs += [ prod_bs * ypub ]

    # Precompute the correction factors
    correction_factors = []
    for i in range(len(triplets)):
        
        total_b = Bn(1)
        for j in range(i, 2 * len(triplets) - i):
            total_b = (total_b * Bs[j]) % o

        assert round_trip[i][0] ==  round_trip[2 * len(triplets) - i][0]
        assert total_b * pubs[i] == pubs[2 * len(triplets) - i]

        correction_factors += [ total_b ]

    all_factors = [] + correction_factors
    all_factors += [ Bn(1) ]
    all_factors += [bf.mod_inverse(o) for bf in reversed(correction_factors)]
    assert len(all_factors) == len(round_trip)

    # Generate data stream
    data = [ sender ] + round_trip + [ sender ]
    addressing = []
    for i, _ in enumerate(round_trip):
        addressing += [(data[1 + i-1][0], data[1 + i+1][0])]

    # Derive all keys
    all_data = zip(round_trip, all_factors, pubs, addressing, secrets) 
    all_keys = []
    for (mname, mpub, msec), bs, yelem, (xfrom, xto), Ksec in all_data:
        
        k1 = KDF(Ksec.export())
        k2 = KDF( (bs * Ksec).export())

        all_keys += [(k1, k2)]
        
    all_data = zip(round_trip, all_factors, pubs, addressing, all_keys) 

    # Build the backwards path
    prev = ''
    backwards_stages = [ ]
    for j in range(len(mix_names) + 1):
        (mname, mpub, msec), bs, yelem, (xfrom, xto), (k1, k2) = all_data[j]
        the_bs = bs.mod_inverse(o).binary()
        
        enc = aes.enc(k2.kenc, k2.iv)
        ciphertext = enc.update(xto + xfrom + the_bs + prev)
        ciphertext += enc.finalize()

        mac = hmac.new(k2.kmac, ciphertext, digestmod=sha1).digest()

        prev = mac + ciphertext
        backwards_stages += [ prev ]

    # Build the forwards path
    prev = ''
    forwards_stages = []
    for jp in range(len(mix_names) + 1):
        j = len(mix_names) - jp

        (mname, mpub, msec), bs, yelem, (xfrom, xto), (k1, k2) = all_data[j]
        the_bs = bs.binary()
        
        enc = aes.enc(k1.kenc, k1.iv)
        ciphertext = enc.update(xfrom + xto + the_bs + prev)
        ciphertext += enc.finalize()

        mac = hmac.new(k1.kmac, ciphertext, digestmod=sha1).digest()

        prev = mac + ciphertext
        forwards_stages += [ prev ]

    forwards_stages = list(reversed(forwards_stages))

    stages = zip(forwards_stages, backwards_stages)

    # Check all the MACs
    if __debug__:
        for j in range(len(mix_names) + 1):
            (msg_f, msg_b) = stages.pop(0)

            (mname, mpub, msec), bs, yelem, (xfrom, xto), (k1, k2) = all_data[j]
            
            mac1 = hmac.new(k1.kmac, msg_f[20:], digestmod=sha1).digest()
            assert msg_f[:20] == mac1

            enc = aes.dec(k1.kenc, k1.iv)        
            plaintext = enc.update(msg_f[20:])
            plaintext += enc.finalize()

            assert xfrom == plaintext[:4] and xto == plaintext[4:8]

            mac2 = hmac.new(k2.kmac, msg_b[20:], digestmod=sha1).digest()
            assert msg_b[:20] == mac2
    # End __debug__

    return zip(pubs[:len(mix_names) + 1], forwards_stages + [''], [''] + backwards_stages)
Example #49
0
def to_challenge(elements):
    """ Generates a Bn challenge by hashing a number of EC points """
    Cstring = b",".join([hexlify(x.export()) for x in elements])
    Chash =  sha256(Cstring).digest()
    return Bn.from_binary(Chash)
Example #50
0
    def _handle_client(self, client_reader, client_writer):

        global paramsReceived

        while True:
            try:  # data = (yield from client_reader.readline()).decode("utf-8")
                startWait = time.time()
                data = yield from client_reader.readuntil(separator=b'fireintheboof')
                endWait = time.time()
                print('IO wait: ', data[0:4], endWait - startWait)
                cmd = data[0:4]
                strippedData = data[4:-13]
            except asyncio.streams.IncompleteReadError:
                data = None
            if not data:  # an empty string means the client disconnected
                break
                # cmd, *args = str(data).rstrip().split(' ')
            if cmd == 'id':
                """secrets = [3, 645, 3430, 420]
                seriSecrets = pickle.dumps(secrets)
                params = setup()

                C, r = commit(params, secrets)
                G = params[0]

                exportedC = C.export()

                retval = 'IDCONFIRMED'

                #client_writer.write("{!r}\n".format(retval).encode("utf-8"))
                #Interesting asyncio thingy here, if I send the data to the client first, the proof is never correct
                #THe client completes and sends the proof to the service provider before the SP receives the C from here."""
                print(literal_eval(args[0]))
                print(type(literal_eval(args[0])))

                reader_sp, writer_sp = yield from asyncio.streams.open_connection("localhost", 12345, loop = loop)
                params = BL_setup()
                LT_idp_state, idp_pub = BL_idp_keys(params)
                #conv_user_commit = bytes(args[0], "utf8")
                #user_commit = encdec.decode(conv_user_commit)
                user_commit = encdec.decode(literal_eval(args[0]))
                msg_to_user = BL_idp_prep(LT_idp_state, user_commit)
            elif cmd == b'para':
                #reader_sp, writer_sp = yield from asyncio.streams.open_connection("localhost", 12345, loop=loop)
                start = time.time()
                paramsReceived = True
                print('Starting...')

                params = decode(strippedData)
                G, q, g, h, z, hs = params
                LT_idp_state, idp_pub = BL_idp_keys(params)


                #send public key to user and service provider

                #writer_sp.write(b'ipub' + encode(idp_pub) + b'fireintheboof')
                client_writer.write(b'mypb' + encode(idp_pub) + b'fireinthepub')


            elif cmd == b'ucmt':
                user_commit, C, c, responses, L2, Age = decode(strippedData)
                rR, rx = responses



                H = G.hash_to_point(b'service_name')
                ID = L2 * H

                Cprime = C - Age * hs[2]

                Wprime = rR * hs[0] + rx * hs[1] + c * Cprime

                Wxprime = rx * H + c * ID

                stuffToHash = (Wprime, Wxprime, C, g, h, z, hs[0], hs[1], hs[2], hs[3], H)
                cstr = b",".join([hexlify(x.export()) for x in stuffToHash])
                chash = sha256(cstr).digest()
                cprime = Bn.from_binary(chash)

                if c == cprime:
                    print("success")
                else:
                    print("no")





                #generate message to user
                msg_to_user = BL_idp_prep(LT_idp_state, user_commit)

                client_writer.write(encode(msg_to_user) + b'fireintheboof')

            elif cmd == b'prep':
                msg_to_user2 = BL_idp_validation(LT_idp_state)

                client_writer.write(encode(msg_to_user2) + b'fireintheboof')

            elif cmd == b'msgi':
                msg_to_idp = decode(strippedData)

                # generate 3rd message to user
                msg_to_user3 = BL_idp_validation_2(LT_idp_state, msg_to_idp)

                client_writer.write(encode(msg_to_user3) + b'fireintheboof')

                end = time.time()
                finalTime = end - start
                print('Total time taken: ', finalTime)

            else:
                #print("Bad command {!r}".format(data), file=sys.stderr)
                pass

            # This enables us to have flow control in our connection.
            yield from client_writer.drain()
Example #51
0
    def _handle_client(self, client_reader, client_writer):
        global count
        global paramsReceived
        IOtime = 0
        while True:
            try:#data = (yield from client_reader.readline()).decode("utf-8")
                startWait = time.time()
                data = yield from client_reader.readuntil(separator=b'fireintheboof')
                endWait = time.time()
                #print('IO wait: ', data[0:4], endWait - startWait)
                IOtime += endWait-startWait

                cmd = data[0:4]

                strippedData = data[4:-13]

            except asyncio.streams.IncompleteReadError:
                data = None
            if not data: # an empty string means the client disconnected
                break
            #cmd, *args = str(data).rstrip().split(' ')
            if cmd == b'buys':

                retval = "id"
                client_writer.write("{!r}\n".format(retval).encode("utf-8"))
                start = time.time()

                count +=1
                id = count

                print(id, 'Starting...')

            elif cmd == b'para':

                params = decode(strippedData)

                paramsReceived = True

            elif cmd == b'ipub':

                idp_pub = decode(strippedData)

            elif cmd == b'vsig':

                sig = decode(strippedData)

            elif cmd == b'vsg2':

                signature = decode(strippedData)
                startSigProof = time.time()
                m = BL_verify_cred(params, idp_pub, 2, sig, signature)
                endSigProof = time.time()
                finalSigProof = endSigProof - startSigProof

                if m != False:
                    print('Signature Correct')
                else:
                    print('Signature Incorrect')

            elif cmd == b'page':

                newStuff = decode(strippedData)
                c, responses, gam_g, gam_hs, Age, xran = newStuff
                rrnd, rR, rx = responses
                #print(gam_hs, Age)

                (G, q, g, h, z, hs) = params

                startProof = time.time()

                H = G.hash_to_point(b'service_name')
                ID = xran * H

                zet1 = sig[2]

                zet1p = zet1 - Age * gam_hs[2]

                Waprime = rrnd * gam_g + rR * gam_hs[0] + rx * gam_hs[1] + c * zet1p

                Wxprime = rx * H + c * ID

                stuffToHash = (gam_g, Waprime, Wxprime, zet1p, gam_hs[0], gam_hs[1], gam_hs[2], H)
                cstr = b",".join([hexlify(x.export()) for x in stuffToHash])
                chash = sha256(cstr).digest()
                c_prime = Bn.from_binary(chash)

                if c == c_prime:
                    end = time.time()
                    finalTime = end-start
                    timeList.append(finalTime)
                    print(id, "Age & User match, time: ", finalTime, 'Time for proof: ', end - startProof, 'Sig proof: ', finalSigProof, 'IO time: ', IOtime)
                else:
                    print("whops")


            elif cmd == 'Commitment':
                """params = setup()
                G = params[0]
                C = EcPt.from_binary(literal_eval(args[0]), G)"""
            elif cmd == 'Proof':

                """c = Bn.from_hex(literal_eval(args[0]))
                responses1 = pickle.loads(literal_eval(args[1]))
                params = setup()
                responses = []

                for res in responses1:
                    responses.append(Bn.from_hex(res))

                proof = c, responses
                print(verifyCommitments(params, C, proof))"""

            # This enables us to have flow control in our connection.
            yield from client_writer.drain()
Example #52
0
for gid in curves:
    G = EcGroup(gid)
    gx = G.order().random() * G.generator()

    rnd = [G.order().random() for _ in range(100)]

    t0 = time.clock()
    for r in rnd:
        dud = r * gx
    t1 = time.clock()

    repreats = 1000
    t = []
    for x in [2, 200]:
        o = Bn(2) ** x
        tests = [o.random() for _ in range(repreats)]

        tx = time.clock()
        for y in tests:
            dud = y * gx
        t += [time.clock() - tx]
        # print(x, t[-1] / repreats)
    if abs(t[0] - t[-1]) < 5.0 / 100:
        const = "CONST"
    else:
        const = "NOCONST"

    timings += [((t1-t0)*1000.0/100.0, gid, const)]

Example #53
0
 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()
Example #54
0
def client():
    reader, writer = yield from asyncio.streams.open_connection(
        '127.0.0.1', 12345, loop=loop)#Service Provider
    reader2, writer2 = yield from asyncio.streams.open_connection(
        '127.0.0.1', 7878, loop=loop)#Identity Provider

    def send(msg, writer):
        print("> " + str(msg))
        writer.write((msg + '\n').encode("utf-8"))
        print(msg)
        print(type(msg.encode("utf8")))

    def sendBin(data, writer):
        #print("bin>" + str(data))
        writer.write(data + b'fireintheboof')
        #writer.write_eof()

    def recv(reader):
        msgback = (yield from reader.readline()).decode("utf-8").rstrip()
        #print("< " + msgback)
        return msgback

    # send a line
    #send("buy", writer)
    sendBin(b'buys', writer)
    msg = yield from recv(reader)
    #if repr('id') == msg:
    if True:
        startWait = time.time()
        print("ok i go get ID")

        #generating, encoding, and sending parameters to both sp and idp
        params = BL_setup()

        G, q, g, h, z, hs = params

        endWait = time.time()

        sendBin(b'para' + encode(params), writer)
        sendBin(b'para' + encode(params), writer2)


        print('Time to generate params: ', endWait-startWait)

        seri_enc_idp_pub = yield from reader2.readuntil(separator=b'fireinthepub')
        if seri_enc_idp_pub[0:4] == b'mypb':



            #idp_pub = tuple(list_enc_idp_pub)
            idp_pub = decode(seri_enc_idp_pub[4:-12])
            sendBin(b'ipub' + encode(idp_pub) + b'fireintheboof', writer)

        #h = Hmac(b'sha256', b'ServiceProviderID')

        L2 = q.random()
        Age = 21

        #new
        #N = params[0].hash_to_point('service_name')
        #pseudonym = x * N

        #encode and send user_commit to idp
        LT_user_state, user_commit = BL_user_setup(params, [L2, Age])

        startTimeProof = time.time()

        C = LT_user_state.C
        R = LT_user_state.R
        q = LT_user_state.params[1]
        H = params[0].hash_to_point(b'service_name')
        ID = L2 * H

        wR_id = q.random()
        wx_id = q.random()

        Wit = wR_id * hs[0] + wx_id * hs[1]
        WID_id = wx_id * H

        print(hs)

        stuffToHash = (Wit, WID_id, C, g, h, z, hs[0], hs[1], hs[2], hs[3], H)
        cstr = b",".join([hexlify(x.export()) for x in stuffToHash])
        chash = sha256(cstr).digest()
        c = Bn.from_binary(chash)

        rR_id = wR_id - c * R
        rx_id = wx_id - c * L2

        endTimeProof = time.time()
        print('Proof took: ', endTimeProof - startTimeProof)

        responses = (rR_id, rx_id)

        values = (user_commit, C, c, responses, L2, Age)

        sendBin(b'ucmt' + encode(values), writer2)

        msg2 = yield from reader2.readuntil(separator=b'fireintheboof')

        msg_to_user = decode(msg2[:-13])

        BL_user_prep(LT_user_state, msg_to_user)

        #request idp's pubkey
        #sendBin(b'pubk', writer2)

        #inform idp Im prepped and ready to go
        sendBin(b'prep', writer2)

        msg3 = yield from reader2.readuntil(separator=b'fireintheboof')

        msg_to_user2 = decode(msg3[:-13])

        #generate msg to idp
        msg_to_idp = BL_user_validation(LT_user_state, idp_pub, msg_to_user2)

        #encode, serialise, and send msg to idp
        sendBin(b'msgi' + encode(msg_to_idp), writer2)

        #receive last message from idp, generate signature

        msg4 = yield from reader2.readuntil(separator=b'fireintheboof')

        msg_to_user3 = decode(msg4[:-13])

        sig = BL_user_validation_2(LT_user_state, msg_to_user3)


        sendBin(b'vsig' + encode(sig) + b'fireintheboof', writer)

        print('idppub: ', idp_pub)

        signature_gamhs = BL_user_prove_cred(LT_user_state)
        signature = signature_gamhs[0]
        gam_hs = signature_gamhs[1]
        gam_g = signature_gamhs[2]


        sendBin(b'vsg2' + encode(signature) + b'fireintheboof', writer)

        zet1p = LT_user_state.zet1 - Age * gam_hs[2]
        newStuff = (gam_hs, Age)

        #prove age

        #get variabels
        rnd = LT_user_state.rnd
        R = LT_user_state.R
        q = LT_user_state.params[1]


        wrnd = q.random()
        wR = q.random()
        wx = q.random()

        Wzet1p = wrnd * gam_g + wR * gam_hs[0] + wx * gam_hs[1] #remember to get gam_g

        WID = wx * params[0].hash_to_point(b'service_name')

        stuffToHash = (gam_g, Wzet1p, WID, zet1p, gam_hs[0], gam_hs[1], gam_hs[2], H)
        cstr = b",".join([hexlify(x.export()) for x in stuffToHash])
        chash = sha256(cstr).digest()
        c = Bn.from_binary(chash)

        rrnd = wrnd - c*rnd
        rR = wR - c*R
        rx = wx - c*L2

        responses = (rrnd, rR, rx)
        newStuff = (c, responses, gam_g, gam_hs, Age, L2)

        """Wprime = rrnd * gam_g + rR * gam_hs[0] + rx * gam_hs[1] + c * zet1p

        print(Wzet1p)
        print(Wprime)"""


        sendBin(b'page' + encode(newStuff) + b'fireintheboof', writer)

        #Close the connections to get rid of IncompleteReadError



        cmd = "asd"
        #cmd, *args = msg2.rstrip().split(' ')
    if repr('IDCONFIRMED') == cmd:

        #for encryption
        """key = keyGen()
        print(repr(key))
        ciphertext = encrypt_AES(key, "HAUHEUheuahehaeuhUAEHUHEAUh")
        serialisedCiphertext = pickle.dumps(ciphertext)
        send(('key ' + repr(key)) + " " + repr(serialisedCiphertext), writer)"""
        """params = setup()
        G = params[0]

        C = EcPt.from_binary(literal_eval(args[0]), G)

        r = Bn.from_binary(literal_eval(args[1]))
        secrets = pickle.loads(literal_eval(args[2]))

        proof = proveCommitment(params, C, r, secrets)
        c, responses = proof
        #Here is where I send the proof to the service provider
        seriRes = pickle.dumps(responses)
        send('Proof ' + repr(c) + " " + repr(seriRes), writer)
        print("the end")"""
        end = time.time()
        print("Time: ", end-start)


    writer.close()
    writer2.close()