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