paillier.paillier module

Implementation of the Asymmetric Encryption Scheme known as Paillier.

class paillier.paillier.Paillier(public_key, secret_key, precision=0, share_secret_key=False, debug=False)[source]

Bases: AsymmetricEncryptionScheme[Tuple[PaillierPublicKey, PaillierSecretKey], Union[Integral, float, FixedPoint], int, int, PaillierCiphertext, PaillierPublicKey, PaillierSecretKey], RandomizedEncryptionScheme[Tuple[PaillierPublicKey, PaillierSecretKey], Union[Integral, float, FixedPoint], int, int, PaillierCiphertext, int]

Paillier Encryption Scheme. This is an AsymmetricEncryptionScheme, with a public and secret key. This is also a RandomizedEncryptionScheme, thus having internal randomness generation and allowing for the use of precomputed randomness.

class SerializedPaillier[source]

Bases: TypedDict

prec: int
pubkey: PaillierPublicKey
scheme_id: int
seckey: PaillierSecretKey
__eq__(other)[source]

Compare this Paillier scheme with another to determine (in)equality. Does not take the secret key into account as it might not be known and the public key combined with the precision should be sufficient to determine equality.

Parameters:

other (object) – Object to compare this Paillier scheme with.

Return type:

bool

Returns:

Boolean value representing (in)equality of both objects.

__init__(public_key, secret_key, precision=0, share_secret_key=False, debug=False)[source]

Construct a new Paillier encryption scheme, with the given keypair, randomness object, precision for fixed point encryption.

Parameters:
  • public_key (PaillierPublicKey) – Public key for this Paillier Scheme.

  • secret_key (PaillierSecretKey | None) – Secret Key for this Paillier Scheme.

  • precision (int) – Fixed point precision of this encoding, in decimal places.

  • share_secret_key (bool) – Boolean value stating whether or not the secret key should be included in serialization. This should only be set to True if one is really sure of it.

  • debug (bool) – flag to determine whether debug information should be displayed.

add(ciphertext_1, ciphertext_2)[source]

Secure addition.

If ciphertext_2 is another PaillierCiphertext \(c_2\), add the underlying plaintext value of ciphertext_1 \(c_1\) with the underlying plaintext value of ciphertext_2. If it is a Plaintext, we add the plaintext value \(m_2\) to ciphertext_1, by first encryption it and obtaining \(c_2 = Enc(m_2)\). We then compute the result as \(c' = c_1 \cdot c_2 \mod n^2\).

The resulting ciphertext is fresh only if at least one of the inputs was fresh. Both inputs are marked as non-fresh after the operation.

Parameters:
  • ciphertext_1 (PaillierCiphertext) – First PaillierCiphertext \(c_1\) of which the underlying plaintext is added.

  • ciphertext_2 (Union[PaillierCiphertext, Integral, float, FixedPoint]) – Either a second PaillierCiphertext \(c_2\) of which the underlying plaintext is added to the first. Or a plaintext \(m_2\) that is added to the underlying plaintext of the first.

Raises:

AttributeError – When ciphertext_2 does not have the same public key as ciphertext_1.

Return type:

PaillierCiphertext

Returns:

A PaillierCiphertext \(c'\) containing the encryption of the addition of both values.

decode(encoded_plaintext)[source]

Decode an EncodedPlaintext given the specified precision of this instantiation.

Parameters:

encoded_plaintext (EncodedPlaintext[int]) – Plaintext to be decoded.

Return type:

Union[Integral, float, FixedPoint]

Returns:

decoded Plaintext value

static deserialize(obj, *, origin=None, **_kwargs)[source]

Deserialization function for Paillier schemes, which will be passed to the communication module.

Parameters:
  • obj (SerializedPaillier) – serialized version of a Paillier scheme.

  • origin (HTTPClient | None) – HTTPClient representing where the message came from if applicable

  • **_kwargs (Any) – optional extra keyword arguments

Raises:
  • SerializationError – When communication library is not installed.

  • ValueError – When a scheme is sent through ID without any prior communication of the scheme

Return type:

Paillier

Returns:

Deserialized Paillier scheme from the given dict. Might not have a secret key when that was not included in the received serialization.

encode(plaintext)[source]

Encode a float or int with the given precision of this instantiation. Allows for positive and negative numbers.

Parameters:

plaintext (Union[Integral, float, FixedPoint]) – Plaintext to be encoded.

Raises:

ValueError – If the plaintext is outside the supported range of this Paillier instance.

Return type:

EncodedPlaintext[int]

Returns:

EncodedPlaintext object containing the encoded value.

static func_l(input_x, n)[source]

Paillier specific \(L(\cdot)\) function: \(L(x) = (x-1)/n\).

Parameters:
  • input_x (int) – input \(x\)

  • n (int) – input \(n\) (public key modulus)

Return type:

int

Returns:

value of \(L(x) = (x-1)/n\).

static generate_key_material(key_length)[source]

Method to generate key material (PaillierPublicKey and PaillierPrivateKey).

Parameters:

key_length (int) – Bit length of the public key \(n\).

Return type:

Tuple[PaillierPublicKey, PaillierSecretKey]

Returns:

Tuple with first the Public Key and then the Secret Key.

classmethod id_from_arguments(public_key, precision=0)[source]

Method that turns the arguments for the constructor into an identifier. This identifier is used to find constructor calls that would result in identical schemes.

Parameters:
  • public_key (PaillierPublicKey) – PaillierPublicKey of the Paillier instance.

  • precision (int) – Precision of the Paillier instance

Return type:

int

Returns:

Identifier of the Paillier instance

mul(ciphertext, scalar)[source]

Multiply the underlying plaintext value of ciph \(c\) with the given scalar \(s\).

We obtain the result by computing \(c' = c^s\).

The resulting ciphertext is fresh only if the input was fresh. The input is marked as non-fresh after the operation.

Parameters:
  • ciphertext (PaillierCiphertext) – PaillierCiphertext \(c\) of which the underlying plaintext is multiplied.

  • scalar (int) – A scalar \(s\) with which the plaintext underlying ciph should be multiplied.

Raises:

TypeError – When the scalar is not an integer.

Return type:

PaillierCiphertext

Returns:

PaillierCiphertext \(c'\) containing the encryption of the product of both values.

neg(ciphertext)[source]

Negate the underlying plaintext of this ciphertext.

If the original plaintext of this ciphertext was 5. this method returns the ciphertext that has -5 as underlying plaintext. Given a ciphertext \(c\) we compute the negated ciphertext \(c'\) such that \(c \cdot c' = 1 \mod n^2\).

The resulting ciphertext is fresh only if the input was fresh. The input is marked as non-fresh after the operation.

Parameters:

ciphertext (PaillierCiphertext) – PaillierCiphertext \(c\) of which the underlying plaintext should be negated.

Return type:

PaillierCiphertext

Returns:

PaillierCiphertext \(c'\) corresponding to the negated plaintext.

random_plaintext(lower_bound=None, upper_bound=None)[source]

Generate a uniformly random plaintext from the given interval.

Parameters:
  • lower_bound (Union[Integral, float, FixedPoint, None]) – Lower bound (inclusive), when no lower bound is given, the lowest value of the plaintext space is used.

  • upper_bound (Union[Integral, float, FixedPoint, None]) – Upper bound (exclusive), when no lower bound is given, the first value that is higher than the maximum value of the plaintext space is used.

Raises:
  • Warning – When the precision of lower_bound or upper_bound is larger than self.precision.

  • ValueError – When an interval larger than plaintext space or an empty interval is specified.

Return type:

FixedPoint

Returns:

A uniformly random element from specified range represented as a fixed point number If range unspecified, yields a uniformly random fixed point number from plaintext space.

sample_mask(lower_bound, upper_bound, security_level=None)[source]

Returns a random value to mask a plaintext message from a given message space of size \(|M|\) with statistical security, given security parameter \(\sigma\). The result will be a random mask from an interval with size \(|M| \cdot 2^{\sigma}\) that is centered around 0. To read the mathematics and reasoning behind this, please take a look at the README.

Parameters:
  • lower_bound (Union[Integral, float, FixedPoint]) – Integral lower bound for message space (inclusive).

  • upper_bound (Union[Integral, float, FixedPoint]) – Integral upper bound for message space (exclusive).

  • security_level (int | None) – Security level \(\sigma\) we require from additive masking, if None a mask with perfect security is returned. The security level should be a non-negative integer, denoting the number of bits of security.

Raises:
  • Warning – When the precision of lower_bound or upper_bound is larger than self.precision. A warning is also returned when the chosen security level equals 0 (since that provides NO security).

  • ValueError – When an interval larger than plaintext space or an empty interval is specified or when an invalid security level is given.

Return type:

FixedPoint

Returns:

A random fixed point number (with statistical security) to be used for masking.

serialize(*, destination=None, **_kwargs)[source]

Serialization function for Paillier schemes, which will be passed to the communication module. The sharing of the secret key depends on the attribute share_secret_key.

Parameters:
  • destination (HTTPClient | list[HTTPClient] | None) – HTTPClient representing where the message will go if applicable, can also be a list of clients in case of a broadcast message.

  • **_kwargs (Any) – optional extra keyword arguments

Raises:

SerializationError – When communication library is not installed.

Return type:

SerializedPaillier

Returns:

serialized version of this Paillier scheme.

serialize_with_secret_key()[source]

Serialization function for Paillier schemes, that does include the secret key.

Raises:

SerializationError – When communication library is not installed.

Return type:

SerializedPaillier

Returns:

serialized version of this Paillier scheme.

serialize_without_secret_key()[source]

Serialization function for Paillier schemes, that does not include the secret key.

Raises:

SerializationError – When communication library is not installed.

Return type:

SerializedPaillier

Returns:

serialized version of this Paillier scheme (without the secret key).

class paillier.paillier.PaillierCiphertext(raw_value, scheme, *, fresh=False)[source]

Bases: RandomizableCiphertext[Tuple[PaillierPublicKey, PaillierSecretKey], Union[Integral, float, FixedPoint], int, int, int]

Ciphertext for the Paillier asymmetric encryption scheme. This ciphertext is rerandomizable and supports homomorphic operations.

class SerializedPaillierCiphertext[source]

Bases: TypedDict

scheme: Paillier
value: int
__eq__(other)[source]

Compare this PaillierCiphertext with another to determine (in)equality.

Parameters:

other (object) – Object to compare this PaillierCiphertext with.

Raises:

TypeError – When other object is not a PaillierCiphertext.

Return type:

bool

Returns:

Boolean value representing (in)equality of both objects.

__init__(raw_value, scheme, *, fresh=False)[source]

Construct a RandomizableCiphertext, with the given value for the given EncryptionScheme.

Parameters:
  • raw_value (int) – PaillierCiphertext value \(c \in \mathbb{Z}_{n^2}\).

  • scheme (Paillier) – Paillier scheme that is used to encrypt this ciphertext.

  • fresh (bool) – Indicates whether fresh randomness is already applied to the raw_value.

Raises:

TypeError – When the given scheme is not a Paillier scheme.

apply_randomness(randomization_value)[source]

Rerandomize this ciphertext using the given random value.

Parameters:

randomization_value (int) – Random value used for rerandomization.

Return type:

None

copy()[source]

Create a copy of this Ciphertext, with the same value and scheme. The copy is not randomized and is considered not fresh.

Return type:

PaillierCiphertext

Returns:

Copied PaillierCiphertext.

static deserialize(obj, **_kwargs)[source]

Deserialization function for Paillier ciphertexts, which will be passed to the communication module.

Parameters:
Raises:

SerializationError – When communication library is not installed.

Return type:

PaillierCiphertext

Returns:

Deserialized PaillierCiphertext from the given dict.

scheme: Paillier
serialize(**_kwargs)[source]

Serialization function for Paillier ciphertexts, which will be passed to the communication module.

If the ciphertext is not fresh, it is randomized before serialization. After serialization, it is always marked as not fresh for security reasons.

Parameters:

**_kwargs (Any) – optional extra keyword arguments

Raises:

SerializationError – When communication library is not installed.

Return type:

SerializedPaillierCiphertext

Returns:

serialized version of this PaillierCiphertext.

class paillier.paillier.PaillierPublicKey(n, g)[source]

Bases: PublicKey

PublicKey for the Paillier encryption scheme.

class SerializedPaillierPublicKey[source]

Bases: TypedDict

g: int
n: int
__eq__(other)[source]

Compare this PaillierPublicKey with another to determine (in)equality.

Parameters:

other (object) – Object to compare this PaillierPublicKey with.

Raises:

TypeError – When other object is not a PaillierPublicKey.

Return type:

bool

Returns:

Boolean value representing (in)equality of both objects.

__hash__()[source]

Compute a hash from this PaillierPublicKey instance.

Return type:

int

Returns:

Hash value.

__init__(n, g)[source]

Constructs a new Paillier public key \((n, g)\), should have \(n=pq\), with \(p, q\) prime, and \(g \in \mathbb{Z}^*_{n^2}\).

Parameters:
  • n (int) – Modulus \(n\) of the plaintext space.

  • g (int) – Plaintext base \(g\) for encryption.

Also contains: n_squared: Modulus of the ciphertext space \(n^2\).

__str__()[source]
Return type:

str

Returns:

Reprentation of public key prepended by (n, g)=

static deserialize(obj, **_kwargs)[source]

Deserialization function for public keys, which will be passed to the communication module.

Parameters:
  • obj (SerializedPaillierPublicKey) – serialized version of a PaillierPublicKey.

  • **_kwargs (Any) – optional extra keyword arguments

Raises:

SerializationError – When communication library is not installed.

Return type:

PaillierPublicKey

Returns:

Deserialized PaillierPublicKey from the given dict.

serialize(**_kwargs)[source]

Serialization function for public keys, which will be passed to the communication module.

Parameters:

**_kwargs (Any) – optional extra keyword arguments

Raises:

SerializationError – When communication library is not installed.

Return type:

SerializedPaillierPublicKey

Returns:

serialized version of this PaillierPublicKey.

class paillier.paillier.PaillierSecretKey(lambda_value, mu, n)[source]

Bases: SecretKey

SecretKey for the Paillier encryption scheme.

class SerializedPaillierSecretKey[source]

Bases: TypedDict

lambda_: int
mu: int
n: int
__eq__(other)[source]

Compare this PaillierSecretKey with another to determine (in)equality.

Parameters:

other (object) – Object to compare this PaillierSecretKey with.

Raises:

TypeError – When other object is not a PaillierSecretKey.

Return type:

bool

Returns:

Boolean value representing (in)equality of both objects.

__hash__()[source]

Compute a hash from this PaillierSecretKey instance.

Return type:

int

Returns:

Hash value.

__init__(lambda_value, mu, n)[source]

Constructs a new Paillier secret key \((\lambda, \mu)\), also contains \(n\). Should have \(n=pq\), with \(p, q\) prime, \(\lambda = \text{lcm}(p-1, q-1)\), and \(\mu = (L(g^\lambda \mod n^2))^{-1} \mod n\), where \(L(\cdot)\) is defined as \(L(x) = (x-1)/n\).

Parameters:
  • lambda_value (int) – Decryption exponent \(\lambda\) of the ciphertext.

  • mu (int) – Decryption divisor \(\mu\) for the ciphertext.

  • n (int) – Modulus \(n\) of the plaintext space.

__str__()[source]
Return type:

str

Returns:

Reprentation of secret key prepended by (lambda, mu)=

static deserialize(obj, **_kwargs)[source]

Deserialization function for public keys, which will be passed to the communication module

Parameters:
  • obj (SerializedPaillierSecretKey) – serialized version of a PaillierSecretKey.

  • **_kwargs (Any) – optional extra keyword arguments

Raises:

SerializationError – When communication library is not installed.

Return type:

PaillierSecretKey

Returns:

Deserialized PaillierSecretKey from the given dict.

serialize(**_kwargs)[source]

Serialization function for secret keys, which will be passed to the communication module.

Parameters:

**_kwargs (Any) – optional extra keyword arguments

Raises:

SerializationError – When communication library is not installed.

Return type:

SerializedPaillierSecretKey

Returns:

serialized version of this PaillierSecretKey.