main.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. // We really want points to be capital letters and scalars to be
  2. // lowercase letters
  3. #![allow(non_snake_case)]
  4. pub mod params;
  5. use aes::cipher::{BlockEncrypt, KeyInit};
  6. use aes::Aes128Enc;
  7. use aes::Block;
  8. use std::env;
  9. use std::io::Cursor;
  10. use std::mem;
  11. use std::time::Instant;
  12. use subtle::Choice;
  13. use subtle::ConditionallySelectable;
  14. use rand::RngCore;
  15. use sha2::Digest;
  16. use sha2::Sha256;
  17. use sha2::Sha512;
  18. use curve25519_dalek::constants as dalek_constants;
  19. use curve25519_dalek::ristretto::CompressedRistretto;
  20. use curve25519_dalek::ristretto::RistrettoBasepointTable;
  21. use curve25519_dalek::ristretto::RistrettoPoint;
  22. use curve25519_dalek::scalar::Scalar;
  23. use spiral_rs::client::*;
  24. use spiral_rs::params::*;
  25. use spiral_rs::server::*;
  26. use lazy_static::lazy_static;
  27. type DbEntry = u64;
  28. // Generators of the Ristretto group (the standard B and another one C,
  29. // for which the DL relationship is unknown), and their precomputed
  30. // multiplication tables. Used for the Oblivious Transfer protocol
  31. lazy_static! {
  32. pub static ref OT_B: RistrettoPoint = dalek_constants::RISTRETTO_BASEPOINT_POINT;
  33. pub static ref OT_C: RistrettoPoint =
  34. RistrettoPoint::hash_from_bytes::<Sha512>(b"OT Generator C");
  35. pub static ref OT_B_TABLE: RistrettoBasepointTable = dalek_constants::RISTRETTO_BASEPOINT_TABLE;
  36. pub static ref OT_C_TABLE: RistrettoBasepointTable = RistrettoBasepointTable::create(&OT_C);
  37. }
  38. // XOR a 16-byte slice into a Block (which will be used as an AES key)
  39. fn xor16(outar: &mut Block, inar: &[u8; 16]) {
  40. for i in 0..16 {
  41. outar[i] ^= inar[i];
  42. }
  43. }
  44. // Encrypt a database of 2^r elements, where each element is a DbEntry,
  45. // using the 2*r provided keys (r pairs of keys). Also add the provided
  46. // blinding factor to each element before encryption (the same blinding
  47. // factor for all elements). Each element is encrypted in AES counter
  48. // mode, with the counter being the element number and the key computed
  49. // as the XOR of r of the provided keys, one from each pair, according
  50. // to the bits of the element number. Outputs a byte vector containing
  51. // the encrypted database.
  52. fn encdb_xor_keys(db: &[DbEntry], keys: &[[u8; 16]], r: usize, blind: DbEntry) -> Vec<u8> {
  53. let num_records: usize = 1 << r;
  54. let mut ret = Vec::<u8>::with_capacity(num_records * mem::size_of::<DbEntry>());
  55. for j in 0..num_records {
  56. let mut key = Block::from([0u8; 16]);
  57. for i in 0..r {
  58. let bit = if (j & (1 << i)) == 0 { 0 } else { 1 };
  59. xor16(&mut key, &keys[2 * i + bit]);
  60. }
  61. let aes = Aes128Enc::new(&key);
  62. let mut block = Block::from([0u8; 16]);
  63. block[0..8].copy_from_slice(&j.to_le_bytes());
  64. aes.encrypt_block(&mut block);
  65. let aeskeystream = DbEntry::from_le_bytes(block[0..8].try_into().unwrap());
  66. let encelem = (db[j].wrapping_add(blind)) ^ aeskeystream;
  67. ret.extend(encelem.to_le_bytes());
  68. }
  69. ret
  70. }
  71. // Generate the keys for encrypting the database
  72. fn gen_db_enc_keys(r: usize) -> Vec<[u8; 16]> {
  73. let mut keys: Vec<[u8; 16]> = Vec::new();
  74. let mut rng = rand::thread_rng();
  75. for _ in 0..2 * r {
  76. let mut k: [u8; 16] = [0; 16];
  77. rng.fill_bytes(&mut k);
  78. keys.push(k);
  79. }
  80. keys
  81. }
  82. // 1-out-of-2 Oblivious Transfer (OT)
  83. fn ot12_request(sel: Choice) -> ((Choice, Scalar), [u8; 32]) {
  84. let Btable: &RistrettoBasepointTable = &OT_B_TABLE;
  85. let C: &RistrettoPoint = &OT_C;
  86. let mut rng = rand07::thread_rng();
  87. let x = Scalar::random(&mut rng);
  88. let xB = &x * Btable;
  89. let CmxB = C - xB;
  90. let P = RistrettoPoint::conditional_select(&xB, &CmxB, sel);
  91. ((sel, x), P.compress().to_bytes())
  92. }
  93. fn ot12_serve(query: &[u8; 32], m0: &[u8; 16], m1: &[u8; 16]) -> [u8; 64] {
  94. let Btable: &RistrettoBasepointTable = &OT_B_TABLE;
  95. let Ctable: &RistrettoBasepointTable = &OT_C_TABLE;
  96. let mut rng = rand07::thread_rng();
  97. let y = Scalar::random(&mut rng);
  98. let yB = &y * Btable;
  99. let yC = &y * Ctable;
  100. let P = CompressedRistretto::from_slice(query).decompress().unwrap();
  101. let yP0 = y * P;
  102. let yP1 = yC - yP0;
  103. let mut HyP0 = Sha256::digest(yP0.compress().as_bytes());
  104. for i in 0..16 {
  105. HyP0[i] ^= m0[i];
  106. }
  107. let mut HyP1 = Sha256::digest(yP1.compress().as_bytes());
  108. for i in 0..16 {
  109. HyP1[i] ^= m1[i];
  110. }
  111. let mut ret = [0u8; 64];
  112. ret[0..32].copy_from_slice(yB.compress().as_bytes());
  113. ret[32..48].copy_from_slice(&HyP0[0..16]);
  114. ret[48..64].copy_from_slice(&HyP1[0..16]);
  115. ret
  116. }
  117. fn ot12_receive(state: (Choice, Scalar), response: &[u8; 64]) -> [u8; 16] {
  118. let yB = CompressedRistretto::from_slice(&response[0..32])
  119. .decompress()
  120. .unwrap();
  121. let yP = state.1 * yB;
  122. let mut HyP = Sha256::digest(yP.compress().as_bytes());
  123. for i in 0..16 {
  124. HyP[i] ^= u8::conditional_select(&response[32 + i], &response[48 + i], state.0);
  125. }
  126. HyP[0..16].try_into().unwrap()
  127. }
  128. // Obliviously fetch the key for element q of the database (which has
  129. // 2^r elements total). Each bit of q is used in a 1-out-of-2 OT to get
  130. // one of the keys in each of the r pairs of keys on the server side.
  131. // The resulting r keys are XORed together.
  132. fn otkey_request(q: usize, r: usize) -> (Vec<(Choice, Scalar)>, Vec<[u8; 32]>) {
  133. let mut state: Vec<(Choice, Scalar)> = Vec::with_capacity(r);
  134. let mut query: Vec<[u8; 32]> = Vec::with_capacity(r);
  135. for i in 0..r {
  136. let bit = ((q >> i) & 1) as u8;
  137. let (si, qi) = ot12_request(bit.into());
  138. state.push(si);
  139. query.push(qi);
  140. }
  141. (state, query)
  142. }
  143. fn otkey_serve(query: Vec<[u8; 32]>, keys: &Vec<[u8; 16]>) -> Vec<[u8; 64]> {
  144. let r = query.len();
  145. assert!(keys.len() == 2 * r);
  146. let mut response: Vec<[u8; 64]> = Vec::with_capacity(r);
  147. for i in 0..r {
  148. response.push(ot12_serve(&query[i], &keys[2 * i], &keys[2 * i + 1]));
  149. }
  150. response
  151. }
  152. fn otkey_receive(state: Vec<(Choice, Scalar)>, response: &Vec<[u8; 64]>) -> Block {
  153. let r = state.len();
  154. assert!(response.len() == r);
  155. let mut key = Block::from([0u8; 16]);
  156. for i in 0..r {
  157. xor16(&mut key, &ot12_receive(state[i], &response[i]));
  158. }
  159. key
  160. }
  161. // Having received the key for element q with r parallel 1-out-of-2 OTs,
  162. // and having received the encrypted element with (non-symmetric) PIR,
  163. // use the key to decrypt the element.
  164. fn otkey_decrypt(key: &Block, q: usize, encelement: DbEntry) -> DbEntry {
  165. let aes = Aes128Enc::new(key);
  166. let mut block = Block::from([0u8; 16]);
  167. block[0..8].copy_from_slice(&q.to_le_bytes());
  168. aes.encrypt_block(&mut block);
  169. let aeskeystream = DbEntry::from_le_bytes(block[0..8].try_into().unwrap());
  170. encelement ^ aeskeystream
  171. }
  172. // Things that are only done once total, not once for each SPIR
  173. fn one_time_setup() {
  174. // Resolve the lazy statics
  175. let _B: &RistrettoPoint = &OT_B;
  176. let _Btable: &RistrettoBasepointTable = &OT_B_TABLE;
  177. let _C: &RistrettoPoint = &OT_C;
  178. let _Ctable: &RistrettoBasepointTable = &OT_C_TABLE;
  179. }
  180. fn print_params_summary(params: &Params) {
  181. let db_elem_size = params.item_size();
  182. let total_size = params.num_items() * db_elem_size;
  183. println!(
  184. "Using a {} x {} byte database ({} bytes total)",
  185. params.num_items(),
  186. db_elem_size,
  187. total_size
  188. );
  189. }
  190. fn main() {
  191. let args: Vec<String> = env::args().collect();
  192. if args.len() != 2 {
  193. println!("Usage: {} r\nr = log_2(num_records)", args[0]);
  194. return;
  195. }
  196. let r: usize = args[1].parse().unwrap();
  197. let num_records = 1 << r;
  198. println!("===== ONE-TIME SETUP =====\n");
  199. let otsetup_start = Instant::now();
  200. let spiral_params = params::get_spiral_params(r);
  201. let mut rng = rand::thread_rng();
  202. one_time_setup();
  203. let otsetup_us = otsetup_start.elapsed().as_micros();
  204. print_params_summary(&spiral_params);
  205. println!("OT one-time setup: {} µs", otsetup_us);
  206. // One-time setup for the Spiral client
  207. let spc_otsetup_start = Instant::now();
  208. let mut clientrng = rand::thread_rng();
  209. let mut client = Client::init(&spiral_params, &mut clientrng);
  210. let pub_params = client.generate_keys();
  211. let pub_params_buf = pub_params.serialize();
  212. let spc_otsetup_us = spc_otsetup_start.elapsed().as_micros();
  213. let spiral_blocking_factor = spiral_params.db_item_size / mem::size_of::<DbEntry>();
  214. println!(
  215. "Spiral client one-time setup: {} µs, {} bytes",
  216. spc_otsetup_us,
  217. pub_params_buf.len()
  218. );
  219. println!("\n===== PREPROCESSING =====\n");
  220. // Spiral preprocessing: create a PIR lookup for an element at a
  221. // random location
  222. let spc_query_start = Instant::now();
  223. let rand_idx = (rng.next_u64() as usize) % num_records;
  224. let rand_pir_idx = rand_idx / spiral_blocking_factor;
  225. println!("rand_idx = {} rand_pir_idx = {}", rand_idx, rand_pir_idx);
  226. let spc_query = client.generate_query(rand_pir_idx);
  227. let spc_query_buf = spc_query.serialize();
  228. let spc_query_us = spc_query_start.elapsed().as_micros();
  229. println!(
  230. "Spiral query: {} µs, {} bytes",
  231. spc_query_us,
  232. spc_query_buf.len()
  233. );
  234. // Create the database encryption keys and do the OT to fetch the
  235. // right one, but don't actually encrypt the database yet
  236. let dbkeys = gen_db_enc_keys(r);
  237. let otkeyreq_start = Instant::now();
  238. let (keystate, keyquery) = otkey_request(rand_idx, r);
  239. let keyquerysize = keyquery.len() * keyquery[0].len();
  240. let otkeyreq_us = otkeyreq_start.elapsed().as_micros();
  241. let otkeysrv_start = Instant::now();
  242. let keyresponse = otkey_serve(keyquery, &dbkeys);
  243. let keyrespsize = keyresponse.len() * keyresponse[0].len();
  244. let otkeysrv_us = otkeysrv_start.elapsed().as_micros();
  245. let otkeyrcv_start = Instant::now();
  246. let otkey = otkey_receive(keystate, &keyresponse);
  247. let otkeyrcv_us = otkeyrcv_start.elapsed().as_micros();
  248. println!("key OT query in {} µs, {} bytes", otkeyreq_us, keyquerysize);
  249. println!("key OT serve in {} µs, {} bytes", otkeysrv_us, keyrespsize);
  250. println!("key OT receive in {} µs", otkeyrcv_us);
  251. // Create a database with recognizable contents
  252. let mut db: Vec<DbEntry> = ((0 as DbEntry)..(num_records as DbEntry))
  253. .map(|x| 10000001 * x)
  254. .collect();
  255. println!("\n===== RUNTIME =====\n");
  256. // Pick the record we actually want to query
  257. let q = (rng.next_u64() as usize) % num_records;
  258. // Compute the offset from the record index we're actually looking
  259. // for to the random one we picked earlier. Tell it to the server,
  260. // who will rotate right the database by that amount before
  261. // encrypting it.
  262. let idx_offset = (num_records + rand_idx - q) % num_records;
  263. println!("Send to server {} bytes", 8 /* sizeof(idx_offset) */);
  264. // The server rotates, blinds, and encrypts the database
  265. let blind: DbEntry = 20;
  266. let encdb_start = Instant::now();
  267. db.rotate_right(idx_offset);
  268. let encdb = encdb_xor_keys(&db, &dbkeys, r, blind);
  269. let encdb_us = encdb_start.elapsed().as_micros();
  270. println!("Server encrypt database {} µs", encdb_us);
  271. // Load the encrypted database into Spiral
  272. let sps_loaddb_start = Instant::now();
  273. let sps_db = load_db_from_seek(&spiral_params, &mut Cursor::new(encdb));
  274. let sps_loaddb_us = sps_loaddb_start.elapsed().as_micros();
  275. println!("Server load database {} µs", sps_loaddb_us);
  276. // Do the PIR query
  277. let sps_query_start = Instant::now();
  278. let sps_query = Query::deserialize(&spiral_params, &spc_query_buf);
  279. let sps_response = process_query(&spiral_params, &pub_params, &sps_query, sps_db.as_slice());
  280. let sps_query_us = sps_query_start.elapsed().as_micros();
  281. println!(
  282. "Server compute response {} µs, {} bytes (*including* the above expansion time)",
  283. sps_query_us,
  284. sps_response.len()
  285. );
  286. // Decode the response to yield the whole Spiral block
  287. let spc_recv_start = Instant::now();
  288. let encdbblock = client.decode_response(sps_response.as_slice());
  289. // Extract the one encrypted DbEntry we were looking for (and the
  290. // only one we are able to decrypt)
  291. let entry_in_block = rand_idx % spiral_blocking_factor;
  292. let loc_in_block = entry_in_block * mem::size_of::<DbEntry>();
  293. let loc_in_block_end = (entry_in_block + 1) * mem::size_of::<DbEntry>();
  294. let encdbentry = DbEntry::from_le_bytes(
  295. encdbblock[loc_in_block..loc_in_block_end]
  296. .try_into()
  297. .unwrap(),
  298. );
  299. let decdbentry = otkey_decrypt(&otkey, rand_idx, encdbentry);
  300. let spc_recv_us = spc_recv_start.elapsed().as_micros();
  301. println!("Client decode response {} µs", spc_recv_us);
  302. println!("index = {}, Response = {}", q, decdbentry);
  303. }