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