def verify(self, mpk, pk, M, sig): a = H(1, M['t1']) h = H(2, M['t2']) b = H3(M['str'], M['t3']) if pair(sig, mpk['g']) == (pair(a, pk) * (pair(h, pk) ** b)): return True return False
def transform(pk, skBlinded, S, ct): transformOutputList = {} policy_str, C, Cpr, Cn, Dn = ct KBlinded, LBlinded, KlBlinded = skBlinded transformOutputList[5] = C policy = createPolicy(policy_str) transformOutputList[0] = prune(policy, S) attrs = transformOutputList[0] coeff = getCoefficients(policy) transformOutputList[1] = len(attrs) Y = transformOutputList[1] transformOutputList[2] = group.init(GT) reservedVarName0 = transformOutputList[2] for y in range(0, Y): pass transformOutputList[1000+5*y] = GetString(attrs[y]) yGetStringSuffix = transformOutputList[1000+5*y] transformOutputList[1001+5*y] = (pair((Cn[yGetStringSuffix] ** coeff[yGetStringSuffix]), LBlinded) * pair((KlBlinded[yGetStringSuffix] ** coeff[yGetStringSuffix]), Dn[yGetStringSuffix])) reservedVarName1 = transformOutputList[1001+5*y] transformOutputList[1002+5*y] = (reservedVarName0 * reservedVarName1) reservedVarName0 = transformOutputList[1002+5*y] transformOutputList[3] = reservedVarName0 A = transformOutputList[3] transformOutputList[4] = pair(Cpr, KBlinded) result0 = transformOutputList[4] output = (transformOutputList, policy, coeff) return output
def transform(pk, skBlinded, S, ct): transformOutputListForLoop = {} transformOutputList = {} policyUSstr, Ctl, C, Cr, Cpr = ct DBlinded, DjBlinded, DjpBlinded = skBlinded transformOutputList[3] = Ctl policy = createPolicy(policyUSstr) attrs = prune(policy, S) coeff = getCoefficients(policy) Y = len(attrs) transformOutputList[0] = group.init(GT) reservedVarName0 = transformOutputList[0] for y in range(0, Y): pass yGetStringSuffix = GetString(attrs[y]) FLrepVar1 = (10 + (5 * y)) transformOutputListForLoop[FLrepVar1] = (pair((Cr[yGetStringSuffix] ** coeff[yGetStringSuffix]), DjBlinded[yGetStringSuffix]) * pair((DjpBlinded[yGetStringSuffix] ** -coeff[yGetStringSuffix]), Cpr[yGetStringSuffix])) reservedVarName1 = transformOutputListForLoop[FLrepVar1] FLrepVar2 = (11 + (5 * y)) transformOutputListForLoop[FLrepVar2] = (reservedVarName0 * reservedVarName1) reservedVarName0 = transformOutputListForLoop[FLrepVar2] transformOutputList[1] = reservedVarName0 A = transformOutputList[1] transformOutputList[2] = pair(C, DBlinded) result0 = transformOutputList[2] output = (transformOutputList) return output
def Encrypt(self, k, t_l, policy_str, GPP, PK_d): s = group.random() w = group.init(ZR, 0) policy = util.createPolicy(policy_str) #Выбираем два случайных вектора sshares = util.calculateSharesList(s, policy) wshares = util.calculateSharesList(w, policy) sshares = dict([(x[0].getAttributeAndIndex(), x[1]) for x in sshares]) wshares = dict([(x[0].getAttributeAndIndex(), x[1]) for x in wshares]) C = k * pair(GPP['g'], GPP['g']) ** s C1, C2, C3, C4 = {}, {}, {}, {} for attr, s_share in sshares.items(): w_share = wshares[attr] k_attr = util.strip_index(attr) r_i = group.random(ZR) for aa in PK_d: if attr in PK_d[aa]: C1[attr] = (pair(GPP['g'], GPP['g']) ** s_share) * (PK_d[aa][k_attr]['e(g,g)^alpha'] ** r_i) C2[attr] = (GPP['g'] ** w_share) * (PK_d[aa][k_attr]['g^betta'] ** r_i) C3[attr] = GPP['g'] ** r_i C4[attr] = PK_d[aa]['H'](k_attr, t_l) ** r_i # if attr == 'ONE' or attr == 'TWO': # C1[attr] = (pair(GPP['g'], GPP['g']) ** s_share) * (PK_d['aa1'][k_attr]['e(g,g)^alpha'] ** r_i) # C2[attr] = (GPP['g'] ** w_share) * (PK_d['aa1'][k_attr]['g^betta'] ** r_i) # C3[attr] = GPP['g'] ** r_i # C4[attr] = PK_d['aa1']['H'](k_attr, t_l) ** r_i # if attr == 'THREE' or attr == 'FOUR': # C1[attr] = (pair(GPP['g'], GPP['g']) ** s_share) * (PK_d['aa2'][k_attr]['e(g,g)^alpha'] ** r_i) # C2[attr] = (GPP['g'] ** w_share) * (PK_d['aa2'][k_attr]['g^betta'] ** r_i) # C3[attr] = GPP['g'] ** r_i # C4[attr] = PK_d['aa2']['H'](k_attr, t_l) ** r_i return {'t_l': t_l, 'C': C, 'C1': C1, 'C2': C2, 'C3': C3, 'C4': C4, 'policy': policy_str}
def transform(sk, ct): transformOutputList = {} policy_str, C0, C1, C2, C3 = ct gid, userS, K = sk transformOutputList[0] = createPolicy(policy_str) policy = transformOutputList[0] transformOutputList[1] = prune(policy, userS) attrs = transformOutputList[1] transformOutputList[2] = getCoefficients(policy) coeff = transformOutputList[2] transformOutputList[3] = group.hash(gid, G1) h_gid = transformOutputList[3] transformOutputList[4] = len(attrs) Y = transformOutputList[4] for y in range(0, Y): transformOutputList[1000+11*y] = GetString(attrs[y]) k = transformOutputList[1000+11*y] transformOutputList[1001+11*y] = pair(h_gid, C3[k]) result0 = transformOutputList[1001+11*y] transformOutputList[1002+11*y] = (result0 ** coeff[k]) result1 = transformOutputList[1002+11*y] transformOutputList[1003+11*y] = (C1[k] ** coeff[k]) result2 = transformOutputList[1003+11*y] transformOutputList[1004+11*y] = (result1 * result2) numerator = transformOutputList[1004+11*y] transformOutputList[1005+11*y] = pair(K[k], C2[k]) denominator0 = transformOutputList[1005+11*y] output = transformOutputList return output
def decrypt(self, pk, sk, ct): policy = util.createPolicy(ct['policy']) pruned = util.prune(policy, sk['attributes']) if pruned == False: return False coeffs = util.getCoefficients(policy) numerator = pair(ct['C0'], sk['K']) # create list for attributes in order... k_x, w_i = {}, {} for i in pruned: print('for pruned',i,':') j = i.getAttributeAndIndex() print('j=',j) k = i.getAttribute() print('k=',k) k_x[ j ] = sk['K_x'][k] w_i[ j ] = coeffs[j] #print('Attribute %s: coeff=%s, k_x=%s' % (j, w_i[j], k_x[j])) C, D = ct['C'], ct['D'] denominator = 1 for i in pruned: j = i.getAttributeAndIndex() denominator *= ( pair(C[j] ** w_i[j], sk['L']) * pair(k_x[j] ** w_i[j], D[j]) ) return ct['C_tilde'] / (numerator / denominator)
def sign(gpk, A_ind, x_ind, M): r = {} g1, g2, h, u, v, w = gpk alpha = group.random(ZR) beta = group.random(ZR) T1 = (u ** alpha) T2 = (v ** beta) T3 = (A_ind * (h ** (alpha + beta))) gamma1 = (x_ind * alpha) gamma2 = (x_ind * beta) r[0] = group.random(ZR) r[1] = group.random(ZR) r[2] = group.random(ZR) r[3] = group.random(ZR) r[4] = group.random(ZR) r[5] = group.random(ZR) R1 = (u ** r[0]) R2 = (v ** r[1]) R3 = ((pair(T3, g2) ** r[2]) * ((pair(h, w) ** (-r[0] - r[1])) * (pair(h, g2) ** (-r[3] - r[4])))) R4 = ((T1 ** r[2]) * (u ** -r[3])) R5 = ((T2 ** r[2]) * (v ** -r[4])) c = group.hash((M, T1, T2, T3, R1, R2, R3, R4, R5), ZR) salpha = (r[0] + (c * alpha)) sbeta = (r[1] + (c * beta)) sx = (r[2] + (c * x_ind)) sgamma1 = (r[3] + (c * gamma1)) sgamma2 = (r[4] + (c * gamma2)) sig = [T1, T2, T3, c, salpha, sbeta, sx, sgamma1, sgamma2, R3] output = sig return output
def pre_dec(self, pk, ik, ct): w = pk['w'] u = pk['u'] S = ik['S'] #['THREE', 'ONE', 'TWO'] K0 = ik['K0'] K1 = ik['K1'] Kj2 = ik['Ki2'] Kj3 = ik['Ki3'] C0 = ct['C0'] Ci1 = ct['C_j_1'] Ci2 = ct['C_j_2'] Ci3 = ct['C_j_3'] Ci4 = ct['C_j_4'] Ci5 = ct['C_j_5'] policy = util.createPolicy(ct['policy']) #[((ONE or THREE) and (TWO or FOUR)) pruned = util.prune(policy, S) #[ONE, TWO] wi = util.getCoefficients(policy) #{u'TWO': <pairing.Element>, u'FOUR': <pairing.Element>, u'THREE': <pairing.Element>, u'ONE': <pairing.Element>} eC0K0 = pair(C0,K0) ECi4wi = 0 for each in pruned: j = each.getAttributeAndIndex() i = each.getAttribute() ECi4wi += Ci4[i] * wi[i] ewECi4wiK1 = pair(w ** ECi4wi,K1) PIeCi1K1eCi2uCi5Kj2eCi3Kj3wi = 1 for each in pruned: j = each.getAttributeAndIndex() i = each.getAttribute() eCi1K1 = pair(Ci1[i],K1) eCi2uCi5Kj2 = pair(Ci2[i] * (u ** -Ci5[i]), Kj2[j]) eCi3Kj3 = pair(Ci3[i],Kj3[j]) PIeCi1K1eCi2uCi5Kj2eCi3Kj3wi *= (eCi1K1 * eCi2uCi5Kj2 * eCi3Kj3) ** wi[i] return eC0K0/(ewECi4wiK1 * PIeCi1K1eCi2uCi5Kj2eCi3Kj3wi)
def testPairing(self): trials = 10 trials2 = trials * 3 group = PairingGroup("SS512") g = group.random(G1) h = group.random(G1) i = group.random(G2) self.assertTrue(group.InitBenchmark()) group.StartBenchmark(["RealTime", "Exp", "Pair"]) for a in range(trials): j = g * h k = i ** group.random(ZR) t = (j ** group.random(ZR)) / h n = pair(h, i) group.EndBenchmark() msmtDict = group.GetGeneralBenchmarks() self.assertTrue(isSaneBenchmark(msmtDict)) self.assertTrue(group.InitBenchmark()) group.StartBenchmark(["CpuTime", "Mul", "Pair"]) for a in range(trials2): j = g * h k = i ** group.random(ZR) n = pair(h, i) group.EndBenchmark() msmtDict = group.GetGeneralBenchmarks() del group self.assertTrue(isSaneBenchmark(msmtDict))
def transform(skBlinded, userS, ct): transformOutputListForLoop = {} transformOutputList = {} policy_str, C0, C1, C2, C3 = ct gidBlinded, KBlinded = skBlinded transformOutputList[1] = C0 policy = createPolicy(policy_str) attrs = prune(policy, userS) coeff = getCoefficients(policy) transformOutputList[0] = group.hash(gidBlinded, G1) h_gid = transformOutputList[0] Y = len(attrs) for y in range(0, Y): pass kDecrypt = GetString(attrs[y]) FLrepVar1 = (10 + (8 * y)) transformOutputListForLoop[FLrepVar1] = pair(h_gid, C3[kDecrypt]) result0 = transformOutputListForLoop[FLrepVar1] FLrepVar2 = (11 + (8 * y)) transformOutputListForLoop[FLrepVar2] = ((result0 ** coeff[kDecrypt]) * (C1[kDecrypt] ** coeff[kDecrypt])) numerator = transformOutputListForLoop[FLrepVar2] FLrepVar3 = (12 + (8 * y)) transformOutputListForLoop[FLrepVar3] = pair((KBlinded[kDecrypt] ** coeff[kDecrypt]), C2[kDecrypt]) denominator = transformOutputListForLoop[FLrepVar3] output = (transformOutputList, attrs, Y, transformOutputListForLoop) return output
def decrypt_range(self, K_s, S, start, end, ct, param): aggregate2 = group.init(G1, 1) aggregate1 = group.init(G1, 1) result = [] for j in S: aggregate2 *= param[self.n+1-j] if j!=start: aggregate1 *= param[self.n+1-j+start] #else: hole = self.n+1-j+start result.append(ct[0][2] * pair(K_s * aggregate1, ct[0][0]) / pair(aggregate2, ct[0][1]) ) count = end-start-1 sorted_sublist = self.extract_consecutive_sublists(S) for i in xrange(count): for k in sorted_sublist: #print(k) #if ((start+i+1) != j): aggregate1 *= self.param[self.n+1-j+start+i+1] #else: hole = self.n+1-j+start+i+1 if ((start+i+1) != k[0]): aggregate1 *= param[self.n+1-k[0]+start+i+1] #aggregate1 /= self.param[self.n+1-S[0]+start+i] aggregate1 /= param[self.n+1-k[1]+start+i] result.append(ct[i+1][2] * pair(K_s * aggregate1, ct[i+1][0]) / pair(aggregate2, ct[i+1][1]) ) return result
def decrypt_general(self, K_s, S, Q, ct, param): aggregate2 = group.init(G1, 1) aggregate1 = group.init(G1, 1) result = [] S = sorted(S) Q = sorted(Q) # print S sorted_sublist = self.extract_consecutive_sublists(S) improvement = 0 for j in S: aggregate2 *= param[self.n+1-j] if j!=Q[0]: aggregate1 *= param[self.n+1-j+Q[0]] #else: hole = self.n+1-j+start result.append(ct[0][2] * pair(K_s * aggregate1, ct[0][0]) / pair(aggregate2, ct[0][1]) ) for i in xrange(1, len(Q)): d = Q[i] - Q[i-1] improvement = len(S) - (2 * len(sorted_sublist) * d) if (improvement>0): print "improve", improvement # print "optimized ver" for l in xrange(d): for k in sorted_sublist: if ((Q[i-1]+l+1) != k[0]): aggregate1 *= param[self.n+1-k[0]+Q[i-1]+l+1] aggregate1 /= param[self.n+1-k[1]+Q[i-1]+l] else: aggregate1 = group.init(G1, 1) for j in S: if j!=Q[i]: aggregate1 *= param[self.n+1-j+Q[i]] result.append(ct[i][2] * pair(K_s * aggregate1, ct[i][0]) / pair(aggregate2, ct[i][1]) ) return result
def decrypt(self, pk, sk, ct): # caculate run time begin = T.time() policy = util.createPolicy(ct['policy']) pruned = util.prune(policy, sk['attributes']) if pruned == False: return False coeffs = util.getCoefficients(policy) numerator = pair(ct['C_0'], sk['K_0']) # create list for attributes in order... k_x, w_i = {}, {} for i in pruned: j = i.getAttributeAndIndex() k = i.getAttribute() k_x[ j ] = sk['K_x'][k] w_i[ j ] = coeffs[j] #print('Attribute %s: coeff=%s, k_x=%s' % (j, w_i[j], k_x[j])) C_t = ct['C_t'] denominator = 1 for i in pruned: j = i.getAttributeAndIndex() denominator *= ( pair(C_t[j]['i_1'] ** w_i[j], sk['K_1']) * pair(C_t[j]['i_2'] ** w_i[j], k_x[j]['i_2']) * pair(C_t[j]['i_3'] ** w_i[j], k_x[j]['i_3'])) end = T.time() print('%.3f\t' % (end - begin), end="") return ct['C'] / (numerator / denominator)
def decrypt(self, pk, sk, ct): Mprime = ct['C0']/(pair(ct['C11'],sk['sk_id1'])*pair(ct['C12'],sk['sk_id2'])* pair(ct['C13'],sk['sk_id3'])*pair(ct['C14'],sk['sk_id4'])) if(debug): print('\nDecrypt....') return Mprime
def encrypt(self, pk, gp, M, policy_str): '''Encrypt''' #M is a group element #pk is a dictionary with all the attributes of all authorities put together. #This is legal because no attribute can be shared by more than one authority #{i: {'e(gg)^alpha_i: , 'g^y_i'} s = group.random() w = group.init(ZR, 0) egg_s = pair(gp['g'],gp['g']) ** s C0 = M * egg_s C1, C2, C3 = {}, {}, {} #Parse the policy string into a tree policy = util.createPolicy(policy_str) sshares = util.calculateSharesList(s, policy) #Shares of the secret wshares = util.calculateSharesList(w, policy) #Shares of 0 wshares = dict([(x[0].getAttributeAndIndex(), x[1]) for x in wshares]) sshares = dict([(x[0].getAttributeAndIndex(), x[1]) for x in sshares]) for attr, s_share in sshares.items(): k_attr = util.strip_index(attr) w_share = wshares[attr] r_x = group.random() C1[attr] = (pair(gp['g'],gp['g']) ** s_share) * (pk[k_attr]['e(gg)^alpha_i'] ** r_x) C2[attr] = gp['g'] ** r_x C3[attr] = (pk[k_attr]['g^y_i'] ** r_x) * (gp['g'] ** w_share) return { 'C0':C0, 'C1':C1, 'C2':C2, 'C3':C3, 'policy':policy_str }
def verify(self, mpk, pk, M, sig): if debug: print("verify...") (S1, S2) = sig['S1'], sig['S2'] a = H2(M, S1) if pair(S2, mpk['g2']) == (pair(pk, mpk['P']) ** a) * S1: return True return False
def dividenconquer(delta, startSigNum, endSigNum, incorrectIndices, dotBCache, dotACache, sumECache, dotDCache, A, IDlist, Mlist, S1list, S2list, S3list, g2, u1b, u2b, ub): dotBLoopVal = 1 dotALoopVal = 1 sumELoopVal = 0 dotDLoopVal = 1 for z in range(startSigNum, endSigNum): dotBLoopVal = (dotBLoopVal * dotBCache[z]) dotALoopVal = (dotALoopVal * dotACache[z]) sumELoopVal = (sumELoopVal + sumECache[z]) dotDLoopVal = (dotDLoopVal * dotDCache[z]) dotFLoopVal = 1 for y in range(0, l): dotCLoopVal = 1 for z in range(startSigNum, endSigNum): k = stringToInt(group, IDlist[z], l, zz) m = stringToInt(group, Mlist[z], l, zz) dotCLoopVal = (dotCLoopVal * ((S2list[z] ** (delta[z] * k[y])) * (S3list[z] ** (delta[z] * m[y])))) dotFLoopVal = (dotFLoopVal * pair(dotCLoopVal, ub[y])) if ( ( ((pair(dotALoopVal, g2) * ((pair(dotBLoopVal, u1b) * dotFLoopVal) * pair(dotDLoopVal, u2b)))) == ((A ** sumELoopVal)) ) ): return else: midwayFloat = ((endSigNum - startSigNum) / 2) midway = int(midwayFloat) if ( ( (midway) == (0) ) ): incorrectIndices.append(startSigNum) output = None else: midSigNum = (startSigNum + midway) dividenconquer(delta, startSigNum, midSigNum, incorrectIndices, dotBCache, dotACache, sumECache, dotDCache, A, IDlist, Mlist, S1list, S2list, S3list, g2, u1b, u2b, ub) dividenconquer(delta, midSigNum, endSigNum, incorrectIndices, dotBCache, dotACache, sumECache, dotDCache, A, IDlist, Mlist, S1list, S2list, S3list, g2, u1b, u2b, ub) output = None
def verify(self, pk, msg, sig): c3 = pk["uPrime"] for i in range(pk["n"]): c3 *= pk["U"][i] ** msg[i] num = pair(pk["g"], sig["d1"]) dem = pair(sig["d2"], c3) return pk["egg"] == num / dem
def verify(P, g2, pk, M, S1, S2): a = group.hash((M, S1), ZR) if ( ( (pair(S2, g2)) == (((pair(pk, P) ** a) * S1)) ) ): output = True else: output = False return output return output
def verify(self, pk, sig, m): M = group.hash(m) if pk['PP2'] == (pair(pk['gd11']*(pk['gd21']**M), sig['s1']) * pair(pk['gd12']*(pk['gd22']**M), sig['s2']) * pair(pk['gd13']*(pk['gd23']**M), sig['s3']) * pair(pk['gd14']*(pk['gd24']**M), sig['s4']) ): return True return False
def verify(X, Y, g, M, a, b, c): m = group.hash(M, ZR) if ( ( (( (pair(Y, a)) == (pair(g, b)) )) and (( ((pair(X, a) * (pair(X, b) ** m))) == (pair(g, c)) )) ) ): output = True else: output = False return output return output
def verify(self, pk, msg, sig): c3 = pk['uPrime'] for i in range(pk['n']): c3 *= pk['U'][i] ** msg[i] num = pair(sig['d1'], pk['g']) dem = pair(sig['d2'], c3) return pk['egg'] == num / dem
def transform(sk, ct): transformOutputList = {} id, d0, d1, d2, d3, d4 = sk c0, c1, c2, c3, c4, cpr = ct transformOutputList[0] = (pair(c0, d0) * (pair(c1, d1) * (pair(c2, d2) * (pair(c3, d3) * pair(c4, d4))))) result = transformOutputList[0] output = transformOutputList return output
def verify(U, V, D, g2, w2, z2, h2, m, sig1, sig2, r, i): M = group.hash(m, ZR) n = ceillog(2, i) if ( ( (pair(sig1, g2)) == (((U ** M) * ((V ** r) * (D * pair(sig2, ((w2 ** n) * ((z2 ** i) * h2))))))) ) ): output = True else: output = False return output return output
def decrypt_range(self, K_s, S, start, end, ct, param): aggregate2 = group.init(G1, 1) aggregate1 = group.init(G1, 1) result = [] amount =1 gen_timing = 0.0 print "start" print start print "end" print end for j in S: aggregate2 *= param[self.n+1-j] if j!=start: aggregate1 *= param[self.n+1-j+start] #else: hole = self.n+1-j+start result.append(ct[0][2] * pair(K_s * aggregate1, ct[0][0]) / pair(aggregate2, ct[0][1]) ) count = end-start-1 sorted_sublist = self.extract_consecutive_sublists(S) for i in xrange(count): for k in sorted_sublist: #print(k) #if ((start+i+1) != j): aggregate1 *= self.param[self.n+1-j+start+i+1] #else: hole = self.n+1-j+start+i+1 if ((start+i+1) != k[0]): aggregate1 *= param[self.n+1-k[0]+start+i+1] #aggregate1 /= self.param[self.n+1-S[0]+start+i] aggregate1 /= param[self.n+1-k[1]+start+i] starttime = time.clock() result.append(ct[i+1][2] * pair(K_s * aggregate1, ct[i+1][0]) / pair(aggregate2, ct[i+1][1]) ) endtime = time.clock() amount+=1 gen_timing+=endtime-starttime print "amount" print amount print "pairing time for one ciphertext" print gen_timing # print "result" # print len(result) return result
def verify(g1, g2, h, u, v, w, M, T1, T2, T3, c, salpha, sbeta, sx, sgamma1, sgamma2, R3): if ( ( (precheck(g1, g2, h, u, v, w, M, T1, T2, T3, c, salpha, sbeta, sx, sgamma1, sgamma2, R3)) == (False) ) ): output = False return output if ( ( (((pair(T3, g2) ** sx) * ((pair(h, w) ** (-salpha - sbeta)) * ((pair(h, g2) ** (-sgamma1 - sgamma2)) * ((pair(T3, w) ** c) * (pair(g1, g2) ** -c)))))) == (R3) ) ): output = True else: output = False return output return output
def transform(skBlinded, ct): transformOutputList = {} idBlinded, d0Blinded, d1Blinded, d2Blinded, d3Blinded, d4Blinded, d5Blinded = skBlinded c0, c1, c2, c3, c4, cpr = ct transformOutputList[1] = cpr transformOutputList[0] = ((((pair(c0, d0Blinded) * pair(c1, d1Blinded)) * pair(c2, d2Blinded)) * pair(c3, d3Blinded)) * pair(c4, d4Blinded)) result = transformOutputList[0] output = transformOutputList return output
def gen_common(self): x, v = self.group.random(ZR, 2) g = self.group.random(G1) index = self.group.init(ZR, 1) # testing message 0 at index 1 V = (g ** ~(x+index)) ** v y = g ** x print("check: lhs = e(V,y) =>", pair(V,y)) print("check: rhs = e(V,g)^-o * e(g,g)^v =>", (pair(V,g) ** -index) * (pair(g,g) ** v)) Protocol.store(self, ('g', g), ('V', V), ('v',v), ('y',y), ('sigma', index) ) return None
def verify(self, pk, x, st): n, y, pi, pi_0 = pk['n'], st['y'], st['pi'], st['pi0'] # check first index check1 = pair(pi[0], pk['g2']) if x[0] == 0 and check1 == pair(pk['g1'], pk['U_t']): if debug: print("Verify: check 0 successful!\t\tcase:", x[0]) elif x[0] == 1 and check1 == pair(pk['U1'][0], pk['U_t']): if debug: print("Verify: check 0 successful!\t\tcase:", x[0]) else: if debug: print("Verify: check 0 FAILURE!\t\t failed case:", x[0]) return False for i in range(1, len(x)): check2 = pair(pi[i], pk['g2']) if x[i] == 0 and check2 == pair(pi[i-1], pk['g2']): if debug: print("Verify: check", i ,"successful!\t\tcase:", x[i]) elif x[i] == 1 and check2 == pair(pi[i-1], pk['U2'][i]): if debug: print("Verify: check", i ,"successful!\t\tcase:", x[i]) else: if debug: print("Verify: check", i ,"FAILURE!\t\tcase:", x[i]) return False if pair(pi_0, pk['g2']) == pair(pi[n-1], pk['U2'][0]) and pair(pi_0, pk['h']) == y: if debug: print("Verify: all and final check successful!!!") return True else: return False
def decrypt(self, pk, sID, ct): num = pair(sID['d2'], ct['c3']) dem = pair(ct['c2'], sID['d1']) if debug: print("Decrypting") print("arg1 =>", sID['d2'].type) print("arg2 =>", ct['c3'].type) print("Num: =>", num) print("Dem: =>", dem) return ct['c1'] * num / dem
def verify_share(self, sig, i, h): assert 0 <= i < self.l B = self.VKs[i] assert pair(sig, g2) == pair(h, B) return True
def verify_signature(self, sig, h): assert pair(sig, g2) == pair(h, self.VK) return True
def keydec(self, pk, dID, CT): A, B, C = CT['A'], CT['B'], CT['C'] v_s = pair(((B**dID['r']) * C), dID['K']) return sha1(v_s)
def abenc_generatetoken(self, GPP, CT, UASK, user_keys): """ Partial decryption of the ciphertext :param GPP: Global Public Parameters :param CT: Ciphertext elements :param UASK: Secret Keys for user gotten from Attribute Authorities :param user_keys: User global keys :return: Partially decrypted ciphertext """ # list to hold corresponding attributes possessed by the user user_attributes = [] for authority in UASK.keys(): user_attributes.extend(UASK[authority]['AK_uid_aid'].keys()) # access ciphertext policy encryption_policy = self.util.createPolicy(CT['policy']) # generate list of minimum policy elements needed for encryption # returns False if user fails policy assessment minimal_policy_list = self.util.prune(encryption_policy, user_attributes) # print(minimal_policy_list) # this is an error handling implementation that should be fixed later if not minimal_policy_list: return False # get attribute coefficients to be able to access their share of the secret coefficients = self.util.getCoefficients(encryption_policy) # initialize the dividend value for the token generation computation dividend = 1 for authority in UASK.keys(): dividend *= ( pair(CT['C_prime'], UASK[authority]['K_uid_aid']) * ~pair(CT['C_prime_prime'], UASK[authority]['K_uid_aid_prime'])) # attribute authority index? n_a = 1 # initialize divisor value for token generation computation divisor = 1 # create dict to hold attributes for the authorities and their corresponding secret keys attribute_keys = {} # create dict to hold attributes contained in the pruned list and their corresponding secret keys pruned_attribute_keys = {} # populate attribute with with corresponding key value pairs for authority in UASK.keys(): attribute_keys.update(UASK[authority]['AK_uid_aid']) # populate pruned attribute with corresponding key value pairs # from attribute list for attribute in minimal_policy_list: pruned_attribute_keys[str(attribute)] = attribute_keys[str( attribute)] # compute divisor for authority in UASK.keys(): temp_divisor = 1 for attribute in minimal_policy_list: x = attribute.getAttributeAndIndex() y = attribute.getAttribute() temp_divisor *= ( (pair(CT['C_i'][y], user_keys) * pair(CT['D_i'][y], pruned_attribute_keys[y]) * ~pair(CT['C_i_prime'][y], UASK[authority]['K_uid_aid_prime']) * ~pair(GPP['g'], CT['D_i_prime'][y]))**(coefficients[x] * n_a)) divisor *= temp_divisor Token = dividend / divisor return (Token, CT['C'])
def m_dec(self, sk, A, B, E): X = objectToBytes(self.group.hash(pair(A, B) ** (1/sk), G1), self.group) xor = self.bytes_xor(E, X) return xor #if user is legitimate, this will be equal to m
def rowvec_pair_mat(v, M) -> list: return [ reduce(lambda a, b: a * b, [pair(v[i], M[i][j]) for i in range(len(v))]) for j in range(len(M[0])) ]
k += 1 return attributes, attributes_ def xor(a, b, grp): a_ = grp.serialize(a, compression=False) b_ = grp.serialize(b, compression=False) c_ = ''.join(chr(ord(a_i) ^ ord(b_i)) for a_i, b_i in zip(a_, b_)) return grp.deserialize(c_, compression=False) xor = lambda ss, cc: ''.join(chr(ord(s) ^ ord(c)) for s, c in zip(ss, cc)) a0 = group.random(G1) a1 = group.random(G2) a = pair(a0, a1) H2 = lambda x: group.hash(str(x) + str(group.random(ZR)), ZR) # b0 = group.random(G1) # b1 = group.random(G2) # b = pair(b0,b1) b = group.random() a_s = group.serialize(a) b_s = group.serialize(b) c_s = xor(H2(a_s), b_s) a group.deserialize(xor(c_s, b_s)) # ==a
def sign(self, title, usk, pk, GID, UID, groupID): t1 = time() m = self.group.hash(title) b0 = usk['b0'] b3 = usk['b3'] b4 = usk['b4'] b5 = usk['b5'] r4 = self.group.random(ZR) r3 = self.group.random(ZR) k = self.group.random(ZR) c0 = b0 * (b3**m) * (b4**r4) * ((pk['u0'] * (pk['u1']**GID) * (pk['u2']**UID) * (pk['u3']**m) * (pk['u4']**r4))**r3) c5 = b5 * (pk['g']**r3) c6 = (pk['u2']**UID) * (pk['u4']**r4) e1 = pk['g']**k e2 = (pk['u0'] * (pk['u1']**GID))**k e3 = (pk['n']**UID) * (pair(pk['h1'], pk['g2'])**k) # 产生pok f = pk['u0'] * (pk['u1']**GID) gp = pair(pk['h1'], pk['g2']) k1 = self.group.random(ZR) k2 = self.group.random(ZR) k3 = self.group.random(ZR) r1 = (pk['u2']**k1) * (pk['u4']**k2) r2 = pk['g']**k3 r3 = f**k3 t4 = (pk['n']**k1) * (gp**k3) hashstr = str(r1) + str(r2) + str(r3) + str(t4) c = self.group.hash(hashstr) s1 = k1 + c * UID s2 = k2 + c * r4 s3 = k3 + c * k signature = { 'c0': c0, 'c5': c5, 'c6': c6, 'e1': e1, 'e2': e2, 'e3': e3, 'c': c, 's1': s1, 's2': s2, 's3': s3 } t2 = time() with open("vssigntime.txt", 'a') as f: f.write(str(t2 - t1)) f.write('\n') print("gs time", t2 - t1) return signature
def dividenconquer(delta, startSigNum, endSigNum, incorrectIndices, dotACache, dotBCache, dotCCache, dotDCache, dotECache, dotFCache, dotGCache, dotHCache, dotICache, dotJCache, dotKCache, dotLCache, dotMCache, sumNCache, g1b, g1ba1, g1a1, g1ba2, g1a2, tau1, tau2, tau1b, tau2b, w, u, h, g1, A): dotALoopVal = 1 dotBLoopVal = 1 dotCLoopVal = 1 dotDLoopVal = 1 dotELoopVal = 1 dotFLoopVal = 1 dotGLoopVal = 1 dotHLoopVal = 1 dotILoopVal = 1 dotJLoopVal = 1 dotKLoopVal = 1 dotLLoopVal = 1 dotMLoopVal = 1 sumNLoopVal = 0 for z in range(startSigNum, endSigNum): dotALoopVal = (dotALoopVal * dotACache[z]) dotBLoopVal = (dotBLoopVal * dotBCache[z]) dotCLoopVal = (dotCLoopVal * dotCCache[z]) dotDLoopVal = (dotDLoopVal * dotDCache[z]) dotELoopVal = (dotELoopVal * dotECache[z]) dotFLoopVal = (dotFLoopVal * dotFCache[z]) dotGLoopVal = (dotGLoopVal * dotGCache[z]) dotHLoopVal = (dotHLoopVal * dotHCache[z]) dotILoopVal = (dotILoopVal * dotICache[z]) dotJLoopVal = (dotJLoopVal * dotJCache[z]) dotKLoopVal = (dotKLoopVal * dotKCache[z]) dotLLoopVal = (dotLLoopVal * dotLCache[z]) dotMLoopVal = (dotMLoopVal * dotMCache[z]) sumNLoopVal = (sumNLoopVal + sumNCache[z]) if ((((pair(g1b, dotALoopVal) * (pair(g1ba1, dotBLoopVal) * (pair(g1a1, dotCLoopVal) * (pair(g1ba2, dotDLoopVal) * pair(g1a2, dotELoopVal)))))) == (( pair(dotFLoopVal, tau1) * (pair(dotGLoopVal, tau2) * (pair(dotHLoopVal, tau1b) * (pair(dotILoopVal, tau2b) * (pair(dotJLoopVal, w) * (pair(dotKLoopVal, u) * (pair(dotLLoopVal, h) * (pair(g1, dotMLoopVal) * (A**sumNLoopVal)))))))))))): return else: midwayFloat = ((endSigNum - startSigNum) / 2) midway = int(midwayFloat) if (((midway) == (0))): incorrectIndices.append(startSigNum) output = None else: midSigNum = (startSigNum + midway) dividenconquer(delta, startSigNum, midSigNum, incorrectIndices, dotACache, dotBCache, dotCCache, dotDCache, dotECache, dotFCache, dotGCache, dotHCache, dotICache, dotJCache, dotKCache, dotLCache, dotMCache, sumNCache, g1b, g1ba1, g1a1, g1ba2, g1a2, tau1, tau2, tau1b, tau2b, w, u, h, g1, A) dividenconquer(delta, midSigNum, endSigNum, incorrectIndices, dotACache, dotBCache, dotCCache, dotDCache, dotECache, dotFCache, dotGCache, dotHCache, dotICache, dotJCache, dotKCache, dotLCache, dotMCache, sumNCache, g1b, g1ba1, g1a1, g1ba2, g1a2, tau1, tau2, tau1b, tau2b, w, u, h, g1, A) output = None
def retrap(self,ck,t): #print 't', t tt=pair(t, ck) #print tt return tt
def PEKS(self, word): g, h = self.pub r = group.random(ZR) t = pair(group.hash(word, G1), h * r) return (g * r, h2.hashToZn(t))
def encrypt(self, params, ID, m, skid, t): r = h.group.random(ZR) C1 = params['g'] ** r C2 = m * (pair(params['g_s'], group.hash(ID, G1)) ** (r * h.hashToZr(skid['skid'], t))) C3 = t return {'C1': C1, 'C2': C2, 'C3': C3}
def pair_vector(v, base): return list(map(lambda x: pair(x, base), v))
def verify(self, pk, msg, sig): c3 = pk['uPrime'] for i in range(pk['n']): c3 *= pk['U'][i]**msg[i] return pk['egg'] == (pair(sig['d1'], pk['g']) / pair(sig['d2'], c3))
def decrypt1(self, params, skid, c): return c['C2'] / pair(skid['skid'], c['C1'])
def setup(self): """ Generates public key and master secret key. """ if debug: print('Setup algorithm:\n') # generate two instances of the k-linear assumption A = [] B = [] for i in range(self.assump_size): A.append(self.group.random(ZR)) B.append(self.group.random(ZR)) # note that A, B are vectors here # pick matrices that help to randomize basis W = {} for i in range(self.uni_size): x = [] for j1 in range(self.assump_size + 1): y = [] for j2 in range(self.assump_size + 1): y.append(self.group.random(ZR)) x.append(y) W[i + 1] = x V = [] for j1 in range(self.assump_size + 1): y = [] for j2 in range(self.assump_size + 1): y.append(self.group.random(ZR)) V.append(y) # vector k = [] for i in range(self.assump_size + 1): k.append(self.group.random(ZR)) # pick a random element from the two source groups and pair them g = self.group.random(G1) h = self.group.random(G2) e_gh = pair(g, h) # now compute various parts of the public parameters # compute the [A]_1 term g_A = [] for i in range(self.assump_size): g_A.append(g**A[i]) g_A.append(g) # compute the [W_1^T A]_1, [W_2^T A]_1, ... terms g_WA = {} for i in range(self.uni_size): x = [] for j1 in range(self.assump_size + 1): y = [] for j2 in range(self.assump_size): prod = (A[j2] * W[i + 1][j2][j1]) + W[i + 1][self.assump_size][j1] y.append(g**prod) x.append(y) g_WA[i + 1] = x g_VA = [] for j1 in range(self.assump_size + 1): y = [] for j2 in range(self.assump_size): prod = (A[j2] * V[j2][j1]) + V[self.assump_size][j1] y.append(g**prod) g_VA.append(y) # compute the e([A]_1, [k]_2) term h_k = [] for i in range(self.assump_size + 1): h_k.append(h**k[i]) e_gh_kA = [] for i in range(self.assump_size): e_gh_kA.append(e_gh**(k[i] * A[i] + k[self.assump_size])) # the public key pk = {'g_A': g_A, 'g_WA': g_WA, 'g_VA': g_VA, 'e_gh_kA': e_gh_kA} # the master secret key msk = {'h': h, 'k': k, 'B': B, 'W': W, 'V': V} return pk, msk
def encrypt1(self, params, m, ID): r = h.group.random(ZR) C1 = params['g'] ** r C2 = m * pair(group.hash(ID, G1), params['g_s']) ** r return {'C1': C1, 'C2': C2}
def F(self, sk, x): result = dotprod(1, -1, sk['n'], lam_func, sk['u'], x) return pair(sk['g1']**(sk['u_t'] * sk['u'][0] * result), sk['h'])
def m_enc(self, g, m, pks, r, s): return self.bytes_xor(objectToBytes(self.group.hash(pair(g,g) ** (r*s), G1), self.group), m) # TODO find suitable hashing function mapping to M
errors = 0 total = 0 for i in range(len(X_test)): biased[1:] = X_test[i] results = ml.evaluate(biased) v = models.Vector(array=X_test[i]) before_encrypt = timeit.default_timer() c = scheme.encrypt(pk, v) after_encrypt = timeit.default_timer() enc_time = after_encrypt - before_encrypt before_eval = timeit.default_timer() evaluation = dk.model.evaluate(c) decrypted = [ evaluation[i] * pair(c.simplifier, dk.skf[i]) for i in range(dk.classes) ] after_eval = timeit.default_timer() eval_time = after_eval - before_eval before_dlog = timeit.default_timer() dec = list(map(dlog.solve, decrypted)) after_dlog = timeit.default_timer() dlog_time = after_dlog - before_dlog if (x is not None for x in dec): if (dec == results.astype(int)).all(): enc_total += enc_time eval_total += eval_time dlog_total += dlog_time total += 1
def keygen(self): g2 = group.random(G1) g1 = group.random(G2) alpha = group.random(ZR) #generate the 4*4 dual pairing vector spaces. d11, d12, d13, d14 = group.random(ZR), group.random(ZR), group.random( ZR), group.random(ZR) d21, d22, d23, d24 = group.random(ZR), group.random(ZR), group.random( ZR), group.random(ZR) d31, d32, d33, d34 = group.random(ZR), group.random(ZR), group.random( ZR), group.random(ZR) d41, d42, d43, d44 = group.random(ZR), group.random(ZR), group.random( ZR), group.random(ZR) D11, D12, D13, D14 = group.init(ZR), group.init(ZR), group.init( ZR), group.init(ZR) D21, D22, D23, D24 = group.init(ZR), group.init(ZR), group.init( ZR), group.init(ZR) D31, D32, D33, D34 = group.init(ZR), group.init(ZR), group.init( ZR), group.init(ZR) D41, D42, D43, D44 = group.init(ZR), group.init(ZR), group.init( ZR), group.init(ZR) one = group.random(ZR) [D11, D12, D13, D14] = self.GaussEleminationinGroups( [[d11, d12, d13, d14, one], [d21, d22, d23, d24, group.init(ZR, long(0))], [d31, d32, d33, d34, group.init(ZR, long(0))], [d41, d42, d43, d44, group.init(ZR, long(0))]]) [D21, D22, D23, D24] = self.GaussEleminationinGroups( [[d11, d12, d13, d14, group.init(ZR, long(0))], [d21, d22, d23, d24, one], [d31, d32, d33, d34, group.init(ZR, long(0))], [d41, d42, d43, d44, group.init(ZR, long(0))]]) [D31, D32, D33, D34] = self.GaussEleminationinGroups( [[d11, d12, d13, d14, group.init(ZR, long(0))], [d21, d22, d23, d24, group.init(ZR, long(0))], [d31, d32, d33, d34, one], [d41, d42, d43, d44, group.init(ZR, long(0))]]) [D41, D42, D43, D44] = self.GaussEleminationinGroups( [[d11, d12, d13, d14, group.init(ZR, long(0))], [d21, d22, d23, d24, group.init(ZR, long(0))], [d31, d32, d33, d34, group.init(ZR, long(0))], [d41, d42, d43, d44, one]]) #generate public parameters. #PP2 = (pair(g1, g2))**(alpha*one) PP2 = (pair(g2, g1))**(alpha * one) gd11 = g1**d11 gd12 = g1**d12 gd13 = g1**d13 gd14 = g1**d14 gd21 = g1**d21 gd22 = g1**d22 gd23 = g1**d23 gd24 = g1**d24 pk = { 'PP2': PP2, 'gd11': gd11, 'gd12': gd12, 'gd13': gd13, 'gd14': gd14, 'gd21': gd21, 'gd22': gd22, 'gd23': gd23, 'gd24': gd24 } #generate private parameters sk = { 'alpha': alpha, 'g2': g2, 'D11': D11, 'D12': D12, 'D13': D13, 'D14': D14, 'D21': D21, 'D22': D22, 'D23': D23, 'D24': D24 } if (debug): print("Public parameters...") group.debug(pk) print("Secret parameters...") group.debug(sk) return (pk, sk)
def verify(self, pk, sig, message): M = self.dump(message) h = group.hash(M, G1) if pair(sig, pk['g']) == pair(h, pk['g^x']): return True return False
def verify(self, pk, M, sig): (a, b, c) = sig['a'], sig['a_y'], sig['a_xy'] m = group.hash(M, ZR) if pair(pk['Y'], a) == pair(pk['g'], b) and (pair(pk['X'], a) * (pair(pk['X'], b) ** m)) == pair(pk['g'], c): return True return False
def decrypt(self, pk, dID, CT): A, B, C = CT['A'], CT['B'], CT['C'] v_s = pair(((B**dID['r']) * C), dID['K']) return A / v_s