lib.rs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. // We really want points to be capital letters and scalars to be
  2. // lowercase letters
  3. #![allow(non_snake_case)]
  4. mod aligned_memory_mt;
  5. mod params;
  6. mod spiral_mt;
  7. pub mod client;
  8. pub mod server;
  9. use aes::cipher::{BlockEncrypt, KeyInit};
  10. use aes::Aes128Enc;
  11. use aes::Block;
  12. use std::env;
  13. use std::mem;
  14. use std::time::Instant;
  15. use subtle::Choice;
  16. use subtle::ConditionallySelectable;
  17. use rand::RngCore;
  18. use sha2::Digest;
  19. use sha2::Sha256;
  20. use sha2::Sha512;
  21. use curve25519_dalek::constants as dalek_constants;
  22. use curve25519_dalek::ristretto::CompressedRistretto;
  23. use curve25519_dalek::ristretto::RistrettoBasepointTable;
  24. use curve25519_dalek::ristretto::RistrettoPoint;
  25. use curve25519_dalek::scalar::Scalar;
  26. use rayon::scope;
  27. use rayon::ThreadPoolBuilder;
  28. use spiral_rs::client::*;
  29. use spiral_rs::params::*;
  30. use spiral_rs::server::*;
  31. use crate::spiral_mt::*;
  32. use lazy_static::lazy_static;
  33. pub type DbEntry = u64;
  34. // Generators of the Ristretto group (the standard B and another one C,
  35. // for which the DL relationship is unknown), and their precomputed
  36. // multiplication tables. Used for the Oblivious Transfer protocol
  37. lazy_static! {
  38. pub static ref OT_B: RistrettoPoint = dalek_constants::RISTRETTO_BASEPOINT_POINT;
  39. pub static ref OT_C: RistrettoPoint =
  40. RistrettoPoint::hash_from_bytes::<Sha512>(b"OT Generator C");
  41. pub static ref OT_B_TABLE: RistrettoBasepointTable = dalek_constants::RISTRETTO_BASEPOINT_TABLE;
  42. pub static ref OT_C_TABLE: RistrettoBasepointTable = RistrettoBasepointTable::create(&OT_C);
  43. }
  44. // XOR a 16-byte slice into a Block (which will be used as an AES key)
  45. fn xor16(outar: &mut Block, inar: &[u8; 16]) {
  46. for i in 0..16 {
  47. outar[i] ^= inar[i];
  48. }
  49. }
  50. // Encrypt a database of 2^r elements, where each element is a DbEntry,
  51. // using the 2*r provided keys (r pairs of keys). Also rotate the
  52. // database by rot positions, and add the provided blinding factor to
  53. // each element before encryption (the same blinding factor for all
  54. // elements). Each element is encrypted in AES counter mode, with the
  55. // counter being the element number and the key computed as the XOR of r
  56. // of the provided keys, one from each pair, according to the bits of
  57. // the element number. Outputs a byte vector containing the encrypted
  58. // database.
  59. pub fn encdb_xor_keys(
  60. db: &[DbEntry],
  61. keys: &[[u8; 16]],
  62. r: usize,
  63. rot: usize,
  64. blind: DbEntry,
  65. num_threads: usize,
  66. ) -> Vec<u8> {
  67. let num_records: usize = 1 << r;
  68. let num_record_mask: usize = num_records - 1;
  69. let negrot = num_records - rot;
  70. let mut ret = Vec::<u8>::with_capacity(num_records * mem::size_of::<DbEntry>());
  71. ret.resize(num_records * mem::size_of::<DbEntry>(), 0);
  72. scope(|s| {
  73. let mut record_thread_start = 0usize;
  74. let records_per_thread_base = num_records / num_threads;
  75. let records_per_thread_extra = num_records % num_threads;
  76. let mut retslice = ret.as_mut_slice();
  77. for thr in 0..num_threads {
  78. let records_this_thread =
  79. records_per_thread_base + if thr < records_per_thread_extra { 1 } else { 0 };
  80. let record_thread_end = record_thread_start + records_this_thread;
  81. let (thread_ret, retslice_) =
  82. retslice.split_at_mut(records_this_thread * mem::size_of::<DbEntry>());
  83. retslice = retslice_;
  84. s.spawn(move |_| {
  85. let mut offset = 0usize;
  86. for j in record_thread_start..record_thread_end {
  87. let rec = (j + negrot) & num_record_mask;
  88. let mut key = Block::from([0u8; 16]);
  89. for i in 0..r {
  90. let bit = if (j & (1 << i)) == 0 { 0 } else { 1 };
  91. xor16(&mut key, &keys[2 * i + bit]);
  92. }
  93. let aes = Aes128Enc::new(&key);
  94. let mut block = Block::from([0u8; 16]);
  95. block[0..8].copy_from_slice(&j.to_le_bytes());
  96. aes.encrypt_block(&mut block);
  97. let aeskeystream = DbEntry::from_le_bytes(block[0..8].try_into().unwrap());
  98. let encelem = (db[rec].wrapping_add(blind)) ^ aeskeystream;
  99. thread_ret[offset..offset + mem::size_of::<DbEntry>()]
  100. .copy_from_slice(&encelem.to_le_bytes());
  101. offset += mem::size_of::<DbEntry>();
  102. }
  103. });
  104. record_thread_start = record_thread_end;
  105. }
  106. });
  107. ret
  108. }
  109. // Generate the keys for encrypting the database
  110. pub fn gen_db_enc_keys(r: usize) -> Vec<[u8; 16]> {
  111. let mut keys: Vec<[u8; 16]> = Vec::new();
  112. let mut rng = rand::thread_rng();
  113. for _ in 0..2 * r {
  114. let mut k: [u8; 16] = [0; 16];
  115. rng.fill_bytes(&mut k);
  116. keys.push(k);
  117. }
  118. keys
  119. }
  120. // 1-out-of-2 Oblivious Transfer (OT)
  121. fn ot12_request(sel: Choice) -> ((Choice, Scalar), [u8; 32]) {
  122. let Btable: &RistrettoBasepointTable = &OT_B_TABLE;
  123. let C: &RistrettoPoint = &OT_C;
  124. let mut rng = rand07::thread_rng();
  125. let x = Scalar::random(&mut rng);
  126. let xB = &x * Btable;
  127. let CmxB = C - xB;
  128. let P = RistrettoPoint::conditional_select(&xB, &CmxB, sel);
  129. ((sel, x), P.compress().to_bytes())
  130. }
  131. fn ot12_serve(query: &[u8; 32], m0: &[u8; 16], m1: &[u8; 16]) -> [u8; 64] {
  132. let Btable: &RistrettoBasepointTable = &OT_B_TABLE;
  133. let Ctable: &RistrettoBasepointTable = &OT_C_TABLE;
  134. let mut rng = rand07::thread_rng();
  135. let y = Scalar::random(&mut rng);
  136. let yB = &y * Btable;
  137. let yC = &y * Ctable;
  138. let P = CompressedRistretto::from_slice(query).decompress().unwrap();
  139. let yP0 = y * P;
  140. let yP1 = yC - yP0;
  141. let mut HyP0 = Sha256::digest(yP0.compress().as_bytes());
  142. for i in 0..16 {
  143. HyP0[i] ^= m0[i];
  144. }
  145. let mut HyP1 = Sha256::digest(yP1.compress().as_bytes());
  146. for i in 0..16 {
  147. HyP1[i] ^= m1[i];
  148. }
  149. let mut ret = [0u8; 64];
  150. ret[0..32].copy_from_slice(yB.compress().as_bytes());
  151. ret[32..48].copy_from_slice(&HyP0[0..16]);
  152. ret[48..64].copy_from_slice(&HyP1[0..16]);
  153. ret
  154. }
  155. fn ot12_receive(state: (Choice, Scalar), response: &[u8; 64]) -> [u8; 16] {
  156. let yB = CompressedRistretto::from_slice(&response[0..32])
  157. .decompress()
  158. .unwrap();
  159. let yP = state.1 * yB;
  160. let mut HyP = Sha256::digest(yP.compress().as_bytes());
  161. for i in 0..16 {
  162. HyP[i] ^= u8::conditional_select(&response[32 + i], &response[48 + i], state.0);
  163. }
  164. HyP[0..16].try_into().unwrap()
  165. }
  166. // Obliviously fetch the key for element q of the database (which has
  167. // 2^r elements total). Each bit of q is used in a 1-out-of-2 OT to get
  168. // one of the keys in each of the r pairs of keys on the server side.
  169. // The resulting r keys are XORed together.
  170. pub fn otkey_request(q: usize, r: usize) -> (Vec<(Choice, Scalar)>, Vec<[u8; 32]>) {
  171. let mut state: Vec<(Choice, Scalar)> = Vec::with_capacity(r);
  172. let mut query: Vec<[u8; 32]> = Vec::with_capacity(r);
  173. for i in 0..r {
  174. let bit = ((q >> i) & 1) as u8;
  175. let (si, qi) = ot12_request(bit.into());
  176. state.push(si);
  177. query.push(qi);
  178. }
  179. (state, query)
  180. }
  181. pub fn otkey_serve(query: Vec<[u8; 32]>, keys: &Vec<[u8; 16]>) -> Vec<[u8; 64]> {
  182. let r = query.len();
  183. assert!(keys.len() == 2 * r);
  184. let mut response: Vec<[u8; 64]> = Vec::with_capacity(r);
  185. for i in 0..r {
  186. response.push(ot12_serve(&query[i], &keys[2 * i], &keys[2 * i + 1]));
  187. }
  188. response
  189. }
  190. pub fn otkey_receive(state: Vec<(Choice, Scalar)>, response: &Vec<[u8; 64]>) -> Block {
  191. let r = state.len();
  192. assert!(response.len() == r);
  193. let mut key = Block::from([0u8; 16]);
  194. for i in 0..r {
  195. xor16(&mut key, &ot12_receive(state[i], &response[i]));
  196. }
  197. key
  198. }
  199. // Having received the key for element q with r parallel 1-out-of-2 OTs,
  200. // and having received the encrypted element with (non-symmetric) PIR,
  201. // use the key to decrypt the element.
  202. pub fn otkey_decrypt(key: &Block, q: usize, encelement: DbEntry) -> DbEntry {
  203. let aes = Aes128Enc::new(key);
  204. let mut block = Block::from([0u8; 16]);
  205. block[0..8].copy_from_slice(&q.to_le_bytes());
  206. aes.encrypt_block(&mut block);
  207. let aeskeystream = DbEntry::from_le_bytes(block[0..8].try_into().unwrap());
  208. encelement ^ aeskeystream
  209. }
  210. // Things that are only done once total, not once for each SPIR
  211. pub fn init(num_threads: usize) {
  212. // Resolve the lazy statics
  213. let _B: &RistrettoPoint = &OT_B;
  214. let _Btable: &RistrettoBasepointTable = &OT_B_TABLE;
  215. let _C: &RistrettoPoint = &OT_C;
  216. let _Ctable: &RistrettoBasepointTable = &OT_C_TABLE;
  217. // Initialize the thread pool
  218. ThreadPoolBuilder::new().num_threads(num_threads).build_global().unwrap();
  219. }
  220. pub fn print_params_summary(params: &Params) {
  221. let db_elem_size = params.item_size();
  222. let total_size = params.num_items() * db_elem_size;
  223. println!(
  224. "Using a {} x {} byte database ({} bytes total)",
  225. params.num_items(),
  226. db_elem_size,
  227. total_size
  228. );
  229. }
  230. #[no_mangle]
  231. pub extern "C" fn spir_init(num_threads: u32) {
  232. init(num_threads as usize);
  233. }