1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
/* 1-2 Oblivious Transfer algorithm using files
 * SI 486D Spring 2016
 */
 
import java.io.*;
import java.util.Arrays;
import java.nio.file.*;
import java.nio.charset.*;
import java.security.*;
import java.security.interfaces.*;
import java.security.spec.*;
import javax.crypto.*;
 
public class OT {
  public static void main(String[] args) {
    PrintWriter cwrite = System.console().writer();
    if (args.length == 1 && args[0].toLowerCase().charAt(0) == 'a') {
      String m0 = read("First message: ");
      String m1 = read("Second message: ");
      Alice a = new Alice(m0, m1);
      a.first();
      pause("Initial data generated. Press ENTER after message is chosen.");
      a.second();
      cwrite.println("Sending complete.");
    }
    else if (args.length == 1 && args[0].toLowerCase().charAt(0) == 'b') {
      String choicestr = read("Which message do you want (0 or 1)? ");
      int choice = Integer.valueOf(choicestr);
      if (choice != 0 && choice != 1) {
        cwrite.println("ERROR: you didn't choose 0 or 1");
        System.exit(1);
      }
      Bob b = new Bob(choice);
      b.first();
      pause("Response sent. Press ENTER after the response is received.");
      String m = b.second();
      cwrite.println("Your message is below.");
      cwrite.println(m);
    }
    else {
      cwrite.println("ERROR: Please enter 'a' or 'b' on the command line.");
      System.exit(1);
    }
    System.exit(0);
  }
 
  private static String read(String prompt) {
    Console cons = System.console();
    cons.writer().print(prompt);
    cons.flush();
    return new String(cons.readPassword());
  }
 
  private static void pause(String msg) {
    Console cons = System.console();
    cons.writer().print(msg);
    cons.flush();
    cons.readLine();
  }
 
  /** Encodes string s into exactly n bytes. */
  static byte[] str2bytes(String s, int n) {
    byte[] b = s.getBytes(StandardCharsets.UTF_8);
    if (b.length > n) {
      System.err.println("ERROR: message is too long to encode in " + n + " bytes");
      System.exit(1);
    }
    return Arrays.copyOf(b, n);
  }
 
  /** Decodes bytes back to string, removing any padding null bytes. */
  static String bytes2str(byte[] a) {
    String s = new String(a, StandardCharsets.UTF_8);
    int n = s.length();
    for (; n > 0 && s.charAt(n-1) == '\0'; --n);
    return s.substring(0, n);
  }
 
  /** Performs byte-wise XOR on two byte arrays. */
  static byte[] xor(byte[] a, byte[] b) {
    byte[] res = new byte[Math.min(a.length, b.length)];
    for (int i=0; i<res.length; ++i) {
      res[i] = (byte)(a[i] ^ b[i]);
    }
    return res;
  }
 
  /** Reads a file and returns a byte array of its contents. */
  static byte[] load(String name) {
    try {
      return Files.readAllBytes(Paths.get(name));
    }
    catch(IOException e) {
      System.err.println("Couldn't read file " + name);
      System.exit(1);
      return null; // stupid compiler doesn't understand System.exit
    }
  }
 
  /** Stores byte array data into a file with the given name. */
  static void store(String name, byte[] data) {
    try {
      Files.write(Paths.get(name), data);
    }
    catch(IOException e) {
      System.err.println("Error writing file " + name);
      System.exit(1);
    }
  }
 
}
 
class Alice {
  private int modlen;
  private byte[] m0b=null, m1b=null;
  private byte[] x0=null, x1=null;
  private KeyPair keys = null;
 
  public Alice(String m0, String m1) {
    this(m0, m1, 1024);
  }
 
  public Alice(String m0, String m1, int modlen) {
    this.modlen = modlen;
    int bytelen = this.modlen / 8;
    this.m0b = OT.str2bytes(m0, bytelen);
    this.m1b = OT.str2bytes(m1, bytelen);
  }
 
  public void first() {
    SecureRandom rgen = new SecureRandom();
 
    KeyPairGenerator kg = null;
    try { kg = KeyPairGenerator.getInstance("RSA"); }
    catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); }
    kg.initialize(this.modlen, rgen);
 
    // Generate key-pair.
    // The top 2 bits of the RSA modulus must both equal 1.
    // This loop executes expected O(1) times to find such a modulus.
    java.math.BigInteger mod = null;
    do {
      this.keys = kg.generateKeyPair();
      mod = ((RSAPublicKey)this.keys.getPublic()).getModulus();
    } while (! mod.testBit(this.modlen-2));
 
    int bytelen = this.modlen / 8;
    this.x0 = new byte[bytelen];
    rgen.nextBytes(this.x0);
    this.x1 = new byte[bytelen];
    rgen.nextBytes(this.x1);
 
    OT.store("x0", this.x0);
    OT.store("x1", this.x1);
    OT.store("Enc", this.keys.getPublic().getEncoded());
  }
 
  public void second() {
    byte[] u = OT.load("u");
    byte[] v0=null, v1=null;
 
    try {
      Cipher dec = Cipher.getInstance("RSA/ECB/NoPadding");
      dec.init(Cipher.DECRYPT_MODE, this.keys.getPrivate());
      v0 = OT.xor(dec.doFinal(OT.xor(u, this.x0)), this.m0b);
      v1 = OT.xor(dec.doFinal(OT.xor(u, this.x1)), this.m1b);
    }
    catch (GeneralSecurityException e) { throw new RuntimeException(e); }
 
    OT.store("v0", v0);
    OT.store("v1", v1);
  }
}
 
class Bob {
  int b;
  byte[] y = null;
 
  public Bob(int b) {
    this.b = b;
  }
 
  public void first() {
    SecureRandom rgen = new SecureRandom();
 
    byte[][] xx = new byte[2][];
    xx[0] = OT.load("x0");
    xx[1] = OT.load("x1");
    int bytelen = xx[0].length;
 
    byte[] Enc = OT.load("Enc");
 
    // Load public key from bytes encoding
    Cipher rsa = null;
    RSAPublicKey key = null;
    try { 
      rsa = Cipher.getInstance("RSA/ECB/NoPadding"); 
      key = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(Enc));
      rsa.init(Cipher.ENCRYPT_MODE, key);
    }
    catch (GeneralSecurityException e) { throw new RuntimeException(e); }
 
    // Generate random nonce y and encrypted response u.
    // Have to iterate until both decryptions on the other end are less
    // than the modulus, expected O(1) times.
    byte[] u = null;
    do {
      this.y = new byte[bytelen];
      rgen.nextBytes(this.y);
      try { 
        u = OT.xor(rsa.doFinal(this.y), xx[this.b]);
        // this encryption is just to check the bounds of y
        rsa.doFinal(OT.xor(u, xx[1-this.b]));
      }
      catch (BadPaddingException e) { 
        this.y = null;
        u = null; 
      }
      catch (GeneralSecurityException e) { throw new RuntimeException(e); }
    } while (u == null);
 
    OT.store("u", u);
  }
 
  public String second() {
    byte[][] vv = new byte[2][];
    vv[0] = OT.load("v0");
    vv[1] = OT.load("v1");
 
    return OT.bytes2str(OT.xor(this.y, vv[this.b]));
  }
}