示例#1
0
def is_smaller(x_bits, y_bits, HE, alpha, n=1000, f=f):
    #takes in input 2 encrypted number (st 0=< x,y < n) given in their binary form
    #coded on alpha bits
    #returns [1] iff y<x , [0] otherwise  (where [1]= encrypt(1))
    #HE is the Homomorphic Encryption scheme (Pyfhel object)

    #Initialisation of same_prefix and same_bit
    #f.write("Initisalisation")
    c_1 = HE.encrypt(PyPtxt([1], HE))
    same_prefix = [c_1]
    same_bit = []
    res = (c_1 - y_bits[0]) * x_bits[0]
    for i in range(alpha):  #min(alpha,int(math.floor(math.log(n))+1))):
        same_bit.append(
            HE.encrypt(PyPtxt([1], HE)) - ((x_bits[i] - y_bits[i])**2))
        tmp = HE.encrypt(PyPtxt([1], HE))
        for j in range(i + 1):
            #f.write("same_bit : "+str(j),HE.decrypt(same_bit[j]))
            tmp *= same_bit[j]
        #f.write("tmp : ",HE.decrypt(tmp))
        same_prefix.append(tmp)
        if i > 0:  #since the 1st term of the sum is already computed before the loop
            res += (HE.encrypt(PyPtxt([1], HE)) -
                    y_bits[i]) * x_bits[i] * same_prefix[i]
            #f.write("res : ",HE.decrypt(res))
    return res
示例#2
0
def is_smaller_fast2(x_bits, y_bits, HE, alpha):
    def product(l, i):
        res = 1
        for j in range(i + 1):
            res *= l[j]
        return res

    def somme(l, i):
        res = 0
        for j in range(i):
            res += l[j]
        return res

    num_cores = multiprocessing.cpu_count()  #number of cores
    print("number of cores : ", num_cores)
    same_prefix = [HE.encrypt(PyPtxt([1], HE))]
    same_bit = Parallel(n_jobs=num_cores - 1)(
        delayed(Computable1.f1)(x_bits[i], y_bits[i]) for i in range(alpha))
    same_prefix += Parallel(n_jobs=num_cores - 1)(delayed(product)(same_bit, i)
                                                  for i in range(alpha))
    to_sum = Parallel(n_jobs=num_cores - 1)(delayed(lambda j: (HE.encrypt(
        PyPtxt([1], HE)) - y_bits[j]) * x_bits[j] * same_prefix[j])(i)
                                            for i in range(alpha))
    res = somme(to_sum, len(to_sum))
    return res
示例#3
0
def Psqrt(x, p, HE):
    def coeffs_Psqrt(p):
        #Returns the coefficients ri that will help compute the polynomial P_sqrt that interpolates the function f:x-->floor(sqrt(x)) on [p]
        l1 = range(0, p)
        l2 = [int(math.floor(math.sqrt(i))) for i in l1]
        #find the coeffs ri (in Zp) that help construct the polynomial
        r = []
        for i in range(p):
            num = l2[i]
            den = 1
            for j in range(p):
                if i != j:
                    den *= i - j
            tmp = (num * inv_modulo(den, p)) % p
            r.append(int(tmp))
        return r

    coeffs = coeffs_Psqrt(p)
    #x encrypted as a single Ctxt
    #0=< x =< p  , p prime
    res = HE.encrypt(PyPtxt([0], HE))
    for i in range(0, p):
        if coeffs[i] != 0:
            tmp = HE.encrypt(PyPtxt([coeffs[i]], HE))
            for j in range(p):
                if i != j:
                    tmp *= (x - HE.encrypt(PyPtxt([j], HE)))
            res += tmp
    return res
示例#4
0
def is_smaller_fast1(x_bits,y_bits,HE,alpha):
    c_1=HE.encrypt(PyPtxt([1], HE))
    same_bit =np.subtract(np.asarray(x_bits),np.asarray(y_bits))**2
    same_bit=np.subtract(np.asarray([c_1.copy(c_1) for i in range(alpha)]),same_bit)
    same_prefix=np.asarray([c_1.copy(c_1)]+[np.prod(same_bit[0:i+1]) for i in range(alpha-1)])
    to_sum=np.multiply(same_prefix,np.multiply(np.subtract(np.asarray([HE.encrypt(PyPtxt([1], HE)) for i in range(alpha)]),np.asarray(y_bits)),np.asarray(x_bits)))
    res = np.sum(to_sum)
    return res
示例#5
0
 def compute_Pbit_i(x, p, coeffs_i, HE):
     #0=< x =< 2^alpha-1 < p  , p prime
     #returns [1] if the ith bit of x is 1, otherwise 0 (x coded on alpha bits)
     res = HE.encrypt(PyPtxt([0], HE))
     for i in range(0, p):
         tmp = HE.encrypt(PyPtxt([coeffs_i[i]], HE))
         for j in range(p):
             if i != j:
                 tmp *= (x - HE.encrypt(PyPtxt([j], HE)))
         res += tmp
     return res
示例#6
0
def l1_norm(a_enc, a_enc_bits, b, b_bits, HE, alpha):
    #a_enc : encrypted vector a (list of Ctxt where each Ctxt is an encrypted coefficient of a)
    #a_enc : encrypted bits of each elt of a (list of lists of Ctxt)
    #same for b and b_bits
    res = HE.encrypt(PyPtxt([0], HE))
    c_2 = HE.encrypt(PyPtxt([2], HE))
    for i in range(len(b)):
        iss = is_smaller_fast1(b_bits[i], a_enc_bits[i], HE, alpha)
        tmp = (b[i] - a_enc[i]) * iss * c_2
        tmp += a_enc[i]
        tmp = tmp - b[i]
        res += tmp
    return res
示例#7
0
def knn(q_enc, q_bits_enc, X_train, Y_train, HE_scheme, p, n, d, k, alpha,
        a_class):
    #q_enc =(enc(q1), ,enc(qd)) : list of the encrypted components of q
    #q_bits=([[q1_bits]], ,[[qd_bits]]) : list of lists, where [[q1_bits]] is the list of each encrypted bit of q1
    #X_train : training set (list of rows, each row being a list itself)
    #Y_train : labels associated with X_train
    #n,d : dimensions of X_train (n : nb of rows, d : nb of columns)
    #k : nb of nearest neighbors to output
    #alpha : nb of bits recquired to encode the input data
    #a_class : nb of bits recquired to encode the number of classes (ex : if 2 classes, a_class=1)
    #p : prime number such that each value in X_train and q are between 0 and sqrt(p)/d
    #HE_scheme : scheme used for encryption (Pyfhel object)

    #Compute the distances (q to each row of X_train)
    distances = dist(q_enc, q_bits_enc, X_train, HE_scheme, alpha)
    distances_bit = []
    for i in range(len(distances)):
        distances_bit.append(convert_to_bits(distances[i], p, alpha,
                                             HE_scheme))
    #Compute Xi (position of the k-nearest neighbours)
    XI = k_smallest_values(distances_bit, k, p, HE_scheme, alpha)
    #Multiply by the auxiliary data
    y_enc = [HE_scheme.encrypt(PyPtxt([elt], HE_scheme)) for elt in X_train[i]]
    res = np.multiply(np.asarray(XI), np.asarray(y_enc))
    return res
示例#8
0
def l1_norm(a_enc, a_enc_bits, b, b_bits, HE, alpha):
    #a_enc : encrypted vector a (list of Ctxt where each Ctxt is an encrypted coefficient of a)
    #a_enc : encrypted bits of each elt of a (list of lists of Ctxt)
    #same for b and b_bits
    p_0 = PyPtxt([0], HE)
    res = HE.encrypt(p_0)
    p_2 = PyPtxt([2], HE)
    c_2 = HE.encrypt(p_2)
    for i in range(len(b)):
        iss = is_smaller(b_bits[i], a_enc_bits[i], HE, alpha=alpha, n=1000)
        tmp = (b[i] - a_enc[i]) * iss * c_2  ##peut etre besoin de copier c_2
        #f.write("tmp ",HE.decrypt(tmp))
        tmp += a_enc[i]
        tmp = tmp - b[i]
        res += tmp
    return res
示例#9
0
def dist(q_enc, q_bits_enc, X_train, HE, alpha, f=f):
    #q_enc =(enc(q1), ,enc(qd)) : list of the encrypted components of q
    #q_bits=([[q1_bits]], ,[[qd_bits]]) : list of lists, where [[q1_bits]] is the list of each encrypted bit of q1
    #X_train : training set (list of rows, each row being a list itself)
    #Y_train : labels associated with X_train
    #n,d : dimensions of X_train (n : nb of rows, d : nb of columns)
    #k : nb of nearest neighbors to output
    #alpha : nb of bits recquired to encode the input data
    #a_class : nb of bits recquired to encode the number of classes (??) (ex : if 2 classes, a_class=1)
    #p : prime number such that each value in X_train and q are between 0 and sqrt(p)/d
    #HE_scheme : scheme used for encryption (Pyfhel object)

    #Step 1 : calculate distances between q and the rows of X_train
    #initialize distances
    distances = []
    n = len(X_train)
    for i in range(n):
        #encrypt each elt of X_train[i]
        b_enc = [HE.encrypt(PyPtxt([elt], HE)) for elt in X_train[i]]
        #also encrypt each elt of X_train[i] as a list of encrypted bits
        b_bits_enc = [encrypt_as_bits(elt, alpha, HE, f) for elt in X_train[i]]
        #compute dist(q,X_train[i])
        dist = l1_norm(q_enc,
                       q_bits_enc,
                       b_enc,
                       b_bits_enc,
                       HE=HE,
                       alpha=alpha)
        distances.append(dist)
    return distances
示例#10
0
def probabilisticAverage(list_x_bits,n,HE,deg,alpha):
    #Takes in input a list of integers (each integer is a list of encrypted bits)
    #n=size of the vector input
    #alpha=number of bits on which each elt of the vector is encoded
    #deg is the degree of the moment to compute (deg=1 : average, deg=2 : second order moment)
    #HE is the Homomorphic Encryption scheme (Pyfhel object)

    #Returns an approximation of the statistical function (ie : average, 2nd order moment..) computed on the integer list
    
    #Initialize
    L=2**alpha
    print("L="+str(L))
    c=int(math.ceil((L**deg)/float(n)))
    print("c="+str(c))
    res=HE.encrypt(PyPtxt([0], HE))
    print("c*n="+str(c*n))
    for i in range(c*n):       #rq : pour L=8 et n=3, c=3 et c*n=9 (environ 440sec)
        tmp=int(math.floor(i/float(c)))    #(rq le dernier i sera c*n-1 donc le dernier tmp sera n-1)
        #print("")
        #print("tmp="+str(tmp))
        #print("")
        tmp=coinToss(list_x_bits[tmp],c*n,HE,deg=deg,alpha=alpha)
        #print("result of the coin toss : ",HE.decrypt(tmp))
        res+=tmp  #peut etre pas besoin d'une liste (sommer directement les elts dans res)
    return res
示例#11
0
def Psqrt2(x, p, HE, f):
    #attempt to improve computation using the polynomialMult method
    def coeffs_Psqrt(p):
        #Returns the coefficients ri that will help compute the polynomial P_sqrt that interpolates the function f:x-->floor(sqrt(x)) on [p]
        l1 = range(0, p)
        l2 = [int(math.floor(math.sqrt(i))) for i in l1]
        f.write("l2 : " + str(l2))
        #find the coeffs ri (in Zp) that help construct the polynomial
        r = []
        f.write("\n")
        f.write("Computing coefficients of Psqrt")
        f.write("\n")
        f.flush()
        for i in range(p):
            num = l2[i]
            den = 1
            for j in range(p):
                if i != j:
                    den *= i - j
            tmp = (num * inv_modulo(den, p)) % p
            r.append(int(tmp))
        return r

    coeffs = coeffs_Psqrt(p)
    #x encrypted as a single Ctxt
    #0=< x =< p  , p prime
    coeffs_ctxt = []
    for i in range(p):
        coeffs_ctxt.append(HE.encrypt(PyPtxt([coeffs[i]], HE)))
    res = x.polynomialMult(coeffs_ctxt)
    return res
示例#12
0
def probabilisticAverage_fast(list_x_bits,n,HE,deg,alpha,f):
    #Takes in input a list of integers (each integer is a list of encrypted bits)
    #n=size of the vector input
    #alpha=number of bits on which each elt of the vector is encoded
    #deg is the degree of the moment to compute (deg=1 : average, deg=2 : second order moment)
    #HE is the Homomorphic Encryption scheme (Pyfhel object)

    #Returns an approximation of the statistical function (ie : average, 2nd order moment..) computed on the integer list
    
    #Initialize
    L=2**alpha
    print("L="+str(L))
    c=int(math.ceil((L**deg)/float(n)))
    print("c="+str(c))
    res=HE.encrypt(PyPtxt([0], HE))
    print("c*n="+str(c*n))
    list_elts=np.asarray([list_x_bits[int(math.floor(i/float(c)))] for i in range(c*n)])
    print("len(list_elts)"+str(len(list_elts)))
    def fct(x):
        return coinToss(x,c*n,HE,deg=deg,alpha=alpha)
    def array_map(x):
        return np.array(list(map(fct, x)))
    #vf=np.vectorize(f)
    #print("to_sum")
    #to_sum=vf(list_elts)
    to_sum=array_map(list_elts)
    #print ("res")
    res = np.sum(to_sum)
    return res
示例#13
0
def k_smallest_values(list_d_bits, p, k, HE, alpha, f=f):
    #Takes in input a list of data (each encrypted as a list of bits)
    #a prime p such that each datapoint 0=< d =< sqrt(p)
    n = len(list_d_bits)
    #Compute average, 2nd order moment and std
    f.write("Compute average")
    f.write("\n")
    avg = probabilisticAverage(
        list_d_bits, n, HE, 1,
        alpha=alpha)  #L=sqrt(p) ?? donc alpha = log2(sqrt(p) ?????
    f.write("average : " + str(HE.decrypt(avg)))
    f.flush()
    f.write("\n")
    f.write("\n")
    f.write("Compute second_moment")
    second_moment = probabilisticAverage(list_d_bits, n, HE, 2, alpha=alpha)
    f.flush()
    f.write("\n")
    f.write("\n")
    f.write("second_moment : " + str(HE.decrypt(second_moment)))
    f.flush()
    f.write("\n")
    A = (avg**2) + second_moment
    f.write("A : " + str(HE.decrypt(A)))
    f.flush()
    f.write("\n")
    f.write("Compute std")
    f.write("\n")
    std = Psqrt(A, p, HE)
    f.write("std : " + str(HE.decrypt(std)))
    f.flush()
    f.write("\n")
    #Compute threshold
    f.write("Compute threshold and convert to bits")
    f.write("\n")
    phi_ = HE.encrypt(PyPtxt([int(round(1 / phi(float(k / n) / 100), 0))], HE))
    f.write(int(round(1 / phi(float(k / n) / 100), 0)))
    f.write("phi : " + str(HE.decrypt(phi_)))
    f.flush()
    f.write("\n")
    T = avg + phi_ * std
    f.write("threshold : " + str(HE.decrypt(T)))
    f.flush()
    f.write("\n")
    T_bits = convert_to_bits(T, p, alpha, HE)
    f.flush()
    f.write("threshold bit by bit : ")
    f.write("\n")
    for bit in T_bits:
        f.write(str(HE.decrypt(bit)))
        f.flush()
        f.write("\n")
    res = []
    for i in range(n):
        res.append(is_smaller(T_bits, list_d_bits[i], HE, alpha=alpha))
        f.write("dist(" + str(i) + ") : " + str(HE.decrypt(res[i])))
        f.flush()
        f.write("\n")
    return res
示例#14
0
def encrypt_as_bits(x, alpha, HE):
    #takes in input a plaintext integer x =< 2^alpha -1
    #returns a list of the encrypted bits of x
    a = '{0:0' + str(alpha) + 'b}'
    x_bits = [int(i) for i in list(a.format(x))]
    x_bits_enc = []
    for i in x_bits:
        x_bits_enc.append(HE.encrypt(PyPtxt([i], HE)))
    return x_bits_enc
示例#15
0
 def run(self, x, y, alpha):
     pool = Pool().map
     same_prefix = [HE.encrypt(PyPtxt([1], HE))]
     same_bit = pool(self.f1, x, y)
     for i in range(alpha):
         same_prefix.append(product(same_bit, i))
     to_sum = pool(self.f2, x, y, same_prefix)
     result = somme(to_sum, len(to_sum))
     return result
示例#16
0
 def test_PyPtxt_creation_deletion(self):
     try:
         self.ptxt = PyPtxt()
         self.ptxt2 = PyPtxt(other_ptxt=self.ptxt)
         self.pyfhel = Pyfhel()
         self.ptxt3 = PyPtxt(pyfhel=self.pyfhel)
         self.ptxt4 = PyPtxt(other_ptxt=self.ptxt3)
     except Exception as err:
         self.fail("PyPtxt() creation failed unexpectedly: ", err)
     self.assertEqual(self.ptxt._encoding, ENCODING_t.UNDEFINED)
     self.ptxt._encoding = ENCODING_t.INTEGER
     self.assertEqual(self.ptxt._encoding, ENCODING_t.INTEGER)
     del (self.ptxt._encoding)
     self.assertEqual(self.ptxt._encoding, ENCODING_t.UNDEFINED)
     self.ptxt._pyfhel = self.pyfhel
     self.ptxt2._pyfhel = self.ptxt._pyfhel
     try:
         del (self.ptxt)
     except Exception as err:
         self.fail("PyPtxt() deletion failed unexpectedly: ", err)
示例#17
0
def encrypt_as_bits(x, alpha, HE, f=f):
    #takes in input a plaintext integer x =< 2^alpha -1
    #returns a list of the encrypted bits of x
    a = '{0:0' + str(alpha) + 'b}'
    x_bits = [int(i) for i in list(a.format(x))]
    x_bits_enc = []
    f.write("Encrypting " + str(x) + " in bits " + str(x_bits))
    f.write("\n")
    f.flush()
    for i in x_bits:
        x_bits_enc.append(HE.encrypt(PyPtxt([i], HE)))
    return x_bits_enc
示例#18
0
 def test_Pyfhel_2a_encode_decode_int(self):
     self.pyfhel = Pyfhel()
     self.pyfhel.contextGen(p=65537)
     self.pyfhel.keyGen()
     self.ptxt = self.pyfhel.encodeInt(127)
     self.assertEqual(self.ptxt.to_string(),
                      b'1x^6 + 1x^5 + 1x^4 + 1x^3 + 1x^2 + 1x^1 + 1')
     self.assertEqual(self.pyfhel.decodeInt(self.ptxt), 127)
     self.ptxt2 = PyPtxt(self.ptxt)
     self.pyfhel.encodeInt(-2, self.ptxt)
     self.assertEqual(self.ptxt.to_string(), b'10000x^1')
     self.assertEqual(self.pyfhel.decodeInt(self.ptxt), -2)
     self.assertEqual(self.pyfhel.decodeInt(self.ptxt2), 127)
示例#19
0
文件: test.py 项目: jeremykohn/Pyfhel
 def test_Pyfhel_2a_encode_decode_int(self):
     pyfhel = Pyfhel()
     pyfhel.contextGen(p=65537)
     pyfhel.keyGen()
     ptxt = pyfhel.encodeInt(127)
     self.assertEqual(ptxt.to_poly_string(),
                      b"1x^6 + 1x^5 + 1x^4 + 1x^3 + 1x^2 + 1x^1 + 1")
     self.assertEqual(pyfhel.decodeInt(ptxt), 127)
     ptxt2 = PyPtxt(ptxt)
     pyfhel.encodeInt(-2, ptxt)
     self.assertEqual(ptxt.to_poly_string(), b"10000x^1")
     self.assertEqual(pyfhel.decodeInt(ptxt), -2)
     self.assertEqual(pyfhel.decodeInt(ptxt2), 127)
示例#20
0
def is_smaller(x_bits, y_bits, HE, alpha):
    #takes in input 2 encrypted number (st 0=< x,y < n) given in their binary form
    #coded on alpha bits
    #returns [1] iff y<x , [0] otherwise  (where [1]= encrypt(1))
    #HE is the Homomorphic Encryption scheme (Pyfhel object)

    #Initialisation of same_prefix and same_bit
    c_1 = HE.encrypt(PyPtxt([1], HE))
    same_prefix = [c_1]
    same_bit = []
    res = (c_1 - y_bits[0]) * x_bits[0]
    for i in range(alpha):
        same_bit.append(
            HE.encrypt(PyPtxt([1], HE)) - ((x_bits[i] - y_bits[i])**2))
        tmp = HE.encrypt(PyPtxt([1], HE))
        for j in range(i + 1):
            tmp *= same_bit[j]
        same_prefix.append(tmp)
        if i > 0:  #since the 1st term of the sum is already computed before the loop
            res += (HE.encrypt(PyPtxt([1], HE)) -
                    y_bits[i]) * x_bits[i] * same_prefix[i]
    return res
def Psqrt(x, p, HE, f):
    def coeffs_Psqrt(p):
        #Returns the coefficients ri that will help compute the polynomial P_sqrt that interpolates the function f:x-->floor(sqrt(x)) on [p]
        l1 = range(0, p)
        l2 = [int(math.floor(math.sqrt(i))) for i in l1]
        #print("l2 : ",l2)
        #find the coeffs ri (in Zp) that help construct the polynomial
        r = []
        for i in range(p):
            num = l2[i]
            den = 1
            for j in range(p):
                if i != j:
                    den *= i - j
            tmp = (num * inv_modulo(den, p)) % p
            r.append(int(tmp))
        return r

    f.write("Computing coefficients of Psqrt")
    f.write("\n")
    f.flush()
    coeffs = coeffs_Psqrt(p)
    #x encrypted as a single Ctxt
    #0=< x =< p  , p prime
    res = HE.encrypt(PyPtxt([0], HE))
    for i in range(0, p):
        if coeffs[i] != 0:
            tmp = HE.encrypt(PyPtxt([coeffs[i]], HE))
            for j in range(p):
                if i != j:
                    #print("j ",j)
                    #print("x-"+str(j)+" : ",HE.decrypt(x-HE.encrypt(PyPtxt([j], HE))))
                    tmp *= (x - HE.encrypt(PyPtxt([j], HE))
                            )  # tmp*=(x-HE.encrypt(PyPtxt([j], HE)))
            #print 'coeffs[i]',type(coeffs[i]),coeffs[i]
            #print "tmp",type(tmp),HE.decrypt(tmp)
            #print("")
            res += tmp
    return res
示例#22
0
def coinToss(x_bits,n,HE,deg,alpha):
#Takes in input an integer n, and an encrypted number 0=< x_bits <n as a list of alpha bits
#generates a random number r between 0 and n  (potentially drawn from a distribution D)
#Returns an encrypted bit b=[1] if r^(1/deg)<x (ie : with probability x/n) otherwise [0]
    #print("Random number between 0 and "+str(n))
    r=randint(0, n)
    #print("r : ",r)
    r=int(math.floor((r**(1/float(deg)))))
    if r>((2**alpha) -1) : #rq : x=< 2**alpha -1 so if r>2**alpha-1, then r>x
        c_0=HE.encrypt(PyPtxt([0], HE))
        return c_0
    else :
        #encrypt r as a list of bits
        r_bits_enc=encrypt_as_bits(r,alpha,HE)
        #compare r_bits and x_bits
        return is_smaller_fast1(x_bits,r_bits_enc,HE,alpha=alpha)
示例#23
0
def k_smallest_values(list_d_bits, p, k, HE, alpha):
    #Takes in input a list of data (each encrypted as a list of bits)
    #a prime p such that each datapoint 0=< d =< sqrt(p)
    n = len(list_d_bits)
    #Compute average, 2nd order moment and std
    avg = probabilisticAverage(
        list_d_bits, n, HE, 1,
        alpha=alpha)  #L=sqrt(p) ?? donc alpha = log2(sqrt(p) ?????
    second_moment = probabilisticAverage(list_d_bits, n, HE, 2, alpha=alpha)
    A = (avg**2) + second_moment
    std = Psqrt(A, p, HE)
    #Compute threshold
    phi_ = HE.encrypt(PyPtxt([int(round(1 / phi(float(k / n) / 100), 0))], HE))
    T = avg + phi_ * std
    T_bits = convert_to_bits(T, p, alpha, HE)
    res = []
    for i in range(n):
        res.append(is_smaller(T_bits, list_d_bits[i], HE, alpha=alpha))
    return res
示例#24
0
def probabilisticAverage(list_x_bits, n, HE, deg, alpha):
    #Takes in input a list of integers (each integer is a list of encrypted bits)
    #n=size of the vector input
    #alpha=number of bits on which each elt of the vector is encoded
    #deg is the degree of the moment to compute (deg=1 : average, deg=2 : second order moment)
    #HE is the Homomorphic Encryption scheme (Pyfhel object)

    #Returns an approximation of the statistical function (ie : average, 2nd order moment..) computed on the integer list

    #Initialize
    L = 2**alpha
    c = int(math.ceil((L**deg) / float(n)))
    a = []
    res = HE.encrypt(PyPtxt([0], HE))
    for i in range((c * n)):
        tmp = int(math.floor(i / c))
        a.append(coinToss(list_x_bits[tmp], c * n, HE, deg=deg, alpha=alpha))
        res += a[i]
    return res
示例#25
0

print("Pyfhel DEMO")
print("  Running KeyGen with params:")
print(KEYGEN_PARAMS)
start = time.time()
HE.keyGen(KEYGEN_PARAMS)
end=time.time()
print("  KeyGen completed in "+str(end-start)+" sec." )

#save and restore the key with saveEnv method
filename='filename.aenv'
start = time.time()
HE.saveEnv(filename)
end=time.time()
c1=HE.encrypt(PyPtxt([1], HE))
HE2=Pyfhel()
start2 = time.time()
HE2.restoreEnv(filename)
end2=time.time()
print "key saved in "+str(end-start)+" sec, and restored in "+str(end2-start2)+" sec."
print HE2.decrypt(c1)

#store the Key as a pickle object
filename='filename_pi.obj'
file_ = open(filename, 'w')
pickle.dump(HE, file_)
file_.close()

file_pi2 = open(filename, 'r')
key = pickle.load(file_pi2)
示例#26
0
def knn(q_enc,
        q_bits_enc,
        X_train,
        Y_train,
        HE_scheme,
        p,
        n,
        d,
        k,
        alpha,
        a_class,
        file=f):
    #q_enc =(enc(q1), ,enc(qd)) : list of the encrypted components of q
    #q_bits=([[q1_bits]], ,[[qd_bits]]) : list of lists, where [[q1_bits]] is the list of each encrypted bit of q1
    #X_train : training set (list of rows, each row being a list itself)
    #Y_train : labels associated with X_train
    #n,d : dimensions of X_train (n : nb of rows, d : nb of columns)
    #k : nb of nearest neighbors to output
    #alpha : nb of bits recquired to encode the input data
    #a_class : nb of bits recquired to encode the number of classes (ex : if 2 classes, a_class=1)
    #p : prime number such that each value in X_train and q are between 0 and sqrt(p)/d
    #HE_scheme : scheme used for encryption (Pyfhel object)

    #compute the distances between q and elements of X_train
    f.write("Distances between q and elements of X_train : ")
    f.write("\n")
    start1 = time.time()
    distances = dist(q_enc, q_bits_enc, X_train, HE_scheme, alpha, f)
    f.write("len(distances) : " + str(len(distances)))
    f.write("\n")
    for res in distances:
        f.write(str(HE_scheme.decrypt(res)))
        f.flush()
    end1 = time.time()
    f.write(str(end1 - start1) + " sec to compute distances.")
    f.write("\n")
    f.write("\n")
    #convert distances to bits
    f.write("Convert distances to bits ")
    f.write("\n")
    f.flush()
    start2 = time.time()
    distances_bit = []
    for i in range(len(distances)):
        distances_bit.append(
            convert_to_bits(distances[i], p, alpha, HE_scheme, f))
        f.write("convert distance " + str(i))
        f.write("\n")
        f.flush()
    end2 = time.time()
    f.write(str(end2 - start2) + " sec to convert distances to bits.")
    f.flush()
    f.write("\n")
    f.write("\n")
    f.write("\n")
    #Find the position of the k nearest neighbours
    f.write("Compute Xi (position of the k-nearest neighbours) :")
    f.write("\n")
    start3 = time.time()
    XI = k_smallest_values(distances_bit, k, p, HE_scheme, alpha, f)
    end3 = time.time()
    f.write(
        str(end3 - start3) +
        " sec to compute the position of the k nearest neighbours.")
    f.flush()
    f.write("\n")
    f.write("\n")
    #Multiply by the auxiliary data
    f.write("Multiply by the auxiliary data")
    f.write("\n")
    y_enc = [HE_scheme.encrypt(PyPtxt([elt], HE_scheme)) for elt in X_train[i]]
    res = np.multiply(np.asarray(XI), np.asarray(y_enc))
    return res
示例#27
0
    "gens": [],
    "ords": []
}

print("  Running KeyGen with params:")
print(KEYGEN_PARAMS)
HE.keyGen(KEYGEN_PARAMS)
end = time.time()
print("  KeyGen completed in " + str(end - start) + " sec.")

n = 7
alpha = 3
p = KEYGEN_PARAMS["p"]
print("Converting " + str(n) + " to bits (alpha = " + str(alpha) + ")")
start = time.time()
x = HE.encrypt(PyPtxt([n], HE))
bits_x = convert_to_bits(x, p, alpha, HE)
end = time.time()
print("Result : ", [HE.decrypt(res) for res in bits_x])
print(str(end - start) + " sec.")

#i=1
#x=HE.encrypt(PyPtxt([n], HE))
#print("Compute the "+str(i)+"th bit of "+str(n)+" (written on "+str(alpha)+" bits)")

#start = time.time()
#coeffs_i=coeffs_Pbit_i(i=i,p=17,alpha=alpha)
#result=compute_Pbit_i(x,p=17,coeffs_i=coeffs_i,HE=HE)
#decrypted_res=HE.decrypt(result)
#print("Result : ",decrypted_res)
#end=time.time()
示例#28
0
    for j in range(d):
        tmp.append(randint(0, (2**alpha) - 1))
    X_train.append(tmp)
    Y_train.append(randint(0, a_class) + 1)
f.write("X_train : " + str(X_train))
f.write("\n")
f.write("\n")
f.write("Y_train : " + str(Y_train))
f.write("\n")
f.flush()

f.write("Encrypting q")
f.write("\n")
f.write("\n")
f.flush()
q_enc = [HE.encrypt(PyPtxt([elt], HE)) for elt in q]
q_bits_enc = [encrypt_as_bits(elt, alpha, HE, f) for elt in q]

f.write("Encrypting X1")
f.write("\n")
f.flush()
x1_enc = [HE.encrypt(PyPtxt([elt], HE)) for elt in X_train[0]]
x1_bits_enc = [encrypt_as_bits(elt, alpha, HE, f) for elt in X_train[0]]

f.flush()

f.write("\n")
f.write("\n")
f.write("Test l1-norm")
f.write("\n")
f.write("\n")
示例#29
0
print("==============================================================")
print("====================== Pyfhel ENCODING =======================")
print("==============================================================")

print("1. Creating Context and KeyGen in a Pyfhel Object ")
HE = Pyfhel()  # Creating empty Pyfhel object
HE.contextGen(p=65537, m=1024, flagBatching=True)  # Generating context.
# The values of p and m are chosen to enable batching (see Demo_Batching_SIMD.py)
HE.keyGen()  # Key Generation.

print("2. Encoding integers with encodeInt")
integer1 = 45
integer2 = -32
ptxt_i1 = HE.encodeInt(integer1)  # Encoding integer1 in a new PyPtxt
ptxt_i2 = PyPtxt()  # Empty plaintexts have no encoding type.
print("    Empty created ptxt_i2: ", str(ptxt_i2))
HE.encodeInt(integer2, ptxt_i2)  # Encoding integer2 in an existing PyPtxt
print("    int ", integer1, '-> ptxt_i1 ', str(ptxt_i1))
print("    int ", integer2, '-> ptxt_i2 ', str(ptxt_i2))

print("3. Encoding floating point values with encodeFrac")
float1 = 3.5
float2 = -7.8
ptxt_f1 = HE.encodeInt(
    float1)  # Encoding float1 in a new PyPtxt with encodeFrac
ptxt_f2 = PyPtxt()
HE.encodeFrac(float2, ptxt_f2)  # Encoding float2 in an existing PyPtxt
print("    float ", float1, '-> ptxt_f1 ', str(ptxt_f1))
print("    float ", float2, '-> ptxt_f2 ', str(ptxt_f2))
示例#30
0
import Pyfhel
from Pyfhel import PyCtxt,PyPtxt,Pyfhel
import time

start = time.time()
HE = Pyfhel()
#Generate Key
KEYGEN_PARAMS={ "p":17,      "r":1,
                "d":0,        "c":2,
                "sec":128,    "w":64,
                "L":50,       "m":-1,
                "R":3,        "s":0,
                "gens":[],    "ords":[]}  
print("  Running KeyGen with params:")
print(str(KEYGEN_PARAMS))
HE.keyGen(KEYGEN_PARAMS)
end=time.time()
print("  KeyGen completed in "+str(end-start)+" sec." )


a=HE.encrypt(PyPtxt([1], HE)) 
b=HE.encrypt(PyPtxt([2], HE)) 
start = time.time()
a*=b
end= time.time()
print("Multiplication in "+str(end-start)+" sec.")