1 package org.ibex.crypto;
2 import java.math.BigInteger;
6 private final BigInteger pq;
7 private final BigInteger e;
8 private final boolean reverse;
10 public RSA(BigInteger pq, BigInteger e, boolean reverse) {
13 this.reverse = reverse;
16 public int getInputBlockSize() { return (pq.bitLength()+7) / 8 - (reverse ? 0 : 1); }
17 public int getOutputBlockSize() { return (pq.bitLength()+7) / 8 - (reverse ? 1 : 0); }
19 public byte[] process(byte[] in) {
20 // output block is the same size as the modulus (rounded up)
21 int outSize = getOutputBlockSize();
22 BigInteger t = new BigInteger(1,in);
23 BigInteger c = t.modPow(e,pq);
24 byte[] cbytes = c.toByteArray();
25 if(cbytes.length > outSize || (reverse && cbytes[0] == 0)) {
26 if(cbytes[0] != 0) throw new RuntimeException("should never happen");
27 byte[] buf = new byte[outSize];
28 System.arraycopy(cbytes,1,buf,0,outSize);
30 } else if(!reverse && cbytes.length < outSize) {
31 // output needs to be exactly outSize in length
32 byte[] buf = new byte[outSize];
33 System.arraycopy(cbytes,0,buf,outSize-cbytes.length,cbytes.length);
40 public static class PublicKey {
41 public final BigInteger modulus;
42 public final BigInteger exponent;
44 public PublicKey(Object o) {
45 Vector seq = (Vector) o;
46 modulus = (BigInteger) seq.elementAt(0);
47 exponent = (BigInteger) seq.elementAt(1);