OSDN Git Service

Imported GNU Classpath 0.90
[pf3gnuchains/gcc-fork.git] / libjava / classpath / gnu / java / security / key / rsa / GnuRSAPrivateKey.java
1 /* GnuRSAPrivateKey.java -- 
2    Copyright 2001, 2002, 2003, 2006 Free Software Foundation, Inc.
3
4 This file is a part of GNU Classpath.
5
6 GNU Classpath is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or (at
9 your option) any later version.
10
11 GNU Classpath is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GNU Classpath; if not, write to the Free Software
18 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
19 USA
20
21 Linking this library statically or dynamically with other modules is
22 making a combined work based on this library.  Thus, the terms and
23 conditions of the GNU General Public License cover the whole
24 combination.
25
26 As a special exception, the copyright holders of this library give you
27 permission to link this library with independent modules to produce an
28 executable, regardless of the license terms of these independent
29 modules, and to copy and distribute the resulting executable under
30 terms of your choice, provided that you also meet, for each linked
31 independent module, the terms and conditions of the license of that
32 module.  An independent module is a module which is not derived from
33 or based on this library.  If you modify this library, you may extend
34 this exception to your version of the library, but you are not
35 obligated to do so.  If you do not wish to do so, delete this
36 exception statement from your version.  */
37
38
39 package gnu.java.security.key.rsa;
40
41 import gnu.classpath.SystemProperties;
42 import gnu.java.security.Registry;
43 import gnu.java.security.key.IKeyPairCodec;
44
45 import java.math.BigInteger;
46 import java.security.PrivateKey;
47 import java.security.interfaces.RSAPrivateCrtKey;
48 import java.security.interfaces.RSAPrivateKey;
49
50 /**
51  * <p>An object that embodies an RSA private key.</p>
52  *
53  * <p>References:</p>
54  * <ol>
55  *    <li><a href="http://www.cosic.esat.kuleuven.ac.be/nessie/workshop/submissions/rsa-pss.zip">
56  *    RSA-PSS Signature Scheme with Appendix, part B.</a><br>
57  *    Primitive specification and supporting documentation.<br>
58  *    Jakob Jonsson and Burt Kaliski.</li>
59  * </ol>
60  */
61 public class GnuRSAPrivateKey extends GnuRSAKey implements PrivateKey,
62     RSAPrivateCrtKey
63 {
64   // Constants and variables
65   // -------------------------------------------------------------------------
66
67   private static final boolean DEBUG = false;
68
69   /** The first prime divisor of the modulus. */
70   private final BigInteger p;
71
72   /** The second prime divisor of the modulus. */
73   private final BigInteger q;
74
75   /** The public exponent of an RSA key. */
76   //   private final BigInteger e;
77   /** The private exponent of an RSA private key. */
78   private final BigInteger d;
79
80   /** The first factor's exponent. */
81   private final BigInteger dP;
82
83   /** The second factor's exponent. */
84   private final BigInteger dQ;
85
86   /** The CRT (Chinese Remainder Theorem) coefficient. */
87   private final BigInteger qInv;
88
89   /** String representation of this key. Cached for speed. */
90   private transient String str;
91
92   // Constructor(s)
93   // -------------------------------------------------------------------------
94
95   /**
96    * Convenience constructor. Calls the constructor with 5 arguments passing
97    * {@link Registry#RAW_ENCODING_ID} as the identifier of the preferred
98    * encoding format.
99    *
100    * @param p the modulus first prime divisor.
101    * @param q the modulus second prime divisor.
102    * @param e the public exponent.
103    * @param d the private exponent.
104    */
105   public GnuRSAPrivateKey(BigInteger p, BigInteger q, BigInteger e,
106                           BigInteger d)
107   {
108     this(Registry.RAW_ENCODING_ID, p, q, e, d);
109   }
110
111   /**
112    * Constructs a new instance of a <code>GnuRSAPrivateKey</code> given the
113    * designated arguments.
114    * 
115    * @param preferredFormat the indetifier of the preferred encoding format to
116    *          use when externalizing this key.
117    * @param p the modulus first prime divisor.
118    * @param q the modulus second prime divisor.
119    * @param e the public exponent.
120    * @param d the private exponent.
121    */
122   public GnuRSAPrivateKey(int preferredFormat, BigInteger p, BigInteger q,
123                           BigInteger e, BigInteger d)
124   {
125     this(preferredFormat, p.multiply(q), e, d, p, q, 
126          e.modInverse(p.subtract(BigInteger.ONE)),
127          e.modInverse(q.subtract(BigInteger.ONE)),
128          q.modInverse(p));
129   }
130
131   /**
132    * Constructs a new instance of a <code>GnuRSAPrivateKey</code> given the
133    * designated arguments.
134    * 
135    * @param preferredFormat the indetifier of the preferred encoding format to
136    *          use when externalizing this key.
137    * @param n the public modulus, which is also the product of <code>p</code>
138    * and <code>q</code>.
139    * @param e the public exponent.
140    * @param d the private exponent.
141    * @param p the modulus first prime divisor.
142    * @param q the modulus second prime divisor.
143    * @param dP the first prime's exponen. A positive integer less than
144    * <code>p</code> and <code>q</code>, satisfying <code>e * dP = 1 (mod p-1)
145    * </code>.
146    * @param dQ the second prime's exponent. A positive integer less than
147    * <code>p</code> and <code>q</code>, satisfying <code>e * dQ = 1 (mod p-1)
148    * </code>.
149    * @param qInv the Chinese Remainder Theorem coefiicient. A positive integer
150    * less than <code>p</code>, satisfying <code>q * qInv = 1 (mod p)</code>.
151    */
152   public GnuRSAPrivateKey(int preferredFormat, BigInteger n, BigInteger e,
153                           BigInteger d, BigInteger p, BigInteger q,
154                           BigInteger dP, BigInteger dQ, BigInteger qInv)
155   {
156     super(preferredFormat == Registry.ASN1_ENCODING_ID ? Registry.PKCS8_ENCODING_ID
157                                                        : preferredFormat,
158           n, e);
159
160     this.d = d;
161     this.p = p;
162     this.q = q;
163     // the exponents dP and dQ are positive integers less than p and q
164     // respectively satisfying
165     //    e * dP = 1 (mod p-1);
166     //    e * dQ = 1 (mod q-1),
167     this.dP = dP;
168     this.dQ = dQ;
169     // the CRT coefficient qInv is a positive integer less than p satisfying
170     //    q * qInv = 1 (mod p).
171     this.qInv = qInv;
172   }
173
174   // Class methods
175   // -------------------------------------------------------------------------
176
177   /**
178    * A class method that takes the output of the <code>encodePrivateKey()</code>
179    * method of an RSA keypair codec object (an instance implementing
180    * {@link IKeyPairCodec} for RSA keys, and re-constructs an instance of this
181    * object.
182    * 
183    * @param k the contents of a previously encoded instance of this object.
184    * @throws ArrayIndexOutOfBoundsException if there is not enough bytes, in
185    *           <code>k</code>, to represent a valid encoding of an instance
186    *           of this object.
187    * @throws IllegalArgumentException if the byte sequence does not represent a
188    *           valid encoding of an instance of this object.
189    */
190   public static GnuRSAPrivateKey valueOf(final byte[] k)
191   {
192     // try RAW codec
193     if (k[0] == Registry.MAGIC_RAW_RSA_PRIVATE_KEY[0])
194       try
195         {
196           return (GnuRSAPrivateKey) new RSAKeyPairRawCodec().decodePrivateKey(k);
197         }
198       catch (IllegalArgumentException ignored)
199         {
200         }
201
202     // try PKCS#8 codec
203     return (GnuRSAPrivateKey) new RSAKeyPairPKCS8Codec().decodePrivateKey(k);
204   }
205
206   // Instance methods
207   // -------------------------------------------------------------------------
208
209   public BigInteger getPrimeP()
210   {
211     return p;
212   }
213
214   public BigInteger getPrimeQ()
215   {
216     return q;
217   }
218
219   public BigInteger getPrimeExponentP()
220   {
221     return dP;
222   }
223
224   public BigInteger getPrimeExponentQ()
225   {
226     return dQ;
227   }
228
229   public BigInteger getCrtCoefficient()
230   {
231     return qInv;
232   }
233
234   // java.security.interfaces.RSAPrivateKey interface implementation ---------
235
236   public BigInteger getPrivateExponent()
237   {
238     return d;
239   }
240
241   // Other instance methods --------------------------------------------------
242
243   /**
244    * Returns the encoded form of this private key according to the
245    * designated format.
246    *
247    * @param format the desired format identifier of the resulting encoding.
248    * @return the byte sequence encoding this key according to the designated
249    * format.
250    * @throws IllegalArgumentException if the format is not supported.
251    * @see RSAKeyPairRawCodec
252    * @see RSAKeyPairPKCS8Codec
253    */
254   public byte[] getEncoded(int format)
255   {
256     final byte[] result;
257     switch (format)
258       {
259       case IKeyPairCodec.RAW_FORMAT:
260         result = new RSAKeyPairRawCodec().encodePrivateKey(this);
261         break;
262       case IKeyPairCodec.PKCS8_FORMAT:
263         result = new RSAKeyPairPKCS8Codec().encodePrivateKey(this);
264         break;
265       default:
266         throw new IllegalArgumentException("Unsupported encoding format: "
267                                            + format);
268       }
269     return result;
270   }
271
272   /**
273    * <p>Returns <code>true</code> if the designated object is an instance of
274    * this class and has the same RSA parameter values as this one.</p>
275    *
276    * @param obj the other non-null RSA key to compare to.
277    * @return <code>true</code> if the designated object is of the same type
278    * and value as this one.
279    */
280   public boolean equals(final Object obj)
281   {
282     if (obj == null)
283       {
284         return false;
285       }
286     if (obj instanceof RSAPrivateKey)
287       {
288         final RSAPrivateKey that = (RSAPrivateKey) obj;
289         return super.equals(that) && d.equals(that.getPrivateExponent());
290       }
291     if (obj instanceof RSAPrivateCrtKey)
292       {
293         final RSAPrivateCrtKey that = (RSAPrivateCrtKey) obj;
294         return super.equals(that) && p.equals(that.getPrimeP())
295                && q.equals(that.getPrimeQ())
296                && dP.equals(that.getPrimeExponentP())
297                && dQ.equals(that.getPrimeExponentQ())
298                && qInv.equals(that.getCrtCoefficient());
299       }
300     return false;
301   }
302
303   public String toString()
304   {
305     if (str == null)
306       {
307         String ls = SystemProperties.getProperty("line.separator");
308         str = new StringBuilder(this.getClass().getName()).append("(")
309             .append(super.toString()).append(",").append(ls)
310             .append("d=0x").append(DEBUG ? d.toString(16) : "**...*").append(ls)
311             .append("p=0x").append(DEBUG ? p.toString(16) : "**...*").append(ls)
312             .append("q=0x").append(DEBUG ? q.toString(16) : "**...*").append(ls)
313             .append("dP=0x").append(DEBUG ? dP.toString(16) : "**...*").append(ls)
314             .append("dQ=0x").append(DEBUG ? dQ.toString(16) : "**...*").append(ls)
315             .append("qInv=0x").append(DEBUG ? qInv.toString(16) : "**...*").append(ls)
316             .append(")").toString();
317       }
318     return str;
319   }
320 }