finished last of the compile errors
[org.ibex.crypto.git] / src / org / ibex / crypto / RSA.java
1 package org.ibex.crypto;
2 import java.math.BigInteger;
3 import java.util.*;
4
5 public class RSA {
6     private final BigInteger pq;
7     private final BigInteger e;
8     private final boolean reverse;
9     
10     public RSA(BigInteger pq, BigInteger e, boolean reverse) {
11         this.pq = pq;
12         this.e = e;
13         this.reverse = reverse;
14     }
15     
16     public int getInputBlockSize() { return (pq.bitLength()+7) / 8 - (reverse ? 0 : 1); }
17     public int getOutputBlockSize() { return (pq.bitLength()+7) / 8 - (reverse ? 1 : 0); }
18     
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);
29             return buf;
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);
34             return buf;
35         } else {
36             return cbytes;
37         }
38     }
39
40     public static class PublicKey {
41         public final BigInteger modulus;
42         public final BigInteger exponent;
43         
44         public PublicKey(Object o) {
45             Vector seq = (Vector) o;
46             modulus = (BigInteger) seq.elementAt(0);
47             exponent = (BigInteger) seq.elementAt(1);
48         }
49     }
50
51 }