HammingDistance.java 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package com.oblivm.backend.example;
  2. import com.oblivm.backend.circuits.arithmetic.IntegerLib;
  3. import com.oblivm.backend.flexsc.CompEnv;
  4. import com.oblivm.backend.gc.BadLabelException;
  5. import com.oblivm.backend.util.EvaRunnable;
  6. import com.oblivm.backend.util.GenRunnable;
  7. public class HammingDistance {
  8. static int totalLength = 100;
  9. private static int countOnes(boolean[] in) {
  10. int cnt = 0;
  11. for (int i = 0; i < in.length; i++)
  12. if (in[i])
  13. cnt++;
  14. return cnt;
  15. }
  16. private static int booleansToInt(boolean[] arr) {
  17. int n = 0;
  18. for (int i = arr.length - 1; i >= 0; i--)
  19. n = (n << 1) | (arr[i] ? 1 : 0);
  20. return n;
  21. }
  22. public static class Generator<T> extends GenRunnable<T> {
  23. T[] inputA;
  24. T[] inputB;
  25. T[] scResult;
  26. int cnt;
  27. @Override
  28. public void prepareInput(CompEnv<T> gen) {
  29. boolean[] in = new boolean[totalLength];
  30. for (int i = 0; i < in.length; ++i)
  31. in[i] = CompEnv.rnd.nextBoolean();
  32. inputA = gen.inputOfAlice(in);
  33. gen.flush();
  34. inputB = gen.inputOfBob(new boolean[totalLength]);
  35. cnt = countOnes(in);
  36. }
  37. @Override
  38. public void secureCompute(CompEnv<T> gen) {
  39. scResult = compute(gen, inputA, inputB);
  40. }
  41. private T[] compute(CompEnv<T> gen, T[] inputA, T[] inputB) {
  42. return new IntegerLib<T>(gen).hammingDistance(inputA, inputB);
  43. }
  44. @Override
  45. public void prepareOutput(CompEnv<T> gen) throws BadLabelException {
  46. boolean[] out = gen.outputToAlice(scResult);
  47. int outValue = booleansToInt(out);
  48. System.out.println((outValue == cnt) + " " + cnt + " " + outValue);
  49. }
  50. }
  51. public static class Evaluator<T> extends EvaRunnable<T> {
  52. T[] inputA;
  53. T[] inputB;
  54. T[] scResult;
  55. @Override
  56. public void prepareInput(CompEnv<T> gen) {
  57. boolean[] in = new boolean[totalLength];
  58. // for(int i = 0; i < in.length; ++i)
  59. // in[i] = CompEnv.rnd.nextBoolean();
  60. inputA = gen.inputOfAlice(new boolean[totalLength]);
  61. gen.flush();
  62. inputB = gen.inputOfBob(in);
  63. }
  64. @Override
  65. public void secureCompute(CompEnv<T> gen) {
  66. scResult = compute(gen, inputA, inputB);
  67. }
  68. private T[] compute(CompEnv<T> gen, T[] inputA, T[] inputB) {
  69. IntegerLib<T> il = new IntegerLib<T>(gen);
  70. il.hammingDistance(inputA, inputB);
  71. gen.setEvaluate();
  72. return il.hammingDistance(inputA, inputB);
  73. }
  74. @Override
  75. public void prepareOutput(CompEnv<T> gen) throws BadLabelException {
  76. gen.outputToAlice(scResult);
  77. }
  78. }
  79. }