encrypt.zk 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. # Verifiable encryption inside ZK
  2. # Normally this algo will be hardened due to malleability attacks
  3. # on the ciphertext, but the ZK proof ensures that the ciphertext
  4. # cannot be modified.
  5. #
  6. # This is basically the el gamal scheme in ZK
  7. constant "Encrypt" {}
  8. witness "Encrypt" {
  9. # We are encrypting values to this public key
  10. EcNiPoint pubkey,
  11. # Emphemeral secret value
  12. Base ephem_secret,
  13. # Values we are encrypting
  14. Base value_1,
  15. Base value_2,
  16. Base value_3,
  17. }
  18. circuit "Encrypt" {
  19. ################################################
  20. # 1. Derive shared secret using DH
  21. ################################################
  22. ephem_pub = ec_mul_var_base(ephem_secret, pubkey);
  23. ephem_pub_x = ec_get_x(ephem_pub);
  24. ephem_pub_y = ec_get_y(ephem_pub);
  25. # Used by the receiver to also derive the same shared secret
  26. constrain_instance(ephem_pub_x);
  27. constrain_instance(ephem_pub_y);
  28. shared_secret = poseidon_hash(ephem_pub_x, ephem_pub_y);
  29. ################################################
  30. # 2. Derive blinding factors for witness values
  31. ################################################
  32. N1 = witness_base(1);
  33. N2 = witness_base(2);
  34. N3 = witness_base(3);
  35. blind_1 = poseidon_hash(shared_secret, N1);
  36. blind_2 = poseidon_hash(shared_secret, N2);
  37. blind_3 = poseidon_hash(shared_secret, N3);
  38. ################################################
  39. # 3. Encrypt the values by applying blinds
  40. ################################################
  41. # This could be add or mul
  42. enc_value_1 = base_mul(value_1, blind_1);
  43. enc_value_2 = base_mul(value_2, blind_2);
  44. enc_value_3 = base_mul(value_3, blind_3);
  45. constrain_instance(enc_value_1);
  46. constrain_instance(enc_value_2);
  47. constrain_instance(enc_value_3);
  48. }