Giter Club home page Giter Club logo

ibarrond / pyfhel Goto Github PK

View Code? Open in Web Editor NEW
436.0 12.0 75.0 15.79 MB

PYthon For Homomorphic Encryption Libraries, perform encrypted computations such as sum, mult, scalar product or matrix multiplication in Python, with NumPy compatibility. Uses SEAL/PALISADE as backends, implemented using Cython.

Home Page: https://pyfhel.readthedocs.io/

License: Apache License 2.0

Python 20.22% C++ 25.34% Dockerfile 0.23% Cython 54.12% CMake 0.10%
homomorphic-encryption encrypted-data homomorphic-encryption-library python seal palisade helib cython encrypted-computation

pyfhel's Introduction

iCodecov Documentation Status PyPI version Maintenance GitHub issues License: GPL v3

Python library for Addition, Subtraction, Multiplication and Scalar Product over encrypted integers (BFV/BGV schemes) and approximated floating point values (CKKS scheme). This library acts as an optimized Python API for C++ Homomorphic Encryption libraries.

🎏 Language Python (3.7+), with Cython and C++ (:warning: requires a C++17 compiler ⚠️.)
πŸ’» OS Linux, Windows & MacOS.
πŸ”’ Version 3.4.2 (stable)
πŸ“š Docs In readthedocs!
✏️ Demos/Examples In the docs with the outputs, sources in the examples folder.
πŸ”Œ Backends SEAL, OpenFHE (WIP). Shipped alongside Pyfhel.
πŸ‘· Authors Alberto Ibarrondo (IDEMIA & EURECOM) and Alexander Viand (ETH Zurich).
πŸŽ“ Original Collaborators Melek Onen (EURECOM), Laurent Gomez (SAP Labs).

If you wish to cite Pyfhel in your derived work, please use the following BibTeX entry:

  @inproceedings{ibarrondo2021pyfhel,
  title={Pyfhel: Python for homomorphic encryption libraries},
  author={Ibarrondo, Alberto and Viand, Alexander},
  booktitle={Proceedings of the 9th on Workshop on Encrypted Computing \& Applied Homomorphic Cryptography},
  pages={11--16},
  year={2021}
}


Install & Uninstall  Summary  Contributing  Bugs & Feature Requests  Legal Disclaimer



Install & Uninstall

To install Pyfhel from PyPI, run (WARNING! it takes several minutes to compile and install, be patient!):

pip install Pyfhel

To install the latest version, you can clone this repository with all the submodules and install it by running:

git clone --recursive https://github.com/ibarrond/Pyfhel.git
pip install .

To uninstall, just run:

pip uninstall Pyfhel

Installing a C/C++ Compiler

Pyfhel requires a C/C++ compiler with C++17 support. We have tested:

  • gcc6 to gcc12 in Linux/MacOS/Windows WSL. To install:
    • Ubuntu: sudo apt install gcc g++
    • MacOS: brew install gcc. MacOS users must also set several environment variables by running:
        # Brew installs GCC in /opt/homebrew/bin on Apple Silicon and /usr/local/bin on Intel.
        if [[ $(uname -m) = "arm64" ]]; then BREW_GCC_PATH="/opt/homebrew/bin"; else BREW_GCC_PATH="/usr/local/bin"; fi

        # Set CC/CXX environment variables to the most recent GNU GCC
        export CC="$BREW_GCC_PATH/$(ls $BREW_GCC_PATH | grep ^gcc-[0-9] | sort -V -r | head -n 1)"
        export CXX="$BREW_GCC_PATH/$(ls $BREW_GCC_PATH | grep ^g++-[0-9] | sort -V -r | head -n 1)"
        
        # Set MACOSX_DEPLOYMENT_TARGET to avoid version mismatch warnings
        echo "MACOSX_DEPLOYMENT_TARGET=$(sw_vers -productVersion)" >> $GITHUB_ENV
        echo "MACOSX_DEPLOYMENT_TARGET=${{ env.MACOSX_DEPLOYMENT_TARGET }}"
  • MSVC2017 and MSVC2019 in Windows. To install:
    • Install Visual C++ Build tools (Download here, guide in here)

Summary

PYthon For Homomorphic Encryption Libraries, Pyfhel implements functionalities of multiple Homomorphic Encryption libraries such as addition, multiplication, exponentiation or scalar product in Python. Pyfhel uses a syntax similar to normal arithmetics (+,-,*). This library is useful both for simple Homomorphic Encryption Demos as well as for complex problems such as Machine Learning algorithms.

Pyfhel is built on top of Afhel, an Abstraction Homomorphic Encryption Libraries in C++. Afhel serves as common API for all backends. Additionally, this project contains a large series of Demos & Tests for Pyfhel.

This repository contains:

  • docs/ Documentation, generated automatically using sphinx and pushed to readthedocs.
  • examples/ Demos and small programs to showcase multiple functionalities.
  • Pyfhel/ contains the source code for Pyfhel and Afhel.
  • Pyfhel/backend, underlying C++ libraries SEAL & PALISADE.

Contributing

This is the standard process to develop/contribute:

  1. Code a new feature/fix a bug. Using Cython for the .pyx and .pxd extensions, C++ for Afhel or Python for examples/tests/other.

  2. Build/Install Pyfhel locally. Use pip install -v -v . for a verbose installation.

  3. Test changes (requires installing pytest). Run the tests locally by executing pytest . in the root directory, and make sure all tests pass.

    • Code coverage (requires installing pytest-cov). Add an empty .cov file in the root directory, and build/install the project locally (pip install .). To run coverage tests, execute pytest --cov . in the root directory, and then coverage html to obtain a report.

You're ready to go! Just create a pull request to the original repo.

Bugs & Feature Requests

Please fill the Bug Report template to provide all the essential info to reproduce your issue and solve the problem.

If you wish to have new functionality added to Pyfhel, you are more than welcome to request it via the Feature template.

Legal disclaimer

This project is Open Source under the Apache V2 License (LICENSE file). Hence, Pyfhel can be used, modified, and copied freely provided that developers:

  1. Acknowledge and mention the original authors of Pyfhel in any derived development, that is, Alberto Ibarrondo (IDEMIA & EURECOM) and Alexander Viand (ETH Zurich) (maybe even cite the paper!).

  2. Maintain the same License, and provide a statement of changes.

We encourage any software using Pyfhel to be Open Source, for the benefit of everyone using it.

pyfhel's People

Contributors

aakankshaduggal avatar alexanderviand avatar alexgadai avatar aquint-zama avatar benqalu avatar davidbstein avatar devharsh avatar hodgesmr avatar ibarrond avatar josegironn avatar kokeshim0chi avatar marcwil avatar pyup-bot avatar remyauda avatar severos avatar tanu17 avatar tdonovic avatar yooopan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pyfhel's Issues

Windows 10 test.py Error when Saving / Reloading ciphertexts

There is something wrong when Saving / Reloading ciphertexts in Windows10 Python3. Full error message:

======================================================================
ERROR: test_Pyfhel_5d_save_restore_batch (__main__.PyfhelTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "Pyfhel\Pyfhel.pyx", line 390, in Pyfhel.Pyfhel.Pyfhel.decryptBatch
RuntimeError: <Pyfhel ERROR> wrong encoding type in PyCtxt

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "..\Pyfhel\test.py", line 424, in test_Pyfhel_5d_save_restore_batch
    self.assertEqual(pyfhel.decryptBatch(loaded)[:4], [1, 2, 3, 4])
SystemError: <method 'decryptBatch' of 'Pyfhel.Pyfhel.Pyfhel' objects> returned a result with an error set

======================================================================
ERROR: test_Pyfhel_5d_save_restore_float (__main__.PyfhelTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "Pyfhel\Pyfhel.pyx", line 366, in Pyfhel.Pyfhel.Pyfhel.decryptFrac
RuntimeError: <Pyfhel ERROR> wrong encoding type in PyCtxt

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "..\Pyfhel\test.py", line 408, in test_Pyfhel_5d_save_restore_float
    self.assertEqual(pyfhel.decryptFrac(loaded), 3.125)
SystemError: <method 'decryptFrac' of 'Pyfhel.Pyfhel.Pyfhel' objects> returned a result with an error set

======================================================================
ERROR: test_Pyfhel_5d_save_restore_int (__main__.PyfhelTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "Pyfhel\Pyfhel.pyx", line 343, in Pyfhel.Pyfhel.Pyfhel.decryptInt
RuntimeError: <Pyfhel ERROR> wrong encoding type in PyCtxt

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "..\Pyfhel\test.py", line 392, in test_Pyfhel_5d_save_restore_int
    self.assertEqual(pyfhel.decryptInt(loaded), 42)
SystemError: <method 'decryptInt' of 'Pyfhel.Pyfhel.Pyfhel' objects> returned a result with an error set

======================================================================
FAIL: test_Pyfhel_5c_save_restore_all (__main__.PyfhelTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "..\Pyfhel\test.py", line 375, in test_Pyfhel_5c_save_restore_all
    pyfhel2.decryptInt(ctxt_restored), 42, "decrypting ciphertext should work"

Make Afhel

Hi Alberto,

I'm starting my final project master's degree and your python project is a must :)

I'm trying to make install everything (Ubuntu 16.04.2) and the first stopper is when I have tried to make & make install Afhel, HELib has been installed like a charm, however it throws an error:
Afhel.cpp:50:14: error: definition of implicitly-declared β€˜Afhel::Afhel()’ Afhel::Afhel(){} ^ compilation terminated due to -Wfatal-errors. Makefile:145: recipe for target 'Afhel.lo' failed make: *** [Afhel.lo] Error 1

Could I have some advices to fix that and work with this Python project?
If you want to speak in Spanish about this, you can reach me at LinkedIn (request has been sent from myself).

Thanks in advance!

P.S.- Also, I have modified some separator errors in the makefiles due to spaces vs tab.
P.S.2.- Could you update the tutorial to install it with the new version? +The new SEAL library should be get from: https://download.microsoft.com/download/B/3/7/B3720F6B-4F4A-4B54-9C6C-751EF194CBE7/SEAL_2.3.1.tar.gz

The version 2.3.0 is not available anymore :(

Test Examples-Demo_float for Version 2

Error:

ctxtSum = ctxt1 + ctxt2 # ctxt1 += ctxt2 for quicker inplace operation
Traceback (most recent call last):
File "", line 1, in
File "Pyfhel/PyCtxt.pyx", line 126, in Pyfhel.PyCtxt.PyCtxt.add
AttributeError: 'NoneType' object has no attribute 'add_encr'

PyFhel installation on ananconda prompt

i used :- pip install PyFhel , for installing pyfhel on my prompt but it has been showing errors " Failed building wheel for Pyfhel", please give a proper procedure to install pyfhel

How to Relinearize. SystemError: <method 'relinearize' of 'Pyfhel.Pyfhel.Pyfhel' objects> returned a result with an error set

Hi,I recently got my hands-on with this amazing library.But i got some problems when i applied logistic regression model with Stochastic gradient descent on encrypted data(Dataset:141rows3cols). when updating the weights until the fifth time,the size of Wx getting very large.Maybe I should use relinKeyGen(int bitCount, int size) and relinearize(PyCtxt ctxt) to reduce its size down to 2.

1.Before i didn't use relinearize(), the sizes showed as followings.

     <Pyfhel Ciphertext,encoding=FRACTIONAL,size=3>
     <Pyfhel Ciphertext,encoding=FRACTIONAL,size=12>
     <Pyfhel Ciphertext,encoding=FRACTIONAL,size=48>
     <Pyfhel Ciphertext,encoding=FRACTIONAL,size=192>
     <Pyfhel Ciphertext,encoding=FRACTIONAL,size=768>

And then the Server went wrong.

2.when initializing relinKeyGen(20,6) and using relinearize(),another problem occured.

SystemError: <method 'relinearize' of 'Pyfhel.Pyfhel.Pyfhel' objects> returned a result with an error set

The key codes are as follow.The only difference about situation 1&2 is " self.pyfhel.relinearize(hy) ".

def dot_product(self,a,theta):
       sum=self.pyfhel.encryptFrac(0)
       for i in range(len(a)):
            sum=self.pyfhel.add(sum,self.pyfhel.multiply(a[i],theta[i],in_new_ctxt=True),in_new_ctxt=True)
       print("dot:",sum)
       return sum

def sigmoid():
       pass
            
def BGD(self,X_enc,y_enc):
        m,n=X_enc.shape
        theta=np.ones((n,1))
        theta=self.encrypt_theta(theta)
        iters=100
        for i in range(iters):
            dataIndex=list(range(m))
            for j in range(m):
                alpha = 4.0/(1.0+i+j)+0.01
                alpha_enc=self.pyfhel.encryptFrac(alpha)
                randIndex=int(random.uniform(0,m))
                hy=self.dot_product(X_enc[randIndex],theta)
                **self.pyfhel.relinearize(hy) //SystemError::<method 
                'relinearize' of 'Pyfhel.Pyfhel.Pyfhel' objects> returned a 
                 result with an error set**
                X_sigmoid=self.sigmoid(hy)
                error=self.pyfhel.sub(X_sigmoid,y_enc[randIndex])
                error_alpha=self.pyfhel.multiply(error,alpha_enc)
                x_error_alpha=self.mul_fra(X_enc[randIndex],error_alpha)
                theta=self.sub_array(theta,x_error_alpha)
                del(dataIndex[randIndex])
        return theta

My question:
1.problem β€”β€”the size of dot.product getting large,can we use the function relinKeyGen() and using relinearize() to solve it?
2.If it's,how to use the function relinKeyGen() and relinearize() ,even the Args relinKeyGen().I couldn't find any example in github -_- so sad.
If it's not,what should I do next?
Looking forward to your reply soon.Thankkkkkkk so much!

Save and load: SystemError: <method 'decryptInt'> returned a result with an error set

from Pyfhel import Pyfhel, PyPtxt, PyCtxt

def save_and_load():

	HE = Pyfhel()
	HE.contextGen(p=65537)
	HE.keyGen()
	integer1 = 10
	ctxt = HE.encryptInt(integer1)
	ctxt.save("ctxt.c1")
	m = PyCtxt()
	result = m.load("ctxt.c1")
	print(result)
	print(HE.decryptInt(result))


if __name__ == "__main__":
	save_and_load()
	print('------------')

Output:

------------
None
Traceback (most recent call last):
  File "Pyfhel/Pyfhel.pyx", line 338, in Pyfhel.Pyfhel.Pyfhel.decryptInt
RuntimeError: <Pyfhel ERROR> wrong encoding type in PyCtxt

The above exception was the direct cause of the following exception:

[...]
SystemError: <method 'decryptInt' of 'Pyfhel.Pyfhel.Pyfhel' objects> returned a result with an error set

Installation Error "SEAL requires GNUC >= 6"

I downloaded Pyfhel and when i am trying to install errors was occurred. I am attaching the screen shots of errors. Please help me to properly install Pyfhel and use the library.
error1
error2

How do I get public key?

Is there a way to get a copy of the public key so I can send it to another party to have them encrypt the data I want to compute?

Cannot do add, multiply operation (no attribute 'add_encr')

Hi,
I have a problem with using Pyfhel. I installed with pip install command and tested it with file Demo_Batching_SIMD.py.

My environment : pip --version pip 19.0.3, Python 3.6.3, numpy==1.16.2, Pyfhel==2.0.0a5, Cython==0.29.6, g++ --version . g++ (Ubuntu 7.1.0-10ubuntu116.04.york0) 7.1.0, gcc (Ubuntu 7.1.0-10ubuntu116.04.york0) 7.1.0

The error is shown below. Can you help me?

(FHEenv):~/Pyfhel/examples$ python Demo_Batching_SIMD.py 
==============================================================
===================== Pyfhel HELLO WORLD =====================
==============================================================
1. Creating Context and KeyGen in a Pyfhel Object 
2. Encrypting integers
    int  127 -> ctxt1  <class 'Pyfhel.PyCtxt.PyCtxt'>
    int  -2 -> ctxt2  <class 'Pyfhel.PyCtxt.PyCtxt'>
3. Operating with encrypted integers
Traceback (most recent call last):
  File "Demo_Batching_SIMD.py", line 35, in <module>
    ctxtSum = ctxt1 + ctxt2         # `ctxt1 += ctxt2` for quicker inplace operation
  File "Pyfhel/PyCtxt.pyx", line 126, in Pyfhel.PyCtxt.PyCtxt.__add__
AttributeError: 'NoneType' object has no attribute 'add_encr'
(FHEenv):~/Pyfhel/examples$ 

how to install pyfhel in macOS

when I install pyfhel, there is an error called:Pyfhel/SEAL/SEAL/seal/locks.h:12:50: error: 'shared_mutex' is unavailable: introduced in macOS 10.12
can you help me to fix it. Thank you.

Can't load saved PyCtxt

Here is my code:

image_encrypted[0][0].save('a.pt')
PyPtxt.load('a.pt')

Error messages:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-61-d0c7229d6a9a> in <module>
      1 image_encrypted[0][0].save('a.pt')
----> 2 PyPtxt.load("a.pt")

TypeError: descriptor 'load' requires a 'Pyfhel.PyPtxt.PyPtxt' object but received a 'str'

How can I load plaintext from the file?

Tests integration

The test is not integrated into the jenkins build, which makes it harder to make sure new code does not break old code.

Demo Examples for Version 2

Demos and examples have not been updated for version2 for more than 3 months. It will be helpful to provide a document for the functionality and examples on how to use Pyfhel.

Test `test_Pyfhel_2d_encode_decode_array` does not work

Apparently something with the memory views is not working correctly.
Sometimes this testcase works sometimes it does not work.
When creating and decrypting a ciphertext by hand the same happens when using the encryptArray and decryptArray functions.

I don't see why this is happening and in doubt I would suggest removing the two functions: encryptBatch and decryptBatch provide basically the same functionality without being weird. We could let encryptBatch support numpy arrays.

Cannot do addition when I put the loaded ciphertext first

Oh,I met a new problem when I try to do addition between two loaded ciphertext.After serveral try,I found if we put the loaded ciphertext first when doing computation it will throw a bug
AttributeError: 'NoneType' object has no attribute 'add'.In fact,the ciphertext could be loaded and decrypted correctly.So we are now in trouble and need your help.

Tests need improvement

At least the following tests should be added:

  • saving keys and a ciphertext and restoring them again
    • variant: only with public key
    • variant: including private key
    • variant: including relinearization key and rotation key
  • less statefulness. convert as many self.field variables to local variables

Installation/Building: Missing sub-dirs

lorenzo@Lorenzos-Air ~/ghubRepo/Pyfhel $ python3 setup.py build --CYTHONIZE
Traceback (most recent call last):
 File "setup.py", line 63, in <module>
   [os.path.join(AFHEL_PATH, 'Afseal.cpp')])
 File "setup.py", line 13, in scan
   for file in os.listdir(dir):
FileNotFoundError: [Errno 2] No such file or directory: 'Pyfhel/SEAL/SEAL/seal'

Installation: issue using Makefiles

When I execute the following command

./configure
cmake .
make
make install
These are all working fine.
But, an error is still reported when running examples: ImportError: No module named 'Pyfhel'
My system configuration is:Ubuntu16.04 Python 3.5 & Cython on top of C++17 g++==7.5.0

Executing Example code Test_sum_HElib.cpp leads to an Error

Test_sum_HElib.cpp includes a header-file utils/Timer.h which is not available in the repository. Hence the execution "make Test_sum_HElib_x" leads to an error as stated below.

''''''''''

electrical@electrical-desktop:~/Downloads/HElib/src$ make Test_sum_HElib_x
HElib requires NTL version 10.0.0 or higher, see http://shoup.net/ntl
If you get compilation errors, try to add/remove -std=c++11 in Makefile
g++ -g -O2 -std=c++11 -pthread -DFHE_THREADS -DFHE_BOOT_THREADS -fmax-errors=2 -o >Test_sum_HElib_x Test_sum_HElib.cpp fhe.a -L/usr/local/lib -lntl -lgmp -lm
Test_sum_HElib.cpp:2:25: fatal error: utils/Timer.h: No such file or directory
compilation terminated.
Makefile:154: recipe for target 'Test_sum_HElib_x' failed
make: *** [Test_sum_HElib_x] Error 1

''''''''''

Variable Transfer

Hello, i'm having trouble with saving some ciphertexts i guess. I have a code, which is like the simple integer summation test, but im trying to use the load and save functions, so with second he(smth like fhe) to do the summation with public key. Then it returns the answer and decrypts in the main he.
But when i try to decrypt, it says "Pyfhel object at xx........" returned a result with an error set.
My code example:

from Pyfhel import Pyfhel,PyCtxt

he = Pyfhel()

he.contextGen(1000)
he.saveContext(b'C:/Users/burhan/Desktop/last/context.txt')
he.keyGen()
he.savepublicKey(b'C:/Users/burhan/Desktop/last/pk.txt')

v1 = 5
v2 = 4
p1 = PyCtxt()
p2 = PyCtxt()
p3 = PyCtxt()
he.encryptInt(v1,p1)
he.encryptInt(v2,p2)

b = he.noiseLevel(p1)
k = he.noiseLevel(p2)
print(p1)
print(p2)
print(b)
print(k)

p1.save(b'C:/Users/burhan/Desktop/last/p1.c1')
p2.save(b'C:/Users/burhan/Desktop/last/p2.c1')

fhe = Pyfhel()
fhe.restoreContext(b'C:/Users/burhan/Desktop/last/context.txt')
fhe.restorepublicKey(b'C:/Users/burhan/Desktop/last/pk.txt')

p6 = PyCtxt()
p4 = PyCtxt()
p5 = PyCtxt()

p4.load(b'C:/Users/burhan/Desktop/last/p1.c1')
p5.load(b'C:/Users/burhan/Desktop/last/p2.c1')

p6 = fhe.add(p4,p5)
p6.save(b'C:/Users/burhan/Desktop/last/p6.c1')
p3.load(b'C:/Users/burhan/Desktop/last/p6.c1')
a = he.decryptInt(p3)
n = he.noiseLevel(p3)

print(a)
print(n)

I'm assuming its happening because of the windows language coding but im not sure. Thanks for your help , have a nice day!

incorrect result when multiplying 3 numbers

I installed pyfhel and ran some code. The operations performed on 2 numbers worked well but with the 3rd number, the result was wrong. This is my code:

from Pyfhel import Pyfhel
HE = Pyfhel()
HE.contextGen(p=65537)
HE.keyGen()

a = 1.1
b = 2.2
c = 3.0

enc_a = HE.encryptFrac(a)
enc_b = HE.encryptFrac(b)
enc_c = HE.encryptFrac(c)

print(HE.decryptFrac(enc_a*enc_b))
print(HE.decryptFrac(enc_b*enc_c))
print(HE.decryptFrac(enc_a*enc_b*enc_c))

the results are:

2.4199999982956797
6.599999999860302 
2.925756250316916e+18

Shift operations among encrypted values

Hello!

I just wanted to ask whether the shift operator was going to be implemented maybe in the future, since I saw in the old documentation the shift function reported in the class Pyfhel: "shift -> SHIFT each cyphertext inside PyCtxt ctxt for each ID in it."

Thank you!

By the way, amazing work with this library. I'm doing some research in this field and I found using Pyfhel really straightforward.

PLEASE TEST THE INSTALLATION!

I haven't had time to test the installation properly (just one quick install with a virtualenv in the same machine I've developed it). Please come back to me wiht all those juicy errors!

Saving and loading doesn't work for windows10 system.

# -*- coding:utf-8 -*-
from Pyfhel import Pyfhel, PyPtxt, PyCtxt
HE = Pyfhel()
HE.contextGen(p=65537)
HE.keyGen()
integer1 = 10
ctxt = HE.encryptInt(integer1)
ctxt.save("ctxt.c1")
m = PyCtxt()
result = m .load("ctxt.c1")
# print(HE.decryptInt(result))

It is just because the ciphertext exported by the load() function cannot be decrypted on the Windows platform.

Initial Update

The bot created this issue to inform you that pyup.io has been set up on this repo.
Once you have closed it, the bot will open pull requests for updates as soon as they are available.

relinKeyGen does not work

Before I can exponentiate a ciphertext using the power function, I need to generate a relinearization key. But after invoking relinKeyGen and then using power, I still get the error message:
RuntimeError: Relinearization key not initialized

It seems that the culprit may be in the following line:

self.afseal.rotateKeyGen(bitCount)

Runtime error with classification models on data encrypted with Pyfhel

Hi,

I recently got my hands-on with this amazing library. I was able to encrypt/decrypt a simple image with help of Pyfhel's encrypt/decrypt operations. The image was converted to a 1D array first and then encryptBatch was applied. The resulted PyCtxt was decrypted with decryptBatch and converted back to image matrix while preserving its shape to get the original image.

I need to apply a classification model on this encrypted data now. The model should train with encrypted data and an unencrypted or encrypted label and predict the output.

However, I am getting following runtime error while training the model.


RuntimeError Traceback (most recent call last)
in
----> 1 clf = LogisticRegression(random_state=42,verbose=10).fit(X_train, y_train)

~/anaconda3/lib/python3.7/site-packages/sklearn/linear_model/_logistic.py in fit(self, X, y, sample_weight)
1525
1526 X, y = check_X_y(X, y, accept_sparse='csr', dtype=dtype, order="C",
-> 1527 accept_large_sparse=solver != 'liblinear')
1528 check_classification_targets(y)
1529 self.classes
= np.unique(y)

~/anaconda3/lib/python3.7/site-packages/sklearn/utils/validation.py in check_X_y(X, y, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, multi_output, ensure_min_samples, ensure_min_features, y_numeric, warn_on_dtype, estimator)
753 ensure_min_features=ensure_min_features,
754 warn_on_dtype=warn_on_dtype,
--> 755 estimator=estimator)
756 if multi_output:
757 y = check_array(y, 'csr', force_all_finite=True, ensure_2d=False,

~/anaconda3/lib/python3.7/site-packages/sklearn/utils/validation.py in check_array(array, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, warn_on_dtype, estimator)
529 array = array.astype(dtype, casting="unsafe", copy=False)
530 else:
--> 531 array = np.asarray(array, order=order, dtype=dtype)
532 except ComplexWarning:
533 raise ValueError("Complex data not supported

~/anaconda3/lib/python3.7/site-packages/numpy/core/_asarray.py in asarray(a, dtype, order)
83
84 """
---> 85 return array(a, dtype, copy=False, order=order)
86
87

~/anaconda3/lib/python3.7/site-packages/pandas/core/series.py in array(self, dtype)
752 dtype='datetime64[ns]')
753 """
--> 754 return np.asarray(self.array, dtype)
755
756 # ----------------------------------------------------------------------

~/anaconda3/lib/python3.7/site-packages/numpy/core/_asarray.py in asarray(a, dtype, order)
83
84 """
---> 85 return array(a, dtype, copy=False, order=order)
86
87

~/anaconda3/lib/python3.7/site-packages/pandas/core/arrays/numpy_.py in array(self, dtype)
182
183 def array(self, dtype=None) -> np.ndarray:
--> 184 return np.asarray(self._ndarray, dtype=dtype)
185
186 _HANDLED_TYPES = (np.ndarray, numbers.Number)

~/anaconda3/lib/python3.7/site-packages/numpy/core/_asarray.py in asarray(a, dtype, order)
83
84 """
---> 85 return array(a, dtype, copy=False, order=order)
86
87

Pyfhel/PyCtxt.pyx in Pyfhel.PyCtxt.PyCtxt.float()
RuntimeError: wrong PyCtxt encoding (not FRACTIONAL)

Windows10 -> ValueError: Buffer dtype mismatch, expected 'int64_t' but got 'long'

When running the Demo_Encrypting.py, result in a Windows10 Python3 is:

==============================================================
===================== Pyfhel ENCRYPTING ======================
==============================================================
1. Creating Context and KeyGen in a Pyfhel Object
2. Encrypting integers with encryptInt
    Empty created ctxt_i2:  <Pyfhel Ciphertext, encoding=UNDEFINED, size=2>
    int  94 -> ctxt_i1  <Pyfhel Ciphertext, encoding=INTEGER, size=2>
    int  -235 -> ctxt_i2  <Pyfhel Ciphertext, encoding=INTEGER, size=2>
3. Encrypting floating point values with encryptFrac
    float  3.5 -> ctxt_f1  <Pyfhel Ciphertext, encoding=FRACTIONAL, size=2>
    float  -7.8 -> ctxt_f2  <Pyfhel Ciphertext, encoding=FRACTIONAL, size=2>
4. Encrypting lists of integers using batching with encryptBatch
    list  [1, 2, 3, 4, 5, 6] -> ctxt_b1  <Pyfhel Ciphertext, encoding=BATCH, size=2>
    list  [-2, 3, -4, -3, 2, -1] -> ctxt_b2  <Pyfhel Ciphertext, encoding=BATCH, size=2>
5. Encrypting numpy 1D integer vectors using batching encryptArray
Traceback (most recent call last):
  File ".\Demo_Encrypting.py", line 49, in <module>
    ctxt_a1 = HE.encryptArray(array1)   # Encrypting array1 in a new PyCtxt with encryptArray
  File "Pyfhel/Pyfhel.pyx", line 228, in Pyfhel.Pyfhel.Pyfhel.encryptArray
ValueError: Buffer dtype mismatch, expected 'int64_t' but got 'long'

Maybe related to https://stackoverflow.com/questions/32262976/cython-buffer-type-mismatch-expected-int-but-got-long?

Executing Demo_HelloWorld.py leads to an Error

Hello,

I installed Pyfhel use pip install Pyfhel and use python3.6, then ran Pyfhel/examples/Demo_HelloWorld.py, but got the following error:

==============================================================
===================== Pyfhel HELLO WORLD =====================
==============================================================
1. Creating Context and KeyGen in a Pyfhel Object 
2. Encrypting integers
Traceback (most recent call last):
  File "Demo_HelloWorld.py", line 29, in <module>
    ctxt1 = HE.encryptInt(integer1) # Encryption makes use of the public key
  File "Pyfhel/Pyfhel.pyx", line 150, in Pyfhel.Pyfhel.Pyfhel.encryptInt
  File "Pyfhel/Pyfhel.pyx", line 168, in Pyfhel.Pyfhel.Pyfhel.encryptInt
RuntimeError: cannot resize aliased Ciphertext

HELib Improved Makefile

Can this file be used to install HELib.

when i tried to make HELib using this file it resulted in error:

`libtool: link: g++  -fPIC -DPIC -shared   .libs/NumbTh.o .libs/timing.o .libs/bluestein.o .libs/PAlgebra.o  .libs/CModulus.o .libs/FHEContext.o .libs/IndexSet.o .libs/DoubleCRT.o .libs/FHE.o .libs/KeySwitching.o .libs/Ctxt.o .libs/EncryptedArray.o .libs/replicate.o .libs/hypercube.o .libs/matching.o .libs/powerful.o .libs/BenesNetwork.o .libs/permutations.o .libs/PermNetwork.o .libs/OptimizePermutations.o .libs/eqtesting.o .libs/polyEval.o .libs/extractDigits.o .libs/EvalMap.o .libs/recryption.o .libs/debugging.o .libs/matmul.o .libs/intraSlot.o .libs/binaryArith.o .libs/binaryCompare.o .libs/tableLookup.o   -L/usr/local/lib -lntl /usr/local/lib/libgmp.so -lstdc++ -lm -lc -lgcc_s   -g -O2 -pthread   -pthread -Wl,-soname -Wl,libfhe.so.1 -o .libs/libfhe.so.1.0.0`           

/usr/bin/ld: /usr/local/lib/libntl.a(FFT.o): relocation R_X86_64_32 against .rodata.str1.8' can not be used when making a shared object; recompile with -fPIC /usr/local/lib/libntl.a: error adding symbols: Bad value collect2: error: ld returned 1 exit status Makefile:159: recipe for target "libfhe.la" failed make: *** [libfhe.la] Error 1

thank you

Installation with pip : "ModuleNotFoundError: No module named 'numpy'"

Hello,

When installing Pyfhel with pip I got the following error :

Collecting Pyfhel
  Downloading https://files.pythonhosted.org/packages/36/ff/dddccc7f782acb14f62f2cd66bf54b90269fd7a30e9771a1378df2ffca9a/Pyfhel-2.0.0a4.tar.gz (745kB)
    100% |β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 747kB 2.8MB/s 
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-install-e3lbn659/Pyfhel/setup.py", line 7, in <module>
        import numpy
    ModuleNotFoundError: No module named 'numpy'
    
    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-e3lbn659/Pyfhel/

I think, it means that numpy should be moved from install_requires to setup_requires in setup.py.

"pip install pyfhel" goes tits up without numpy dep

Pyfhel does not automatically detect numpy as a dependency and install it.
Rather, it throws a traceback error "numpy not found" (in PyCharm).

Edit: after I manually installed numpy, the pyfhel install command executed fine.

Env: Python 3.7.8 (tags/v3.7.8:4b47a5b6ba, Jun 28 2020, 08:53:46) [MSC v.1916 64 bit (AMD64)] on win32

Numpy/Pandas Mean gives unencrypted result

I have encrypted every value in a column in a pandas dataframe .
Now when I use np.mean() on that column, it is returning the unencrypted result.
I am expecting it to return the encrypted mean.
Is this an expected behaviour?

How do I implement SIMD operations?

Dear developer, I downloaded this file earlier and found the Demo_Batching_SIMD.py file in examples does not mention SIMD operation, Could you show me an example of SIMD operation? Thanks.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.