lightphe


Namelightphe JSON
Version 0.0.11 PyPI version JSON
download
home_pagehttps://github.com/serengil/LightPHE
SummaryA Lightweight Partially Homomorphic Encryption Library for Python
upload_time2025-01-20 17:33:42
maintainerNone
docs_urlNone
authorSefik Ilkin Serengil
requires_python>=3.5.5
licenseNone
keywords
VCS
bugtrack_url
requirements sympy pytest
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)
[![arXiv](https://img.shields.io/badge/arXiv-2408.05219-b31b1b.svg?logo=arXiv)](https://arxiv.org/abs/2408.05219)
<!-- [![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/) ([`Weierstrass`](https://sefiks.com/2016/03/13/the-math-behind-elliptic-curve-cryptography/), [`Koblitz`](sefiks.com/2016/03/13/the-math-behind-elliptic-curves-over-binary-field/) and [`Edwards`](https://sefiks.com/2018/12/19/a-gentle-introduction-to-edwards-curves/) forms), [`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"
]

phe = 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 = phe.encrypt(m)

# proof of work
assert phe.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 code snippet illustrates how to generate a random public-private key pair using the Paillier and encrypt a plaintext pair. The resulting ciphertext pair, c1 and c2, along with the public key, is then sent from the on-premises environment to the cloud.

```python
def on_premise() -> Tuple[int, int, dict]:
    """
    Executes on-premise operations: initializes a cryptosystem by generating 
    a random public-private key pair, then encrypts two plaintext values.

    Returns:
       result (tuple): A tuple containing:
       - c1 (int): The first ciphertext
       - c2 (int): The second ciphertext
       - public_key (dict): The public key for the cryptosystem
    """
    # generate a random private-public key pair
    phe = LightPHE(algorithm_name = "Paillier")

    # define plaintexts
    m1 = 10000 # base salary in usd
    m2 = 500 # wage increase in usd

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

    return (c1, c2, phe.cs.public_key)
```

### Homomorphic Operations on Cloud

This code snippet demonstrates how to perform homomorphic addition on the cloud side without using the private key. However, the cloud is unable to decrypt c3 itself, even though it is the one that calculated it.

```python
def cloud(c1: int, c2: int, public_key: dict) -> int:
    """
    Performs cloud-side operations: reconstructs a cryptosystem using the 
    provided public key and executes a homomorphic addition on two ciphertexts.

    Args:
       c1 (int): The first ciphertext
       c2 (int): The second ciphertext
       public_key (dict): The public key of an existing cryptosystem
    Retunrs:
       c3 (int): The resulting ciphertext after homomorphic addition
    """
    # restore cryptosystem with just the public key
    phe = LightPHE(algorithm_name = "Paillier", keys = public_key)

    # cast c1 and c2 to ciphertext objects
    c1 = phe.create_ciphertext_obj(c1)
    c2 = phe.create_ciphertext_obj(c2)

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

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

    # perform homomorphic addition
    c3 = c1 + c2

    # confirm that cloud cannot decrypt c3
    with pytest.raises(ValueError, match="You must have private key"):
      phe.decrypt(c3)
    
    return c3.value
```

### On-Prem Decryption And Proof of Work

This code snippet demonstrates the proof of work. Even though c3 was calculated in the cloud by adding c1 and c2, on-premises can validate that its decryption must be equal to the addition of plaintexts m1 and m2.

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

In this homomorphic pipeline, the cloud's computational power was utilized to calculate c3, but it can only be decrypted by the on-premises side. Additionally, while we performed the encryption on the on-premises side, this is not strictly necessary; only the public key is required for encryption. Therefore, encryption can also be performed on the non-premises side. This approach is particularly convenient when collecting data from multiple edge devices and storing all of it in the cloud simultaneously.

### Scalar Multiplication

Besides, Paillier is supporting multiplying ciphertexts by a known plain constant. This code snippet demonstrates how to perform scalar multiplication on encrypted data using Paillier homomorphic encryption with the LightPHE library.

```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 phe.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 = phe.regenerate_ciphertext(c1)
assert c1_prime.value != c1.value
assert phe.decrypt(c1_prime) == m1
assert phe.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.

### Elliptic Curve Cryptography

ECC is a powerful public-key cryptosystem based on the algebraic structure of elliptic curves over finite fields. The library supports 3 elliptic curve forms (weierstrass, edwards and koblitz) and 100+ standard elliptic curve configurations.

Building an elliptic curve with LightPHE is very straightforward. Once the curve is initialized, you can perform operations such as point addition and scalar multiplication.

```python
from lightphe import ECC

forms = ["weierstrass", "edwards", "koblitz"]

# construct an elliptic curve
ed = ECC(form_name="edwards")

# Base Point
G = ed.G

_2G = G + G
_3G = _2G + G
_5G = _3G + _2G

_20G = 4 * G
_19G = _20G - G
```

In LightPHE, the [Elliptic Curve ElGamal](https://sefiks.com/2018/08/21/elliptic-curve-elgamal-encryption/) scheme is implemented, offering a secure and efficient homomorphic encryption option.

```python
forms = ["weierstass", "edwards", "koblitz"]

phe = LightPHE(
    algorithm_name="EllipticCurve-ElGamal",
    form=forms[1],
)
```

One of the crucial factors that define the security level of an elliptic curve cryptosystem is the order of the curve. The order of a curve is the number of points on the curve, and it directly influences the strength of the encryption. A higher order typically corresponds to a stronger cryptosystem, making it more resistant to cryptographic attacks.

Each curve in LightPHE has a specific order, which is carefully chosen to balance performance and security. By selecting an elliptic curve with a larger order, you increase the security of your cryptographic system, but this may come with a trade-off in computational efficiency. Therefore, choosing the appropriate curve order is a crucial decision based on your application’s security and performance requirements.

See [`curves`](https://github.com/serengil/LightPHE/tree/master/lightphe/elliptic_curve_forms) page for a list of all supported forms, curves and their details.

# 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/0d/e8/6f4dd9c0ed6777a54a586f6dbacd3a435b7599af56570164232688975944/lightphe-0.0.11.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[![arXiv](https://img.shields.io/badge/arXiv-2408.05219-b31b1b.svg?logo=arXiv)](https://arxiv.org/abs/2408.05219)\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/) ([`Weierstrass`](https://sefiks.com/2016/03/13/the-math-behind-elliptic-curve-cryptography/), [`Koblitz`](sefiks.com/2016/03/13/the-math-behind-elliptic-curves-over-binary-field/) and [`Edwards`](https://sefiks.com/2018/12/19/a-gentle-introduction-to-edwards-curves/) forms), [`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\nphe = 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 = phe.encrypt(m)\n\n# proof of work\nassert phe.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 code snippet illustrates how to generate a random public-private key pair using the Paillier and encrypt a plaintext pair. The resulting ciphertext pair, c1 and c2, along with the public key, is then sent from the on-premises environment to the cloud.\n\n```python\ndef on_premise() -> Tuple[int, int, dict]:\n    \"\"\"\n    Executes on-premise operations: initializes a cryptosystem by generating \n    a random public-private key pair, then encrypts two plaintext values.\n\n    Returns:\n       result (tuple): A tuple containing:\n       - c1 (int): The first ciphertext\n       - c2 (int): The second ciphertext\n       - public_key (dict): The public key for the cryptosystem\n    \"\"\"\n    # generate a random private-public key pair\n    phe = LightPHE(algorithm_name = \"Paillier\")\n\n    # define plaintexts\n    m1 = 10000 # base salary in usd\n    m2 = 500 # wage increase in usd\n\n    # calculate ciphertexts\n    c1 = phe.encrypt(m1).value\n    c2 = phe.encrypt(m2).value\n\n    return (c1, c2, phe.cs.public_key)\n```\n\n### Homomorphic Operations on Cloud\n\nThis code snippet demonstrates how to perform homomorphic addition on the cloud side without using the private key. However, the cloud is unable to decrypt c3 itself, even though it is the one that calculated it.\n\n```python\ndef cloud(c1: int, c2: int, public_key: dict) -> int:\n    \"\"\"\n    Performs cloud-side operations: reconstructs a cryptosystem using the \n    provided public key and executes a homomorphic addition on two ciphertexts.\n\n    Args:\n       c1 (int): The first ciphertext\n       c2 (int): The second ciphertext\n       public_key (dict): The public key of an existing cryptosystem\n    Retunrs:\n       c3 (int): The resulting ciphertext after homomorphic addition\n    \"\"\"\n    # restore cryptosystem with just the public key\n    phe = LightPHE(algorithm_name = \"Paillier\", keys = public_key)\n\n    # cast c1 and c2 to ciphertext objects\n    c1 = phe.create_ciphertext_obj(c1)\n    c2 = phe.create_ciphertext_obj(c2)\n\n    # confirm that cloud cannot decrypt c1\n    with pytest.raises(ValueError, match=\"You must have private key\"):\n      phe.decrypt(c1)\n\n    # confirm that cloud cannot decrypt c2\n    with pytest.raises(ValueError, match=\"You must have private key\"):\n      phe.decrypt(c2)\n\n    # perform homomorphic addition\n    c3 = c1 + c2\n\n    # confirm that cloud cannot decrypt c3\n    with pytest.raises(ValueError, match=\"You must have private key\"):\n      phe.decrypt(c3)\n    \n    return c3.value\n```\n\n### On-Prem Decryption And Proof of Work\n\nThis code snippet demonstrates the proof of work. Even though c3 was calculated in the cloud by adding c1 and c2, on-premises can validate that its decryption must be equal to the addition of plaintexts m1 and m2.\n\n```python\n# proof of work - private key required\nassert phe.decrypt(c3) == m1 + m2\n```\n\nIn this homomorphic pipeline, the cloud's computational power was utilized to calculate c3, but it can only be decrypted by the on-premises side. Additionally, while we performed the encryption on the on-premises side, this is not strictly necessary; only the public key is required for encryption. Therefore, encryption can also be performed on the non-premises side. This approach is particularly convenient when collecting data from multiple edge devices and storing all of it in the cloud simultaneously.\n\n### Scalar Multiplication\n\nBesides, Paillier is supporting multiplying ciphertexts by a known plain constant. This code snippet demonstrates how to perform scalar multiplication on encrypted data using Paillier homomorphic encryption with the LightPHE library.\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 phe.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 = phe.regenerate_ciphertext(c1)\nassert c1_prime.value != c1.value\nassert phe.decrypt(c1_prime) == m1\nassert phe.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### Elliptic Curve Cryptography\n\nECC is a powerful public-key cryptosystem based on the algebraic structure of elliptic curves over finite fields. The library supports 3 elliptic curve forms (weierstrass, edwards and koblitz) and 100+ standard elliptic curve configurations.\n\nBuilding an elliptic curve with LightPHE is very straightforward. Once the curve is initialized, you can perform operations such as point addition and scalar multiplication.\n\n```python\nfrom lightphe import ECC\n\nforms = [\"weierstrass\", \"edwards\", \"koblitz\"]\n\n# construct an elliptic curve\ned = ECC(form_name=\"edwards\")\n\n# Base Point\nG = ed.G\n\n_2G = G + G\n_3G = _2G + G\n_5G = _3G + _2G\n\n_20G = 4 * G\n_19G = _20G - G\n```\n\nIn LightPHE, the [Elliptic Curve ElGamal](https://sefiks.com/2018/08/21/elliptic-curve-elgamal-encryption/) scheme is implemented, offering a secure and efficient homomorphic encryption option.\n\n```python\nforms = [\"weierstass\", \"edwards\", \"koblitz\"]\n\nphe = LightPHE(\n    algorithm_name=\"EllipticCurve-ElGamal\",\n    form=forms[1],\n)\n```\n\nOne of the crucial factors that define the security level of an elliptic curve cryptosystem is the order of the curve. The order of a curve is the number of points on the curve, and it directly influences the strength of the encryption. A higher order typically corresponds to a stronger cryptosystem, making it more resistant to cryptographic attacks.\n\nEach curve in LightPHE has a specific order, which is carefully chosen to balance performance and security. By selecting an elliptic curve with a larger order, you increase the security of your cryptographic system, but this may come with a trade-off in computational efficiency. Therefore, choosing the appropriate curve order is a crucial decision based on your application\u2019s security and performance requirements.\n\nSee [`curves`](https://github.com/serengil/LightPHE/tree/master/lightphe/elliptic_curve_forms) page for a list of all supported forms, curves and their details.\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.11",
    "project_urls": {
        "Homepage": "https://github.com/serengil/LightPHE"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "047df63e52ea3dee55ef5d1e54cdc3282e19b80d81f4432916cb4187d5efbf4c",
                "md5": "1f6dafa0581585cfa73467fc49ee8505",
                "sha256": "c7ac673e95729ff0256b02f9700328034fd745ca9350972638de95b44b86adea"
            },
            "downloads": -1,
            "filename": "lightphe-0.0.11-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "1f6dafa0581585cfa73467fc49ee8505",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.5.5",
            "size": 61905,
            "upload_time": "2025-01-20T17:33:41",
            "upload_time_iso_8601": "2025-01-20T17:33:41.523724Z",
            "url": "https://files.pythonhosted.org/packages/04/7d/f63e52ea3dee55ef5d1e54cdc3282e19b80d81f4432916cb4187d5efbf4c/lightphe-0.0.11-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "0de86f4dd9c0ed6777a54a586f6dbacd3a435b7599af56570164232688975944",
                "md5": "e5f7e2d86d3fe82b5705efe305b81ec2",
                "sha256": "09caefd7e4ad1af87773f99ef99957cafff08307a9570bea194fc42078acfff3"
            },
            "downloads": -1,
            "filename": "lightphe-0.0.11.tar.gz",
            "has_sig": false,
            "md5_digest": "e5f7e2d86d3fe82b5705efe305b81ec2",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.5.5",
            "size": 40249,
            "upload_time": "2025-01-20T17:33:42",
            "upload_time_iso_8601": "2025-01-20T17:33:42.854979Z",
            "url": "https://files.pythonhosted.org/packages/0d/e8/6f4dd9c0ed6777a54a586f6dbacd3a435b7599af56570164232688975944/lightphe-0.0.11.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-01-20 17:33:42",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "serengil",
    "github_project": "LightPHE",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "requirements": [
        {
            "name": "sympy",
            "specs": [
                [
                    "==",
                    "1.12"
                ]
            ]
        },
        {
            "name": "pytest",
            "specs": [
                [
                    "==",
                    "7.1.2"
                ]
            ]
        }
    ],
    "lcname": "lightphe"
}
        
Elapsed time: 0.72238s