f5d07593c8aeb794bc9b763f3d8a2521485f3e18
[org.ibex.crypto.git] / src / org / ibex / crypto / PKCS1.java
1 package com.brian_web.crypto;
2
3 import java.security.SecureRandom;
4
5 public class PKCS1 {
6     private final RSA rsa;
7     private final SecureRandom srand;
8     public PKCS1(RSA rsa) { this(rsa,new SecureRandom()); }
9     public PKCS1(RSA rsa,SecureRandom srand) { this.rsa = rsa; this.srand = srand; }
10     
11     public byte[] encode(byte[] in) {
12         int size = rsa.getInputBlockSize();
13         if(in.length > size -  11) throw new IllegalArgumentException("message too long");
14         byte[] buf = new byte[size];
15         byte[] rand = new byte[size - in.length - 2];
16         srand.nextBytes(rand);
17         for(int i=0;i<rand.length;i++) while(rand[i] == 0) rand[i] = (byte)srand.nextInt();
18         int p=0;
19         buf[p++] = 0x02;
20         System.arraycopy(rand,0,buf,p,rand.length);
21         p+=rand.length;
22         buf[p++]  = 0x0;
23         System.arraycopy(in,0,buf,p,in.length);
24
25         return rsa.process(buf);
26     }
27     
28     public byte[] decode(byte[] in) throws Exn {
29         byte[] buf = rsa.process(in);
30         if(buf.length < 10) throw new Exn("Data too short");
31         if(buf[0] != 2 && buf[0] != 1) throw new Exn("Data not in correct format " + (buf[0]&0xff));
32         int start = 9;
33         while(start < buf.length && buf[start] != 0) start++;
34         if(start == buf.length) throw new Exn("No null separator");
35         start++;
36         byte[] ret = new byte[buf.length - start];
37         System.arraycopy(buf,start,ret,0,ret.length);
38         return ret;
39     }
40     
41     public static class Exn extends Exception { public Exn(String s) { super(s); } }
42 }