Imported GNU Classpath 0.90
[official-gcc.git] / libjava / classpath / gnu / java / security / sig / rsa / RSA.java
blob7d1707e195deda84decc581d37bc35b3542ee04b
1 /* RSA.java --
2 Copyright (C) 2001, 2002, 2003, 2006 Free Software Foundation, Inc.
4 This file is a part of GNU Classpath.
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.
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.
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
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.
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. */
39 package gnu.java.security.sig.rsa;
41 import gnu.java.security.Properties;
42 import gnu.java.security.util.PRNG;
44 import java.math.BigInteger;
45 import java.security.PrivateKey;
46 import java.security.PublicKey;
47 import java.security.interfaces.RSAPrivateCrtKey;
48 import java.security.interfaces.RSAPrivateKey;
49 import java.security.interfaces.RSAPublicKey;
51 /**
52 * <p>Utility methods related to the RSA algorithm.</p>
54 * <p>References:</p>
55 * <ol>
56 * <li><a href="http://www.cosic.esat.kuleuven.ac.be/nessie/workshop/submissions/rsa-pss.zip">
57 * RSA-PSS Signature Scheme with Appendix, part B.</a><br>
58 * Primitive specification and supporting documentation.<br>
59 * Jakob Jonsson and Burt Kaliski.</li>
61 * <li><a href="http://www.ietf.org/rfc/rfc3447.txt">Public-Key Cryptography
62 * Standards (PKCS) #1:</a><br>
63 * RSA Cryptography Specifications Version 2.1.<br>
64 * Jakob Jonsson and Burt Kaliski.</li>
66 * <li><a href="http://crypto.stanford.edu/~dabo/abstracts/ssl-timing.html">
67 * Remote timing attacks are practical</a><br>
68 * D. Boneh and D. Brumley.</li>
69 * </ol>
71 public class RSA
74 // Constants and variables
75 // -------------------------------------------------------------------------
77 private static final BigInteger ZERO = BigInteger.ZERO;
79 private static final BigInteger ONE = BigInteger.ONE;
81 /** Our default source of randomness. */
82 private static final PRNG prng = PRNG.getInstance();
84 // Constructor(s)
85 // -------------------------------------------------------------------------
87 /** Trivial private constructor to enforce Singleton pattern. */
88 private RSA()
90 super();
93 // Class methods
94 // -------------------------------------------------------------------------
96 // Signature and verification methods --------------------------------------
98 /**
99 * <p>An implementation of the <b>RSASP</b> method: Assuming that the
100 * designated RSA private key is a valid one, this method computes a
101 * <i>signature representative</i> for a designated <i>message
102 * representative</i> signed by the holder of the designated RSA private
103 * key.<p>
105 * @param K the RSA private key.
106 * @param m the <i>message representative</i>: an integer between
107 * <code>0</code> and <code>n - 1</code>, where <code>n</code> is the RSA
108 * <i>modulus</i>.
109 * @return the <i>signature representative</i>, an integer between
110 * <code>0</code> and <code>n - 1</code>, where <code>n</code> is the RSA
111 * <i>modulus</i>.
112 * @throws ClassCastException if <code>K</code> is not an RSA one.
113 * @throws IllegalArgumentException if <code>m</code> (the <i>message
114 * representative</i>) is out of range.
116 public static final BigInteger sign(final PrivateKey K, final BigInteger m)
120 return RSADP((RSAPrivateKey) K, m);
122 catch (IllegalArgumentException x)
124 throw new IllegalArgumentException(
125 "message representative out of range");
130 * <p>An implementation of the <b>RSAVP</b> method: Assuming that the
131 * designated RSA public key is a valid one, this method computes a
132 * <i>message representative</i> for the designated <i>signature
133 * representative</i> generated by an RSA private key, for a message
134 * intended for the holder of the designated RSA public key.</p>
136 * @param K the RSA public key.
137 * @param s the <i>signature representative</i>, an integer between
138 * <code>0</code> and <code>n - 1</code>, where <code>n</code> is the RSA
139 * <i>modulus</i>.
140 * @return a <i>message representative</i>: an integer between <code>0</code>
141 * and <code>n - 1</code>, where <code>n</code> is the RSA <i>modulus</i>.
142 * @throws ClassCastException if <code>K</code> is not an RSA one.
143 * @throws IllegalArgumentException if <code>s</code> (the <i>signature
144 * representative</i>) is out of range.
146 public static final BigInteger verify(final PublicKey K, final BigInteger s)
150 return RSAEP((RSAPublicKey) K, s);
152 catch (IllegalArgumentException x)
154 throw new IllegalArgumentException(
155 "signature representative out of range");
159 // Encryption and decryption methods ---------------------------------------
162 * <p>An implementation of the <code>RSAEP</code> algorithm.</p>
164 * @param K the recipient's RSA public key.
165 * @param m the message representative as an MPI.
166 * @return the resulting MPI --an MPI between <code>0</code> and
167 * <code>n - 1</code> (<code>n</code> being the public shared modulus)-- that
168 * will eventually be padded with an appropriate framing/padding scheme.
169 * @throws ClassCastException if <code>K</code> is not an RSA one.
170 * @throws IllegalArgumentException if <code>m</code>, the message
171 * representative is not between <code>0</code> and <code>n - 1</code>
172 * (<code>n</code> being the public shared modulus).
174 public static final BigInteger encrypt(final PublicKey K, final BigInteger m)
178 return RSAEP((RSAPublicKey) K, m);
180 catch (IllegalArgumentException x)
182 throw new IllegalArgumentException(
183 "message representative out of range");
188 * <p>An implementation of the <code>RSADP</code> algorithm.</p>
190 * @param K the recipient's RSA private key.
191 * @param c the ciphertext representative as an MPI.
192 * @return the message representative, an MPI between <code>0</code> and
193 * <code>n - 1</code> (<code>n</code> being the shared public modulus).
194 * @throws ClassCastException if <code>K</code> is not an RSA one.
195 * @throws IllegalArgumentException if <code>c</code>, the ciphertext
196 * representative is not between <code>0</code> and <code>n - 1</code>
197 * (<code>n</code> being the shared public modulus).
199 public static final BigInteger decrypt(final PrivateKey K, final BigInteger c)
203 return RSADP((RSAPrivateKey) K, c);
205 catch (IllegalArgumentException x)
207 throw new IllegalArgumentException(
208 "ciphertext representative out of range");
212 // Conversion methods ------------------------------------------------------
215 * <p>Converts a <i>multi-precision integer</i> (MPI) <code>s</code> into an
216 * octet sequence of length <code>k</code>.</p>
218 * @param s the multi-precision integer to convert.
219 * @param k the length of the output.
220 * @return the result of the transform.
221 * @exception IllegalArgumentException if the length in octets of meaningful
222 * bytes of <code>s</code> is greater than <code>k</code>.
224 public static final byte[] I2OSP(final BigInteger s, final int k)
226 byte[] result = s.toByteArray();
227 if (result.length < k)
229 final byte[] newResult = new byte[k];
230 System.arraycopy(result, 0, newResult, k - result.length, result.length);
231 result = newResult;
233 else if (result.length > k)
234 { // leftmost extra bytes should all be 0
235 final int limit = result.length - k;
236 for (int i = 0; i < limit; i++)
238 if (result[i] != 0x00)
240 throw new IllegalArgumentException("integer too large");
243 final byte[] newResult = new byte[k];
244 System.arraycopy(result, limit, newResult, 0, k);
245 result = newResult;
247 return result;
250 // helper methods ----------------------------------------------------------
252 private static final BigInteger RSAEP(final RSAPublicKey K, final BigInteger m)
254 // 1. If the representative m is not between 0 and n - 1, output
255 // "representative out of range" and stop.
256 final BigInteger n = K.getModulus();
257 if (m.compareTo(ZERO) < 0 || m.compareTo(n.subtract(ONE)) > 0)
259 throw new IllegalArgumentException();
261 // 2. Let c = m^e mod n.
262 final BigInteger e = K.getPublicExponent();
263 final BigInteger result = m.modPow(e, n);
264 // 3. Output c.
265 return result;
268 private static final BigInteger RSADP(final RSAPrivateKey K, BigInteger c)
270 // 1. If the representative c is not between 0 and n - 1, output
271 // "representative out of range" and stop.
272 final BigInteger n = K.getModulus();
273 if (c.compareTo(ZERO) < 0 || c.compareTo(n.subtract(ONE)) > 0)
275 throw new IllegalArgumentException();
278 // 2. The representative m is computed as follows.
279 BigInteger result;
280 if (!(K instanceof RSAPrivateCrtKey))
282 // a. If the first form (n, d) of K is used, let m = c^d mod n.
283 final BigInteger d = K.getPrivateExponent();
284 result = c.modPow(d, n);
286 else
288 // from [3] p.13 --see class docs:
289 // The RSA blinding operation calculates x = (r^e) * g mod n before
290 // decryption, where r is random, e is the RSA encryption exponent, and
291 // g is the ciphertext to be decrypted. x is then decrypted as normal,
292 // followed by division by r, i.e. (x^e) / r mod n. Since r is random,
293 // x is random and timing the decryption should not reveal information
294 // about the key. Note that r should be a new random number for every
295 // decryption.
296 final boolean rsaBlinding = Properties.doRSABlinding();
297 BigInteger r = null;
298 BigInteger e = null;
299 if (rsaBlinding)
300 { // pre-decryption
301 r = newR(n);
302 e = ((RSAPrivateCrtKey) K).getPublicExponent();
303 final BigInteger x = r.modPow(e, n).multiply(c).mod(n);
304 c = x;
307 // b. If the second form (p, q, dP, dQ, qInv) and (r_i, d_i, t_i)
308 // of K is used, proceed as follows:
309 final BigInteger p = ((RSAPrivateCrtKey) K).getPrimeP();
310 final BigInteger q = ((RSAPrivateCrtKey) K).getPrimeQ();
311 final BigInteger dP = ((RSAPrivateCrtKey) K).getPrimeExponentP();
312 final BigInteger dQ = ((RSAPrivateCrtKey) K).getPrimeExponentQ();
313 final BigInteger qInv = ((RSAPrivateCrtKey) K).getCrtCoefficient();
315 // i. Let m_1 = c^dP mod p and m_2 = c^dQ mod q.
316 final BigInteger m_1 = c.modPow(dP, p);
317 final BigInteger m_2 = c.modPow(dQ, q);
318 // ii. If u > 2, let m_i = c^(d_i) mod r_i, i = 3, ..., u.
319 // iii. Let h = (m_1 - m_2) * qInv mod p.
320 final BigInteger h = m_1.subtract(m_2).multiply(qInv).mod(p);
321 // iv. Let m = m_2 + q * h.
322 result = m_2.add(q.multiply(h));
324 if (rsaBlinding)
325 { // post-decryption
326 result = result.multiply(r.modInverse(n)).mod(n);
330 // 3. Output m
331 return result;
335 * <p>Returns a random MPI with a random bit-length of the form <code>8b</code>,
336 * where <code>b</code> is in the range <code>[32..64]</code>.</p>
338 * @return a random MPI whose length in bytes is between 32 and 64 inclusive.
340 private static final BigInteger newR(final BigInteger N)
342 final int upper = (N.bitLength() + 7) / 8;
343 final int lower = upper / 2;
344 final byte[] bl = new byte[1];
345 int b;
348 prng.nextBytes(bl);
349 b = bl[0] & 0xFF;
351 while (b < lower || b > upper);
352 final byte[] buffer = new byte[b]; // 256-bit MPI
353 prng.nextBytes(buffer);
354 return new BigInteger(1, buffer);