Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ElGamal cipher #161

Merged
merged 10 commits into from
May 7, 2024
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added

- Add `ElGamal` encryption module [#162]

### Changed

- Restructure `Encryption` module.

## [0.27.0] - 2024-04-24

### Added
Expand Down Expand Up @@ -284,6 +292,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Canonical implementation shielded by feature.

<!-- ISSUES -->
[#162]: https://github.com/dusk-network/phoenix-core/issues/162
[#156]: https://github.com/dusk-network/phoenix-core/issues/156
[#155]: https://github.com/dusk-network/phoenix-core/issues/155
[#152]: https://github.com/dusk-network/phoenix-core/issues/152
Expand Down
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ exclude = [".github/workflows/dusk-ci.yml", ".gitignore"]
[dependencies]
rand_core = { version = "0.6", default-features = false }
dusk-bytes = "0.1"
dusk-plonk = { version = "0.19", default-features = false, optional = true }
xevisalle marked this conversation as resolved.
Show resolved Hide resolved
dusk-bls12_381 = { version = "0.13", default-features = false }
bls12_381-bls = { version = "0.3", default-features = false }
dusk-jubjub = { version = "0.14", default-features = false, features = ["zeroize"] }
Expand Down Expand Up @@ -40,3 +41,6 @@ rkyv-impl = [
"rkyv",
"bytecheck"
]
zk = [
"dusk-plonk",
]
File renamed without changes.
60 changes: 60 additions & 0 deletions src/encryption/elgamal.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
// Copyright (c) DUSK NETWORK. All rights reserved.

//! This module implements the ElGamal asymmetric cipher. It allows to
//! encrypt, decrypt, and prove encryption in Zero-Knowledge of JubJub points.
//!
//! Reference: https://link.springer.com/chapter/10.1007/3-540-39568-7_2

use dusk_jubjub::{JubJubExtended, JubJubScalar, GENERATOR};

#[cfg(feature = "zk")]
use dusk_plonk::prelude::*;

/// Encrypts a JubJubExtended plaintext given a public key and a fresh random
/// number 'r', returning a ciphertext (JubJubExtended, JubJubExtended)
pub fn encrypt(
public_key: &JubJubExtended,
plaintext: &JubJubExtended,
r: &JubJubScalar,
) -> (JubJubExtended, JubJubExtended) {
let ciphertext_1 = GENERATOR * r;
let ciphertext_2 = plaintext + public_key * r;

(ciphertext_1, ciphertext_2)
}

/// Decrypts a ciphertext given a secret key,
/// returning a JubJubExtended plaintext
pub fn decrypt(
secret_key: &JubJubScalar,
ciphertext_1: &JubJubExtended,
ciphertext_2: &JubJubExtended,
) -> JubJubExtended {
ciphertext_2 - ciphertext_1 * secret_key
xevisalle marked this conversation as resolved.
Show resolved Hide resolved
}

/// Encrypt in-circuit a plaintext, returning
/// a ciphertext (WitnessPoint, WitnessPoint)
#[cfg(feature = "zk")]
pub fn zk_encrypt(
composer: &mut Composer,
public_key: &JubJubAffine,
plaintext: &JubJubAffine,
r: &JubJubScalar,
) -> Result<(WitnessPoint, WitnessPoint), Error> {
// IMPORT INPUTS
let public_key = composer.append_point(*public_key);
let plaintext = composer.append_point(*plaintext);
let r = composer.append_witness(*r);

// ENCRYPT
let R = composer.component_mul_point(r, public_key);
let ciphertext_1 = composer.component_mul_generator(r, GENERATOR)?;
xevisalle marked this conversation as resolved.
Show resolved Hide resolved
let ciphertext_2 = composer.component_add_point(plaintext, R);

Ok((ciphertext_1, ciphertext_2))
}
11 changes: 11 additions & 0 deletions src/encryption/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
// Copyright (c) DUSK NETWORK. All rights reserved.

/// AES symmetric cipher
pub mod aes;

/// ElGamal asymmetric cipher
pub mod elgamal;
8 changes: 5 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,13 @@ pub mod note;
/// Phoenix Core Keys & Addresses
mod keys;

/// Encryption and decryption methods
/// Encryption algorithms
mod encryption;

/// Encryption and decryption methods
pub use encryption::{decrypt, encrypt, ENCRYPTION_EXTRA_SIZE};
/// AES symmetric cipher
pub use encryption::aes;
/// ElGamal asymmetric cipher
pub use encryption::elgamal;
/// Hash function
pub use keys::hash;
/// Public (Spend) Key
Expand Down
8 changes: 4 additions & 4 deletions src/note.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use dusk_jubjub::{
GENERATOR_NUMS_EXTENDED,
};

use crate::encryption::{decrypt, encrypt, ENCRYPTION_EXTRA_SIZE};
use crate::aes;

use dusk_poseidon::sponge::hash;
use ff::Field;
Expand All @@ -31,7 +31,7 @@ pub(crate) const PLAINTEXT_SIZE: usize = 40;

/// Size of the Phoenix notes encryption
pub(crate) const ENCRYPTION_SIZE: usize =
PLAINTEXT_SIZE + ENCRYPTION_EXTRA_SIZE;
PLAINTEXT_SIZE + aes::ENCRYPTION_EXTRA_SIZE;

/// The types of a Note
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
Expand Down Expand Up @@ -123,7 +123,7 @@ impl Note {
let mut plaintext = value.to_bytes().to_vec();
plaintext.append(&mut blinding_factor.to_bytes().to_vec());

encrypt(&shared_secret, &plaintext, rng)
aes::encrypt(&shared_secret, &plaintext, rng)
.expect("Encrypted correctly.")
}
};
Expand Down Expand Up @@ -200,7 +200,7 @@ impl Note {
let shared_secret = dhke(vk.a(), R);

let dec_plaintext: [u8; PLAINTEXT_SIZE] =
decrypt(&shared_secret, &self.encryption)?;
aes::decrypt(&shared_secret, &self.encryption)?;

let value = u64::from_slice(&dec_plaintext[..u64::SIZE])?;

Expand Down
116 changes: 109 additions & 7 deletions tests/encryption.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,127 @@
//
// Copyright (c) DUSK NETWORK. All rights reserved.

use dusk_jubjub::{JubJubAffine, JubJubScalar, GENERATOR};
use dusk_jubjub::{JubJubAffine, JubJubScalar, GENERATOR, GENERATOR_EXTENDED};
use ff::Field;
use rand_core::OsRng;

use phoenix_core::{decrypt, encrypt, ENCRYPTION_EXTRA_SIZE};
use phoenix_core::{aes, elgamal, PublicKey, SecretKey};

#[cfg(feature = "zk")]
xevisalle marked this conversation as resolved.
Show resolved Hide resolved
use dusk_plonk::prelude::*;
#[cfg(feature = "zk")]
static LABEL: &[u8; 12] = b"dusk-network";
#[cfg(feature = "zk")]
const CAPACITY: usize = 12; // capacity required for the setup

#[cfg(feature = "zk")]
#[derive(Default, Debug)]
pub struct ElGamalCircuit {
public_key: JubJubAffine,
plaintext: JubJubAffine,
r: JubJubScalar,
ciphertext_1: JubJubAffine,
ciphertext_2: JubJubAffine,
}

#[cfg(feature = "zk")]
impl ElGamalCircuit {
pub fn new(
public_key: &JubJubExtended,
plaintext: &JubJubExtended,
r: &JubJubScalar,
ciphertext_1: &JubJubExtended,
ciphertext_2: &JubJubExtended,
) -> Self {
Self {
public_key: JubJubAffine::from(public_key),
plaintext: JubJubAffine::from(plaintext),
r: *r,
ciphertext_1: JubJubAffine::from(ciphertext_1),
ciphertext_2: JubJubAffine::from(ciphertext_2),
}
}
}

#[cfg(feature = "zk")]
impl Circuit for ElGamalCircuit {
fn circuit(&self, composer: &mut Composer) -> Result<(), Error> {
let (ciphertext_1, ciphertext_2) = elgamal::zk_encrypt(
composer,
&self.public_key,
&self.plaintext,
&self.r,
)?;

// ASSERT RESULT MAKING THE CIPHERTEXT PUBLIC
composer.assert_equal_public_point(ciphertext_1, self.ciphertext_1);
composer.assert_equal_public_point(ciphertext_2, self.ciphertext_2);

Ok(())
}
}

#[test]
fn test_encrypt_and_decrypt() {
fn test_aes_encrypt_and_decrypt() {
const PLAINTEXT_SIZE: usize = 20;
const ENCRYPTION_SIZE: usize = PLAINTEXT_SIZE + ENCRYPTION_EXTRA_SIZE;
const ENCRYPTION_SIZE: usize = PLAINTEXT_SIZE + aes::ENCRYPTION_EXTRA_SIZE;

let shared_secret_key =
JubJubAffine::from(GENERATOR * JubJubScalar::from(1234u64));

let plaintext = b"00112233445566778899";
let encryption: [u8; ENCRYPTION_SIZE] =
encrypt(&shared_secret_key, plaintext, &mut OsRng)
aes::encrypt(&shared_secret_key, plaintext, &mut OsRng)
.expect("Encrypted correctly.");
let dec_plaintext =
decrypt(&shared_secret_key, &encryption).expect("Decrypted correctly.");
let dec_plaintext = aes::decrypt(&shared_secret_key, &encryption)
.expect("Decrypted correctly.");

assert_eq!(&dec_plaintext, plaintext);
}

#[test]
fn test_elgamal_encrypt_and_decrypt() {
let sk = SecretKey::random(&mut OsRng);
let pk = PublicKey::from(&sk);

let message = GENERATOR_EXTENDED * JubJubScalar::from(1234u64);

// Encrypt using a fresh random value 'r'
let r = JubJubScalar::random(&mut OsRng);
let (c1, c2) = elgamal::encrypt(pk.A(), &message, &r);

// Assert decryption
let dec_message = elgamal::decrypt(sk.a(), &c1, &c2);
assert_eq!(message, dec_message);

// Assert decryption using an incorrect key
let dec_message_wrong = elgamal::decrypt(sk.b(), &c1, &c2);
assert_ne!(message, dec_message_wrong);
}

#[cfg(feature = "zk")]
#[test]
fn test_elgamal_zk_encrypt() {
let sk = SecretKey::random(&mut OsRng);
let pk = PublicKey::from(&sk);

let message = GENERATOR_EXTENDED * JubJubScalar::from(1234u64);
let r = JubJubScalar::random(&mut OsRng);
let (c1, c2) = elgamal::encrypt(pk.A(), &message, &r);

let pp = PublicParameters::setup(1 << CAPACITY, &mut OsRng).unwrap();

let (prover, verifier) = Compiler::compile::<ElGamalCircuit>(&pp, LABEL)
.expect("failed to compile circuit");

let (proof, public_inputs) = prover
.prove(
&mut OsRng,
&ElGamalCircuit::new(&pk.A(), &message, &r, &c1, &c2),
)
.expect("failed to prove");

verifier
.verify(&proof, &public_inputs)
.expect("failed to verify proof");
}