Skip to content

Instantly share code, notes, and snippets.

@Kaelinator
Created April 25, 2022 18:49
Show Gist options
  • Select an option

  • Save Kaelinator/86e0facf4935988c557b07377445f28e to your computer and use it in GitHub Desktop.

Select an option

Save Kaelinator/86e0facf4935988c557b07377445f28e to your computer and use it in GitHub Desktop.
Pseudorandom Function Encryption in Java
import java.math.BigInteger;
import java.util.Random;
import java.util.HashMap;
class PRFEncryption {
private BigInteger key;
private int length;
public PRFEncryption(int length) {
this.length = length;
this.key = random(length);
}
/*
* returns cyphertext = [r, m xor F(key, r)]
*/
public BigInteger[] encrypt(BigInteger message) {
BigInteger r = random(length);
BigInteger ct1 = Oracle.f(key, r).xor(message);
return new BigInteger[] { r, ct1 };
}
/*
* returns message
*/
public BigInteger decrypt(BigInteger r, BigInteger ct1) {
return Oracle.f(key, r).xor(ct1);
}
private static BigInteger random(int length) {
Random rnd = new Random();
String n = "";
for (int i = 0; i < length; i++) {
n += rnd.nextInt(10);
}
return new BigInteger(n);
}
static class Oracle {
private static HashMap<String, String> prf = new HashMap<String, String>();
public static BigInteger f(BigInteger key, BigInteger input) {
String keyS = key.toString();
String inputS = input.toString();
String pair = keyS + inputS;
if (prf.containsKey(pair)) {
return new BigInteger(prf.get(pair));
}
BigInteger output = random(keyS.length());
prf.put(pair, output.toString());
return output;
}
}
public static void main(String[] args) {
PRFEncryption scheme = new PRFEncryption(10);
BigInteger message = new BigInteger("1234567890");
System.out.println("Message: " + message);
BigInteger[] cyphertext = scheme.encrypt(message);
System.out.println("Cyphertext: " + cyphertext[0] + "" + cyphertext[1]);
BigInteger output = scheme.decrypt(cyphertext[0], cyphertext[1]);
System.out.println("Output: " + output);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment