lightphe


Namelightphe JSON
Version 0.0.8 PyPI version JSON
download
home_pagehttps://github.com/serengil/LightPHE
SummaryA Lightweight Partially Homomorphic Encryption Library for Python
upload_time2024-08-17 07:17:20
maintainerNone
docs_urlNone
authorSefik Ilkin Serengil
requires_python>=3.5.5
licenseNone
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # LightPHE

<div align="center">

[![PyPI Downloads](https://static.pepy.tech/personalized-badge/lightphe?period=total&units=international_system&left_color=grey&right_color=blue&left_text=downloads)](https://pepy.tech/project/lightphe)
[![Stars](https://img.shields.io/github/stars/serengil/LightPHE?color=yellow&style=flat&label=%E2%AD%90%20stars)](https://github.com/serengil/LightPHE/stargazers)
[![Tests](https://github.com/serengil/LightPHE/actions/workflows/tests.yml/badge.svg)](https://github.com/serengil/LightPHE/actions/workflows/tests.yml)
[![License](http://img.shields.io/:license-MIT-green.svg?style=flat)](https://github.com/serengil/LightPHE/blob/master/LICENSE)
[![DOI](http://img.shields.io/:DOI-10.48550/arXiv.2408.05219-blue.svg?style=flat)](https://arxiv.org/abs/2408.05219)

[![Blog](https://img.shields.io/:blog-sefiks.com-blue.svg?style=flat&logo=wordpress)](https://sefiks.com)
[![YouTube](https://img.shields.io/:youtube-@sefiks-red.svg?style=flat&logo=youtube)](https://www.youtube.com/@sefiks?sub_confirmation=1)
[![Twitter](https://img.shields.io/:follow-@serengil-blue.svg?style=flat&logo=x)](https://twitter.com/intent/user?screen_name=serengil)

[![Support me on Patreon](https://img.shields.io/endpoint.svg?url=https%3A%2F%2Fshieldsio-patreon.vercel.app%2Fapi%3Fusername%3Dserengil%26type%3Dpatrons&style=flat)](https://www.patreon.com/serengil?repo=lightphe)
[![GitHub Sponsors](https://img.shields.io/github/sponsors/serengil?logo=GitHub&color=lightgray)](https://github.com/sponsors/serengil)
[![Buy Me a Coffee](https://img.shields.io/badge/-buy_me_a%C2%A0coffee-gray?logo=buy-me-a-coffee)](https://buymeacoffee.com/serengil)

</div>

<p align="center"><img src="https://raw.githubusercontent.com/serengil/LightPHE/master/icons/phi.png" width="200" height="240"></p>

LightPHE is a lightweight partially homomorphic encryption library for python. It is a hybrid homomoprhic encryption library wrapping many schemes such as [`RSA`](https://sefiks.com/2023/03/06/a-step-by-step-partially-homomorphic-encryption-example-with-rsa-in-python/), [`ElGamal`](https://sefiks.com/2023/03/27/a-step-by-step-partially-homomorphic-encryption-example-with-elgamal-in-python/), [`Exponential ElGamal`](https://sefiks.com/2023/03/27/a-step-by-step-partially-homomorphic-encryption-example-with-elgamal-in-python/), [`Elliptic Curve ElGamal`](https://sefiks.com/2018/08/21/elliptic-curve-elgamal-encryption/), [`Paillier`](https://sefiks.com/2023/04/03/a-step-by-step-partially-homomorphic-encryption-example-with-paillier-in-python/), [`Damgard-Jurik`](https://sefiks.com/2023/10/20/a-step-by-step-partially-homomorphic-encryption-example-with-damgard-jurik-in-python/), [`Okamoto–Uchiyama`](https://sefiks.com/2023/10/20/a-step-by-step-partially-homomorphic-encryption-example-with-okamoto-uchiyama-in-python/), [`Benaloh`](https://sefiks.com/2023/10/06/a-step-by-step-partially-homomorphic-encryption-example-with-benaloh-in-python-from-scratch/), [`Naccache–Stern`](https://sefiks.com/2023/10/26/a-step-by-step-partially-homomorphic-encryption-example-with-naccache-stern-in-python/), [`Goldwasser–Micali`](https://sefiks.com/2023/10/27/a-step-by-step-partially-homomorphic-encryption-example-with-goldwasser-micali-in-python/).

# Partially vs Fully Homomorphic Encryption

Even though fully homomorphic encryption (FHE) has become available in recent times, but when considering the trade-offs, LightPHE emerges as a more efficient and practical choice. If your specific task doesn't demand the full homomorphic capabilities, opting for partial homomorphism with LightPHE is the logical decision.

- 🏎️ Notably faster
- πŸ’» Demands fewer computational resources
- πŸ“ Generating much smaller ciphertexts
- πŸ”‘ Distributing much smaller keys
- 🧠 Well-suited for memory-constrained environments
- βš–οΈ Strikes a favorable balance for practical use cases

# Installation [![PyPI](https://img.shields.io/pypi/v/lightphe.svg)](https://pypi.org/project/lightphe/)

The easiest way to install the LightPHE package is to install it from python package index (PyPI).

```shell
pip install lightphe
```

Then you will be able to import the library and use its functionalities.

```python
from lightphe import LightPHE
```

# Summary of Homomorphic Features of Different Cryptosystems in LightPHE

In summary, LightPHE is covering following algorithms and these are partially homomorphic with respect to the operations mentioned in the following table.

| Algorithm | Multiplicatively<br>Homomorphic | Additively<br>Homomorphic | Multiplication with a Plain Constant | Exclusively<br>Homomorphic | Regeneration<br>of Ciphertext |
| --- | --- | --- | --- | --- | --- |
| RSA | βœ… | ❌ | ❌ | ❌ | ❌ |
| ElGamal | βœ… | ❌ | ❌ | ❌ | βœ… |
| Exponential ElGamal | ❌ | βœ… | βœ… | ❌ | βœ… |
| Elliptic Curve ElGamal | ❌ | βœ… | βœ… | ❌ | ❌ |
| Paillier | ❌ | βœ… | βœ… | ❌ | βœ… |
| Damgard-Jurik | ❌ | βœ… | βœ… | ❌ | βœ… |
| Benaloh | ❌ | βœ… | βœ… | ❌ | βœ… |
| Naccache-Stern | ❌ | βœ… | βœ… | ❌ | βœ… |
| Okamoto-Uchiyama | ❌ | βœ… | βœ… | ❌ | βœ… |
| Goldwasser-Micali | ❌ | ❌ | ❌ | βœ… | ❌ |

# Building cryptosystem

Once you imported the library, then you can build a cryptosystem for several algorithms. This basically generates private and public key pair.

```python
algorithms = [
  "RSA",
  "ElGamal",
  "Exponential-ElGamal",
  "Paillier",
  "Damgard-Jurik",
  "Okamoto-Uchiyama",
  "Benaloh",
  "Naccache-Stern",
  "Goldwasser-Micali",
  "EllipticCurve-ElGamal"
]

cs = LightPHE(algorithm_name = algorithms[0])
```

# Encryption & Decryption

Once you built your cryptosystem, you will be able to encrypt and decrypt messages with the built cryptosystem.

```python
# define plaintext
m = 17

# calculate ciphertext
c = cs.encrypt(m)

# proof of work
assert cs.decrypt(c) == m
```

# Homomorphic Operations

Once you have the ciphertext, you will be able to perform homomorphic operations on encrypted data without holding private key. For instance, Paillier is homomorphic with respect to the addition. In other words, decryption of the addition of two ciphertexts is equivalent to addition of plaintexts.

### On-Prem Encryption

This Python code snippet demonstrates how to generate a private-public key pair using the Paillier cryptosystem via the LightPHE library. First, an instance of the LightPHE class is created with the Paillier algorithm. Then, the public key is exported and saved to a file named "public.txt" to build the same cryptosystem with only public key in the cloud side later. The code defines two plaintext values, m1 and m2, respectively. These plaintext values are encrypted to generate ciphertexts c1 and c2 using the public key. Finally, the ciphertexts c1 and c2 are prepared to be sent to a cloud system for secure processing or storage.

```python
# generate private-public key pair
cs = LightPHE(algorithm_name = "Paillier")

# export public key to build same cryptosystem with only public key in the cloud
cs.export_keys(target_file = "public.txt", public = True)

# export private key to build same cryptosystem on-prem later
cs.export_keys(target_file = "private.txt", public = False)

# define plaintexts
m1 = 17
m2 = 23

# calculate ciphertexts
c1 = cs.encrypt(m1).value
c2 = cs.encrypt(m2).value

# send c1 and c2 pair to a cloud system
```

### Homomorphic Operations on Cloud

This Python code snippet illustrates how to handle encrypted data on the cloud side using the Paillier cryptosystem with the LightPHE library. Upon receiving the encrypted values c1 and c2, the cloud system initializes the cryptosystem using the exported public key stored in public.txt. To ensure the security of the data, a test is performed to confirm that the cloud system cannot decrypt c1 and c2 without the private key. This is done using the pytest library, which raises a ValueError if decryption is attempted, verifying that decryption is not possible without the private key. Finally, the code demonstrates homomorphic addition by adding the two ciphertexts, resulting in a new ciphertext c3 that represents the encrypted sum of the original plaintext values.

```python
# cloud side receives encrypted c1 and c2

# restore cryptosystem with the exported public key
cs = LightPHE(algorithm_name = "Paillier", key_file = "public.txt")

# convert c1 and c2 to ciphertext objects
c1 = cs.create_ciphertext_obj(c1)
c2 = cs.create_ciphertext_obj(c2)

# confirm that cloud cannot decrypt c1
with pytest.raises(ValueError, match="You must have private key to perform decryption"):
  cs.decrypt(c1)

# confirm that cloud cannot decrypt c2
with pytest.raises(ValueError, match="You must have private key to perform decryption"):
  cs.decrypt(c2)

# homomorphic addition - private key not required
c3 = c1 + c2

# confirm that cloud cannot decrypt c3
with pytest.raises(ValueError, match="You must have private key to perform decryption"):
  cs.decrypt(c3)
```

### On-Prem Decryption

This Python code snippet demonstrates the final step in a secure computation process using homomorphic encryption with the LightPHE library. After receiving the ciphertext c3 from the cloud, which is the result of homomorphic addition of two ciphertexts c1 and c2, the on-premises system (which has the private key) decrypts c3 to verify the result. The decrypted value is then asserted to be equal to the sum of the original plaintext values m1 and m2. This step ensures the correctness of the homomorphic computation performed by the cloud.

```python
# on-prem side receives c3 from cloud

# restore cryptosystem with the exported private key
cs = LightPHE(algorithm_name = "Paillier", key_file = "private.txt")

# proof of work - private key required
assert cs.decrypt(c3) == m1 + m2
```

### Scalar Multiplication

Besides, Paillier is supporting multiplying ciphertexts by a known plain constant. This Python code snippet demonstrates how to perform scalar multiplication on encrypted data using homomorphic encryption with the LightPHE library. The factor k is set to 1.05, representing a 5% increase. On the cloud side, this factor is used to multiply the ciphertext c1, resulting in a new ciphertext c4. When the on-premises system, which holds the private key, receives c4, it decrypts it and verifies that the decrypted value matches the original plaintext m1 scaled by k (i.e., 1.05 * m1). This ensures that the homomorphic scalar multiplication was performed correctly on the encrypted data.

```python
# increasing something 5%
k = 1.05

# scalar multiplication - cloud (private key is not required)
c4 = k * c1

# proof of work on-prem - private key is required
assert cs.decrypt(c4) == k * m1
```

### Ciphertext Regeneration

Similar to the most of additively homomorphic algorithms, Paillier lets you to regenerate ciphertext while you are not breaking its plaintext restoration. You may consider to do this re-generation many times to have stronger ciphertexts.

```python
c1_prime = cs.regenerate_ciphertext(c1)
assert c1_prime.value != c1.value
assert cs.decrypt(c1_prime) == m1
assert cs.decrypt(c1) == m1
```

### Unsupported Operations

Finally, if you try to perform an operation that algorithm does not support, then an exception will be thrown. For instance, Paillier is not homomorphic with respect to the multiplication or xor. To put it simply, you cannot multiply two ciphertexts. If you enforce this calculation, you will have an exception.

```python
# pailier is not multiplicatively homomorphic
with pytest.raises(ValueError, match="Paillier is not homomorphic with respect to the multiplication"):
  c1 * c2

# pailier is not exclusively homomorphic
with pytest.raises(ValueError, match="Paillier is not homomorphic with respect to the exclusive or"):
  c1 ^ c2
```

However, if you tried to multiply ciphertexts with RSA, or xor ciphertexts with Goldwasser-Micali, these will be succeeded because those cryptosystems support those homomorphic operations.

# Working with vectors

You can encrypt the output vectors of machine learning models with LightPHE. These encrypted tensors come with homomorphic operation support including homomorphic addition, element-wise multiplication and scalar multiplication.

```python
# build an additively homomorphic cryptosystem
cs = LightPHE(algorithm_name="Paillier")

# define plain tensors
t1 = [1.005, 2.05, 3.5, 4]
t2 = [5, 6.2, 7.002, 8.02]

# encrypt tensors
c1 = cs.encrypt(t1)
c2 = cs.encrypt(t2)

# perform homomorphic addition
c3 = c1 + c2

# perform homomorphic element-wise multiplication
c4 = c1 * c2

# perform homomorphic scalar multiplication
k = 5
c5 = k * c1

# decrypt the addition tensor
t3 = cs.decrypt(c3)

# decrypt the element-wise multiplied tensor
t4 = cs.decrypt(c4)

# decrypt the scalar multiplied tensor
t5 = cs.decrypt(c5)

# data validations
threshold = 0.5
for i in range(0, len(t1)):
   assert abs((t1[i] + t2[i]) - t3[i]) < threshold
   assert abs((t1[i] * t2[i]) - t4[i]) < threshold
   assert abs((t1[i] * k) - t5[i]) < threshold
```

Unfortunately, vector multiplication (dot product) requires both homomorphic addition and homomorphic multiplication and this cannot be done with partially homomorphic encryption algorithms.

# Contributing

All PRs are more than welcome! If you are planning to contribute a large patch, please create an issue first to get any upfront questions or design decisions out of the way first.

You should be able run `make test` and `make lint` commands successfully before committing. Once a PR is created, GitHub test workflow will be run automatically and unit test results will be available in [GitHub actions](https://github.com/serengil/LightPHE/actions/workflows/tests.yml) before approval. Besides, workflow will evaluate the code with pylint as well.

# Support

There are many ways to support a project - starring⭐️ the GitHub repo is just one πŸ™

You can also support this work on [Patreon](https://www.patreon.com/serengil?repo=lightphe), [GitHub Sponsors](https://github.com/sponsors/serengil) or [Buy Me a Coffee](https://buymeacoffee.com/serengil).

<a href="https://www.patreon.com/serengil?repo=lightphe">
<img src="https://raw.githubusercontent.com/serengil/LightPHE/master/icons/patreon.png" width="30%" height="30%">
</a>

<a href="https://buymeacoffee.com/serengil">
<img src="https://raw.githubusercontent.com/serengil/LightPHE/master/icons/bmc-button.png" width="25%" height="25%">
</a>

Also, your company's logo will be shown on README on GitHub if you become sponsor in gold, silver or bronze tiers.

# Citation

Please cite LightPHE in your publications if it helps your research. Here is its BibTex entry:

```BibTeX
@misc{serengil2024lightphe,
   title     = {LightPHE: Integrating Partially Homomorphic Encryption into Python with Extensive Cloud Environment Evaluations}, 
   author    = {Serengil, Sefik Ilkin and Ozpinar, Alper},
   year      = {2024},
   publisher = {arXiv},
   url       = {https://arxiv.org/abs/2408.05219},
   doi       = {10.48550/arXiv.2408.05219}
}
```

Also, if you use LightPHE in your projects, please add `lightphe` in the `requirements.txt`.

# License

LightPHE is licensed under the MIT License - see [`LICENSE`](https://github.com/serengil/LightPHE/blob/master/LICENSE) for more details.



            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/serengil/LightPHE",
    "name": "lightphe",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.5.5",
    "maintainer_email": null,
    "keywords": null,
    "author": "Sefik Ilkin Serengil",
    "author_email": "serengil@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/ab/79/79e0f06e95049e77d4915c71fec5168b9ecf8b09be7619fed9324869f532/lightphe-0.0.8.tar.gz",
    "platform": null,
    "description": "# LightPHE\n\n<div align=\"center\">\n\n[![PyPI Downloads](https://static.pepy.tech/personalized-badge/lightphe?period=total&units=international_system&left_color=grey&right_color=blue&left_text=downloads)](https://pepy.tech/project/lightphe)\n[![Stars](https://img.shields.io/github/stars/serengil/LightPHE?color=yellow&style=flat&label=%E2%AD%90%20stars)](https://github.com/serengil/LightPHE/stargazers)\n[![Tests](https://github.com/serengil/LightPHE/actions/workflows/tests.yml/badge.svg)](https://github.com/serengil/LightPHE/actions/workflows/tests.yml)\n[![License](http://img.shields.io/:license-MIT-green.svg?style=flat)](https://github.com/serengil/LightPHE/blob/master/LICENSE)\n[![DOI](http://img.shields.io/:DOI-10.48550/arXiv.2408.05219-blue.svg?style=flat)](https://arxiv.org/abs/2408.05219)\n\n[![Blog](https://img.shields.io/:blog-sefiks.com-blue.svg?style=flat&logo=wordpress)](https://sefiks.com)\n[![YouTube](https://img.shields.io/:youtube-@sefiks-red.svg?style=flat&logo=youtube)](https://www.youtube.com/@sefiks?sub_confirmation=1)\n[![Twitter](https://img.shields.io/:follow-@serengil-blue.svg?style=flat&logo=x)](https://twitter.com/intent/user?screen_name=serengil)\n\n[![Support me on Patreon](https://img.shields.io/endpoint.svg?url=https%3A%2F%2Fshieldsio-patreon.vercel.app%2Fapi%3Fusername%3Dserengil%26type%3Dpatrons&style=flat)](https://www.patreon.com/serengil?repo=lightphe)\n[![GitHub Sponsors](https://img.shields.io/github/sponsors/serengil?logo=GitHub&color=lightgray)](https://github.com/sponsors/serengil)\n[![Buy Me a Coffee](https://img.shields.io/badge/-buy_me_a%C2%A0coffee-gray?logo=buy-me-a-coffee)](https://buymeacoffee.com/serengil)\n\n</div>\n\n<p align=\"center\"><img src=\"https://raw.githubusercontent.com/serengil/LightPHE/master/icons/phi.png\" width=\"200\" height=\"240\"></p>\n\nLightPHE is a lightweight partially homomorphic encryption library for python. It is a hybrid homomoprhic encryption library wrapping many schemes such as [`RSA`](https://sefiks.com/2023/03/06/a-step-by-step-partially-homomorphic-encryption-example-with-rsa-in-python/), [`ElGamal`](https://sefiks.com/2023/03/27/a-step-by-step-partially-homomorphic-encryption-example-with-elgamal-in-python/), [`Exponential ElGamal`](https://sefiks.com/2023/03/27/a-step-by-step-partially-homomorphic-encryption-example-with-elgamal-in-python/), [`Elliptic Curve ElGamal`](https://sefiks.com/2018/08/21/elliptic-curve-elgamal-encryption/), [`Paillier`](https://sefiks.com/2023/04/03/a-step-by-step-partially-homomorphic-encryption-example-with-paillier-in-python/), [`Damgard-Jurik`](https://sefiks.com/2023/10/20/a-step-by-step-partially-homomorphic-encryption-example-with-damgard-jurik-in-python/), [`Okamoto\u2013Uchiyama`](https://sefiks.com/2023/10/20/a-step-by-step-partially-homomorphic-encryption-example-with-okamoto-uchiyama-in-python/), [`Benaloh`](https://sefiks.com/2023/10/06/a-step-by-step-partially-homomorphic-encryption-example-with-benaloh-in-python-from-scratch/), [`Naccache\u2013Stern`](https://sefiks.com/2023/10/26/a-step-by-step-partially-homomorphic-encryption-example-with-naccache-stern-in-python/), [`Goldwasser\u2013Micali`](https://sefiks.com/2023/10/27/a-step-by-step-partially-homomorphic-encryption-example-with-goldwasser-micali-in-python/).\n\n# Partially vs Fully Homomorphic Encryption\n\nEven though fully homomorphic encryption (FHE) has become available in recent times, but when considering the trade-offs, LightPHE emerges as a more efficient and practical choice. If your specific task doesn't demand the full homomorphic capabilities, opting for partial homomorphism with LightPHE is the logical decision.\n\n- \ud83c\udfce\ufe0f Notably faster\n- \ud83d\udcbb Demands fewer computational resources\n- \ud83d\udccf Generating much smaller ciphertexts\n- \ud83d\udd11 Distributing much smaller keys\n- \ud83e\udde0 Well-suited for memory-constrained environments\n- \u2696\ufe0f Strikes a favorable balance for practical use cases\n\n# Installation [![PyPI](https://img.shields.io/pypi/v/lightphe.svg)](https://pypi.org/project/lightphe/)\n\nThe easiest way to install the LightPHE package is to install it from python package index (PyPI).\n\n```shell\npip install lightphe\n```\n\nThen you will be able to import the library and use its functionalities.\n\n```python\nfrom lightphe import LightPHE\n```\n\n# Summary of Homomorphic Features of Different Cryptosystems in LightPHE\n\nIn summary, LightPHE is covering following algorithms and these are partially homomorphic with respect to the operations mentioned in the following table.\n\n| Algorithm | Multiplicatively<br>Homomorphic | Additively<br>Homomorphic | Multiplication with a Plain Constant | Exclusively<br>Homomorphic | Regeneration<br>of Ciphertext |\n| --- | --- | --- | --- | --- | --- |\n| RSA | \u2705 | \u274c | \u274c | \u274c | \u274c |\n| ElGamal | \u2705 | \u274c | \u274c | \u274c | \u2705 |\n| Exponential ElGamal | \u274c | \u2705 | \u2705 | \u274c | \u2705 |\n| Elliptic Curve ElGamal | \u274c | \u2705 | \u2705 | \u274c | \u274c |\n| Paillier | \u274c | \u2705 | \u2705 | \u274c | \u2705 |\n| Damgard-Jurik | \u274c | \u2705 | \u2705 | \u274c | \u2705 |\n| Benaloh | \u274c | \u2705 | \u2705 | \u274c | \u2705 |\n| Naccache-Stern | \u274c | \u2705 | \u2705 | \u274c | \u2705 |\n| Okamoto-Uchiyama | \u274c | \u2705 | \u2705 | \u274c | \u2705 |\n| Goldwasser-Micali | \u274c | \u274c | \u274c | \u2705 | \u274c |\n\n# Building cryptosystem\n\nOnce you imported the library, then you can build a cryptosystem for several algorithms. This basically generates private and public key pair.\n\n```python\nalgorithms = [\n  \"RSA\",\n  \"ElGamal\",\n  \"Exponential-ElGamal\",\n  \"Paillier\",\n  \"Damgard-Jurik\",\n  \"Okamoto-Uchiyama\",\n  \"Benaloh\",\n  \"Naccache-Stern\",\n  \"Goldwasser-Micali\",\n  \"EllipticCurve-ElGamal\"\n]\n\ncs = LightPHE(algorithm_name = algorithms[0])\n```\n\n# Encryption & Decryption\n\nOnce you built your cryptosystem, you will be able to encrypt and decrypt messages with the built cryptosystem.\n\n```python\n# define plaintext\nm = 17\n\n# calculate ciphertext\nc = cs.encrypt(m)\n\n# proof of work\nassert cs.decrypt(c) == m\n```\n\n# Homomorphic Operations\n\nOnce you have the ciphertext, you will be able to perform homomorphic operations on encrypted data without holding private key. For instance, Paillier is homomorphic with respect to the addition. In other words, decryption of the addition of two ciphertexts is equivalent to addition of plaintexts.\n\n### On-Prem Encryption\n\nThis Python code snippet demonstrates how to generate a private-public key pair using the Paillier cryptosystem via the LightPHE library. First, an instance of the LightPHE class is created with the Paillier algorithm. Then, the public key is exported and saved to a file named \"public.txt\" to build the same cryptosystem with only public key in the cloud side later. The code defines two plaintext values, m1 and m2, respectively. These plaintext values are encrypted to generate ciphertexts c1 and c2 using the public key. Finally, the ciphertexts c1 and c2 are prepared to be sent to a cloud system for secure processing or storage.\n\n```python\n# generate private-public key pair\ncs = LightPHE(algorithm_name = \"Paillier\")\n\n# export public key to build same cryptosystem with only public key in the cloud\ncs.export_keys(target_file = \"public.txt\", public = True)\n\n# export private key to build same cryptosystem on-prem later\ncs.export_keys(target_file = \"private.txt\", public = False)\n\n# define plaintexts\nm1 = 17\nm2 = 23\n\n# calculate ciphertexts\nc1 = cs.encrypt(m1).value\nc2 = cs.encrypt(m2).value\n\n# send c1 and c2 pair to a cloud system\n```\n\n### Homomorphic Operations on Cloud\n\nThis Python code snippet illustrates how to handle encrypted data on the cloud side using the Paillier cryptosystem with the LightPHE library. Upon receiving the encrypted values c1 and c2, the cloud system initializes the cryptosystem using the exported public key stored in public.txt. To ensure the security of the data, a test is performed to confirm that the cloud system cannot decrypt c1 and c2 without the private key. This is done using the pytest library, which raises a ValueError if decryption is attempted, verifying that decryption is not possible without the private key. Finally, the code demonstrates homomorphic addition by adding the two ciphertexts, resulting in a new ciphertext c3 that represents the encrypted sum of the original plaintext values.\n\n```python\n# cloud side receives encrypted c1 and c2\n\n# restore cryptosystem with the exported public key\ncs = LightPHE(algorithm_name = \"Paillier\", key_file = \"public.txt\")\n\n# convert c1 and c2 to ciphertext objects\nc1 = cs.create_ciphertext_obj(c1)\nc2 = cs.create_ciphertext_obj(c2)\n\n# confirm that cloud cannot decrypt c1\nwith pytest.raises(ValueError, match=\"You must have private key to perform decryption\"):\n  cs.decrypt(c1)\n\n# confirm that cloud cannot decrypt c2\nwith pytest.raises(ValueError, match=\"You must have private key to perform decryption\"):\n  cs.decrypt(c2)\n\n# homomorphic addition - private key not required\nc3 = c1 + c2\n\n# confirm that cloud cannot decrypt c3\nwith pytest.raises(ValueError, match=\"You must have private key to perform decryption\"):\n  cs.decrypt(c3)\n```\n\n### On-Prem Decryption\n\nThis Python code snippet demonstrates the final step in a secure computation process using homomorphic encryption with the LightPHE library. After receiving the ciphertext c3 from the cloud, which is the result of homomorphic addition of two ciphertexts c1 and c2, the on-premises system (which has the private key) decrypts c3 to verify the result. The decrypted value is then asserted to be equal to the sum of the original plaintext values m1 and m2. This step ensures the correctness of the homomorphic computation performed by the cloud.\n\n```python\n# on-prem side receives c3 from cloud\n\n# restore cryptosystem with the exported private key\ncs = LightPHE(algorithm_name = \"Paillier\", key_file = \"private.txt\")\n\n# proof of work - private key required\nassert cs.decrypt(c3) == m1 + m2\n```\n\n### Scalar Multiplication\n\nBesides, Paillier is supporting multiplying ciphertexts by a known plain constant. This Python code snippet demonstrates how to perform scalar multiplication on encrypted data using homomorphic encryption with the LightPHE library. The factor k is set to 1.05, representing a 5% increase. On the cloud side, this factor is used to multiply the ciphertext c1, resulting in a new ciphertext c4. When the on-premises system, which holds the private key, receives c4, it decrypts it and verifies that the decrypted value matches the original plaintext m1 scaled by k (i.e., 1.05 * m1). This ensures that the homomorphic scalar multiplication was performed correctly on the encrypted data.\n\n```python\n# increasing something 5%\nk = 1.05\n\n# scalar multiplication - cloud (private key is not required)\nc4 = k * c1\n\n# proof of work on-prem - private key is required\nassert cs.decrypt(c4) == k * m1\n```\n\n### Ciphertext Regeneration\n\nSimilar to the most of additively homomorphic algorithms, Paillier lets you to regenerate ciphertext while you are not breaking its plaintext restoration. You may consider to do this re-generation many times to have stronger ciphertexts.\n\n```python\nc1_prime = cs.regenerate_ciphertext(c1)\nassert c1_prime.value != c1.value\nassert cs.decrypt(c1_prime) == m1\nassert cs.decrypt(c1) == m1\n```\n\n### Unsupported Operations\n\nFinally, if you try to perform an operation that algorithm does not support, then an exception will be thrown. For instance, Paillier is not homomorphic with respect to the multiplication or xor. To put it simply, you cannot multiply two ciphertexts. If you enforce this calculation, you will have an exception.\n\n```python\n# pailier is not multiplicatively homomorphic\nwith pytest.raises(ValueError, match=\"Paillier is not homomorphic with respect to the multiplication\"):\n  c1 * c2\n\n# pailier is not exclusively homomorphic\nwith pytest.raises(ValueError, match=\"Paillier is not homomorphic with respect to the exclusive or\"):\n  c1 ^ c2\n```\n\nHowever, if you tried to multiply ciphertexts with RSA, or xor ciphertexts with Goldwasser-Micali, these will be succeeded because those cryptosystems support those homomorphic operations.\n\n# Working with vectors\n\nYou can encrypt the output vectors of machine learning models with LightPHE. These encrypted tensors come with homomorphic operation support including homomorphic addition, element-wise multiplication and scalar multiplication.\n\n```python\n# build an additively homomorphic cryptosystem\ncs = LightPHE(algorithm_name=\"Paillier\")\n\n# define plain tensors\nt1 = [1.005, 2.05, 3.5, 4]\nt2 = [5, 6.2, 7.002, 8.02]\n\n# encrypt tensors\nc1 = cs.encrypt(t1)\nc2 = cs.encrypt(t2)\n\n# perform homomorphic addition\nc3 = c1 + c2\n\n# perform homomorphic element-wise multiplication\nc4 = c1 * c2\n\n# perform homomorphic scalar multiplication\nk = 5\nc5 = k * c1\n\n# decrypt the addition tensor\nt3 = cs.decrypt(c3)\n\n# decrypt the element-wise multiplied tensor\nt4 = cs.decrypt(c4)\n\n# decrypt the scalar multiplied tensor\nt5 = cs.decrypt(c5)\n\n# data validations\nthreshold = 0.5\nfor i in range(0, len(t1)):\n   assert abs((t1[i] + t2[i]) - t3[i]) < threshold\n   assert abs((t1[i] * t2[i]) - t4[i]) < threshold\n   assert abs((t1[i] * k) - t5[i]) < threshold\n```\n\nUnfortunately, vector multiplication (dot product) requires both homomorphic addition and homomorphic multiplication and this cannot be done with partially homomorphic encryption algorithms.\n\n# Contributing\n\nAll PRs are more than welcome! If you are planning to contribute a large patch, please create an issue first to get any upfront questions or design decisions out of the way first.\n\nYou should be able run `make test` and `make lint` commands successfully before committing. Once a PR is created, GitHub test workflow will be run automatically and unit test results will be available in [GitHub actions](https://github.com/serengil/LightPHE/actions/workflows/tests.yml) before approval. Besides, workflow will evaluate the code with pylint as well.\n\n# Support\n\nThere are many ways to support a project - starring\u2b50\ufe0f the GitHub repo is just one \ud83d\ude4f\n\nYou can also support this work on [Patreon](https://www.patreon.com/serengil?repo=lightphe), [GitHub Sponsors](https://github.com/sponsors/serengil) or [Buy Me a Coffee](https://buymeacoffee.com/serengil).\n\n<a href=\"https://www.patreon.com/serengil?repo=lightphe\">\n<img src=\"https://raw.githubusercontent.com/serengil/LightPHE/master/icons/patreon.png\" width=\"30%\" height=\"30%\">\n</a>\n\n<a href=\"https://buymeacoffee.com/serengil\">\n<img src=\"https://raw.githubusercontent.com/serengil/LightPHE/master/icons/bmc-button.png\" width=\"25%\" height=\"25%\">\n</a>\n\nAlso, your company's logo will be shown on README on GitHub if you become sponsor in gold, silver or bronze tiers.\n\n# Citation\n\nPlease cite LightPHE in your publications if it helps your research. Here is its BibTex entry:\n\n```BibTeX\n@misc{serengil2024lightphe,\n   title     = {LightPHE: Integrating Partially Homomorphic Encryption into Python with Extensive Cloud Environment Evaluations}, \n   author    = {Serengil, Sefik Ilkin and Ozpinar, Alper},\n   year      = {2024},\n   publisher = {arXiv},\n   url       = {https://arxiv.org/abs/2408.05219},\n   doi       = {10.48550/arXiv.2408.05219}\n}\n```\n\nAlso, if you use LightPHE in your projects, please add `lightphe` in the `requirements.txt`.\n\n# License\n\nLightPHE is licensed under the MIT License - see [`LICENSE`](https://github.com/serengil/LightPHE/blob/master/LICENSE) for more details.\n\n\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "A Lightweight Partially Homomorphic Encryption Library for Python",
    "version": "0.0.8",
    "project_urls": {
        "Homepage": "https://github.com/serengil/LightPHE"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "ce8f605c2ca40d454188a8685e0b351d045ba54451c6619ff4b6cde52ba86fc4",
                "md5": "f9c9617bc5695dd81210fa01dcdd19d3",
                "sha256": "ae878d8b1f18b99f2edf09e0c9f595307cdd22dc56b13c3c76b100e7997ed1e7"
            },
            "downloads": -1,
            "filename": "lightphe-0.0.8-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "f9c9617bc5695dd81210fa01dcdd19d3",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.5.5",
            "size": 53540,
            "upload_time": "2024-08-17T07:17:18",
            "upload_time_iso_8601": "2024-08-17T07:17:18.529087Z",
            "url": "https://files.pythonhosted.org/packages/ce/8f/605c2ca40d454188a8685e0b351d045ba54451c6619ff4b6cde52ba86fc4/lightphe-0.0.8-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "ab7979e0f06e95049e77d4915c71fec5168b9ecf8b09be7619fed9324869f532",
                "md5": "ddf097ae9770df46a3071f3dd3f22b56",
                "sha256": "8a8d1c521f1f4ea302c9e41166743f3643bfc15ad72dcbd568d649c4938af495"
            },
            "downloads": -1,
            "filename": "lightphe-0.0.8.tar.gz",
            "has_sig": false,
            "md5_digest": "ddf097ae9770df46a3071f3dd3f22b56",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.5.5",
            "size": 34043,
            "upload_time": "2024-08-17T07:17:20",
            "upload_time_iso_8601": "2024-08-17T07:17:20.197476Z",
            "url": "https://files.pythonhosted.org/packages/ab/79/79e0f06e95049e77d4915c71fec5168b9ecf8b09be7619fed9324869f532/lightphe-0.0.8.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-08-17 07:17:20",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "serengil",
    "github_project": "LightPHE",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "requirements": [],
    "lcname": "lightphe"
}
        
Elapsed time: 0.34853s