Skip to content

Instantly share code, notes, and snippets.

@nginnever
Last active May 17, 2024 01:34
Show Gist options
  • Save nginnever/dcb78fa5a8a47c0df3fed9a1d7bf745d to your computer and use it in GitHub Desktop.
Save nginnever/dcb78fa5a8a47c0df3fed9a1d7bf745d to your computer and use it in GitHub Desktop.
use std::{error::Error};
use fhe::bfv::{self, Encoding, Plaintext, PublicKey, SecretKey};
use fhe_traits::{FheDecoder, FheEncoder, FheEncrypter, Serialize, FheDecrypter};
use rand::{thread_rng};
fn main() -> Result<(), Box<dyn Error>> {
let degree = 4096;
let plaintext_modulus: u64 = 4096;
let moduli = vec![0xffffee001, 0xffffc4001, 0x1ffffe0001];
let params = bfv::BfvParametersBuilder::new()
.set_degree(degree)
.set_plaintext_modulus(plaintext_modulus)
.set_moduli(&moduli)
.build_arc()?;
let mut rng = thread_rng();
let sk = SecretKey::random(&params, &mut rng);
let pk = PublicKey::new(&sk, &mut rng);
let input1: Vec<u64> = vec![2];
let input2: Vec<u64> = vec![4];
let input3: Vec<u64> = vec![10];
let pt1 = Plaintext::try_encode(&input1, Encoding::poly(), &params)?;
let pt2 = Plaintext::try_encode(&input2, Encoding::poly(), &params)?;
let pt3 = Plaintext::try_encode(&input3, Encoding::poly(), &params)?;
let ct1 = pk.try_encrypt(&pt1, &mut rng)?;
let _ct1_bytes = ct1.to_bytes();
let ct2 = pk.try_encrypt(&pt2, &mut rng)?;
let _ct2_bytes = ct2.to_bytes();
let ct3 = pk.try_encrypt(&pt3, &mut rng)?;
let _ct3_bytes = ct3.to_bytes();
let mut prod = &ct1 * &ct2;
prod = &prod * &ct3;
let decrypted = sk.try_decrypt(&prod)?;
let tally_vec = Vec::<u64>::try_decode(&decrypted, Encoding::poly())?;
let tally_result = tally_vec[0];
println!("{:?}", tally_result);
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment