main.rs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. use tfhe::shortint::{gen_keys, Parameters};
  19. fn main() {
  20. // Generate a set of client/server keys, using the default parameters.
  21. // The client generates both keys. The server key is meant to be published
  22. // so that homomorphic circuits can be computed.
  23. let (client_key, server_key) = gen_keys(Parameters::default());
  24. let msg1 = 3;
  25. let msg2 = 2;
  26. // Encrypt two messages using the (private) client key:
  27. let ct_1 = client_key.encrypt(msg1);
  28. let ct_2 = client_key.encrypt(msg2);
  29. // Homomorphically compute an addition
  30. let ct_add = server_key.unchecked_add(&ct_1, &ct_2);
  31. // Define the Hamming weight function
  32. // f: x -> sum of the bits of x
  33. let f = |x: u64| x.count_ones() as u64;
  34. // Generate the accumulator for the function
  35. let acc = server_key.generate_accumulator(f);
  36. // Compute the function over the ciphertext using the PBS
  37. let ct_res = server_key.keyswitch_programmable_bootstrap(&ct_add, &acc);
  38. // Decrypt the ciphertext using the (private) client key
  39. let output = client_key.decrypt(&ct_res);
  40. assert_eq!(output, f(msg1 + msg2));
  41. println!("{:#b}", msg1 + msg2);
  42. }