licensing update to APSL 2.0
[org.ibex.crypto.git] / src / org / ibex / crypto / RSA.java
1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
4
5 package org.ibex.crypto;
6 import java.math.BigInteger;
7 import java.util.*;
8
9 public class RSA {
10     private final BigInteger pq;
11     private final BigInteger e;
12     private final boolean reverse;
13     
14     public RSA(BigInteger pq, BigInteger e, boolean reverse) {
15         this.pq = pq;
16         this.e = e;
17         this.reverse = reverse;
18     }
19     
20     public int getInputBlockSize() { return (pq.bitLength()+7) / 8 - (reverse ? 0 : 1); }
21     public int getOutputBlockSize() { return (pq.bitLength()+7) / 8 - (reverse ? 1 : 0); }
22     
23     public byte[] process(byte[] in) {
24         // output block is the same size as the modulus (rounded up)
25         int outSize = getOutputBlockSize();
26         BigInteger t = new BigInteger(1,in);
27         BigInteger c = t.modPow(e,pq);
28         byte[] cbytes = c.toByteArray();
29         if(cbytes.length > outSize || (reverse && cbytes[0] == 0)) {
30             if(cbytes[0] != 0) throw new RuntimeException("should never happen");
31             byte[] buf = new byte[outSize];
32             System.arraycopy(cbytes,1,buf,0,outSize);
33             return buf;
34         } else if(!reverse && cbytes.length < outSize) {
35             // output needs to be exactly outSize in length
36             byte[] buf = new byte[outSize];
37             System.arraycopy(cbytes,0,buf,outSize-cbytes.length,cbytes.length);
38             return buf;
39         } else {
40             return cbytes;
41         }
42     }
43
44     public static class PublicKey {
45         public final BigInteger modulus;
46         public final BigInteger exponent;
47         
48         public PublicKey(Object o) {
49             Vector seq = (Vector) o;
50             modulus = (BigInteger) seq.elementAt(0);
51             exponent = (BigInteger) seq.elementAt(1);
52         }
53     }
54
55 }