summaryrefslogtreecommitdiff
path: root/gnu/java/security/jce/sig/EncodedKeyFactory.java
blob: 9f866fa0787fd88a9a40d81d86ca83cbf7132204 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
/* EncodedKeyFactory.java -- JCE Encoded key factory Adapter
   Copyright (C) 2006, 2010, 2014, 2015  Free Software Foundation, Inc.

This file is part of GNU Classpath.

GNU Classpath is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

GNU Classpath is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Classpath; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version. */


package gnu.java.security.jce.sig;

import gnu.java.security.Configuration;
import gnu.java.security.Registry;
import gnu.java.security.key.dss.DSSPrivateKey;
import gnu.java.security.key.dss.DSSPublicKey;
import gnu.java.security.key.rsa.GnuRSAPrivateKey;
import gnu.java.security.key.rsa.GnuRSAPublicKey;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.InvalidParameterException;
import java.security.Key;
import java.security.KeyFactorySpi;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.DSAPrivateKeySpec;
import java.security.spec.DSAPublicKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateCrtKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.crypto.interfaces.DHPrivateKey;
import javax.crypto.interfaces.DHPublicKey;
import javax.crypto.spec.DHPrivateKeySpec;
import javax.crypto.spec.DHPublicKeySpec;

/**
 * A factory for keys encoded in either the X.509 format (for public keys) or
 * the PKCS#8 format (for private keys).
 */
public class EncodedKeyFactory
    extends KeyFactorySpi
{
  private static final Logger log = Configuration.DEBUG ?
                Logger.getLogger(EncodedKeyFactory.class.getName()) : null;

  private static Object invokeConstructor(String className, Object[] params)
      throws InvalidKeySpecException
  {
    Class<?> clazz = getConcreteClass(className);
    try
      {
        Constructor<?> ctor = getConcreteCtor(clazz);
        Object result = ctor.newInstance(params);
        return result;
      }
    catch (InstantiationException x)
      {
        throw new InvalidKeySpecException(x.getMessage(), x);
      }
    catch (IllegalAccessException x)
      {
        throw new InvalidKeySpecException(x.getMessage(), x);
      }
    catch (InvocationTargetException x)
      {
        throw new InvalidKeySpecException(x.getMessage(), x);
      }
  }

  private static Class<?> getConcreteClass(String className)
      throws InvalidKeySpecException
  {
    try
      {
        Class<?> result = Class.forName(className);
        return result;
      }
    catch (ClassNotFoundException x)
      {
        throw new InvalidKeySpecException(x.getMessage(), x);
      }
  }

  private static Constructor<?> getConcreteCtor(Class<?> clazz)
      throws InvalidKeySpecException
  {
    try
      {
        Constructor<?> result = clazz.getConstructor(new Class[] {int.class,
                                                               BigInteger.class,
                                                               BigInteger.class,
                                                               BigInteger.class,
                                                               BigInteger.class});
        return result;
      }
    catch (NoSuchMethodException x)
      {
        throw new InvalidKeySpecException(x.getMessage(), x);
      }
  }

  private static Object invokeValueOf(String className, byte[] encoded)
      throws InvalidKeySpecException
  {
    Class<?> clazz = getConcreteClass(className);
    try
      {
        Method valueOf = getValueOfMethod(clazz);
        Object result = valueOf.invoke(null, new Object[] { encoded });
        return result;
      }
    catch (IllegalAccessException x)
      {
        throw new InvalidKeySpecException(x.getMessage(), x);
      }
    catch (InvocationTargetException x)
      {
        throw new InvalidKeySpecException(x.getMessage(), x);
      }
  }

  private static Method getValueOfMethod(Class<?> clazz)
      throws InvalidKeySpecException
  {
    try
      {
        Method result = clazz.getMethod("valueOf", new Class[] {byte[].class});
        return result;
      }
    catch (NoSuchMethodException x)
      {
        throw new InvalidKeySpecException(x.getMessage(), x);
      }
  }

  @Override
  protected PublicKey engineGeneratePublic(KeySpec keySpec)
      throws InvalidKeySpecException
  {
    if (Configuration.DEBUG)
      log.entering(this.getClass().getName(), "engineGeneratePublic()", keySpec);
    PublicKey result = null;
    if (keySpec instanceof DSAPublicKeySpec)
      result = decodeDSSPublicKey((DSAPublicKeySpec) keySpec);
    else if (keySpec instanceof RSAPublicKeySpec)
      result = decodeRSAPublicKey((RSAPublicKeySpec) keySpec);
    else if (keySpec instanceof DHPublicKeySpec)
      result = decodeDHPublicKey((DHPublicKeySpec) keySpec);
    else
      {
        if (! (keySpec instanceof X509EncodedKeySpec))
          throw new InvalidKeySpecException("Unsupported key specification");

        byte[] input = ((X509EncodedKeySpec) keySpec).getEncoded();
        boolean ok = false;
        // try DSS
        try
          {
            result = DSSPublicKey.valueOf(input);
            ok = true;
          }
        catch (InvalidParameterException ignored)
          {
            if (Configuration.DEBUG)
              log.log(Level.FINE, "Exception in DSSPublicKey.valueOf(). Ignore",
                      ignored);
          }
        if (! ok) // try RSA
          try
            {
              result = GnuRSAPublicKey.valueOf(input);
              ok = true;
            }
          catch (InvalidParameterException ignored)
            {
              if (Configuration.DEBUG)
                log.log(Level.FINE,
                        "Exception in GnuRSAPublicKey.valueOf(). Ignore",
                        ignored);
            }
          if (! ok) // try DH
            result = decodeDHPublicKey(input);
      }
    if (Configuration.DEBUG)
      log.exiting(this.getClass().getName(), "engineGeneratePublic()", result);
    return result;
  }
  
  @Override
  protected PrivateKey engineGeneratePrivate(KeySpec keySpec)
      throws InvalidKeySpecException
  {
    if (Configuration.DEBUG)
      log.entering(this.getClass().getName(), "engineGeneratePrivate()", keySpec);
    PrivateKey result = null;
    if (keySpec instanceof DSAPrivateKeySpec)
      result = decodeDSSPrivateKey((DSAPrivateKeySpec) keySpec);
    else if (keySpec instanceof RSAPrivateCrtKeySpec)
      result = decodeRSAPrivateKey((RSAPrivateCrtKeySpec) keySpec);
    else if (keySpec instanceof DHPrivateKeySpec)
      result = decodeDHPrivateKey((DHPrivateKeySpec) keySpec);
    else
      {
        if (! (keySpec instanceof PKCS8EncodedKeySpec))
          throw new InvalidKeySpecException("Unsupported key specification");

        byte[] input = ((PKCS8EncodedKeySpec) keySpec).getEncoded();
        boolean ok = false;
        // try DSS
        try
          {
            result = DSSPrivateKey.valueOf(input);
            ok = true;
          }
        catch (InvalidParameterException ignored)
          {
            if (Configuration.DEBUG)
              log.log(Level.FINE, "Exception in DSSPrivateKey.valueOf(). Ignore",
                      ignored);
          }
        if (! ok) // try RSA
          try
            {
              result = GnuRSAPrivateKey.valueOf(input);
              ok = true;
            }
          catch (InvalidParameterException ignored)
            {
              if (Configuration.DEBUG)
                log.log(Level.FINE,
                        "Exception in GnuRSAPrivateKey.valueOf(). Ignore",
                        ignored);
            }
        if (! ok) // try DH
          result = decodeDHPrivateKey(input);
      }
    if (Configuration.DEBUG)
      log.exiting(this.getClass().getName(), "engineGeneratePrivate()", result);
    return result;
  }
  
  @Override
  protected <T extends KeySpec> T engineGetKeySpec(Key key, Class<T> keySpec)
      throws InvalidKeySpecException
  {
    if (key instanceof PublicKey
        && Registry.X509_ENCODING_SORT_NAME.equalsIgnoreCase(key.getFormat())
        && keySpec.isAssignableFrom(X509EncodedKeySpec.class))
      return keySpec.cast(new X509EncodedKeySpec(key.getEncoded()));

    if (key instanceof PrivateKey
        && Registry.PKCS8_ENCODING_SHORT_NAME.equalsIgnoreCase(key.getFormat())
        && keySpec.isAssignableFrom(PKCS8EncodedKeySpec.class))
      return keySpec.cast(new PKCS8EncodedKeySpec(key.getEncoded()));

    throw new InvalidKeySpecException("Unsupported format or invalid key spec class");
  }

  @Override
  protected Key engineTranslateKey(Key key) throws InvalidKeyException
  {
    throw new InvalidKeyException("Key translation not supported");
  }

  /**
   * @param spec an instance of {@link DSAPublicKeySpec} to decode.
   * @return an instance of {@link DSSPublicKey} constructed from the
   *         information in the designated key-specification.
   */
  private static DSSPublicKey decodeDSSPublicKey(DSAPublicKeySpec spec)
  {
    BigInteger p = spec.getP();
    BigInteger q = spec.getQ();
    BigInteger g = spec.getG();
    BigInteger y = spec.getY();
    return new DSSPublicKey(Registry.X509_ENCODING_ID, p, q, g, y);
  }

  /**
   * @param spec an instance of {@link RSAPublicKeySpec} to decode.
   * @return an instance of {@link GnuRSAPublicKey} constructed from the
   *         information in the designated key-specification.
   */
  private static GnuRSAPublicKey decodeRSAPublicKey(RSAPublicKeySpec spec)
  {
    BigInteger n = spec.getModulus();
    BigInteger e = spec.getPublicExponent();
    return new GnuRSAPublicKey(Registry.X509_ENCODING_ID, n, e);
  }

  /**
   * @param spec an instance of {@link DHPublicKeySpec} to decode.
   * @return an instance of a {@link DHPublicKey} constructed from the
   *         information in the designated key-specification.
   * @throws InvalidKeySpecException if no concrete implementation of the
   *           {@link DHPublicKey} interface exists at run-time, or if an
   *           exception occurs during its instantiation.
   */
  private static DHPublicKey decodeDHPublicKey(DHPublicKeySpec spec)
      throws InvalidKeySpecException
  {
    BigInteger p = spec.getP();
    BigInteger g = spec.getG();
    BigInteger y = spec.getY();
    Object[] params = new Object[] {Integer.valueOf(Registry.X509_ENCODING_ID),
                                    null, p, g, y};
    Object obj = invokeConstructor("gnu.javax.crypto.key.dh.GnuDHPublicKey",
                                   params);
    return (DHPublicKey) obj;
  }

  /**
   * @param encoded the bytes to decode.
   * @return an instance of a {@link DHPublicKey} constructed from the
   *         information in the designated key-specification.
   * @throws InvalidKeySpecException if no concrete implementation of the
   *           {@link DHPublicKey} interface exists at run-time, or if an
   *           exception occurs during its instantiation.
   */
  private static DHPublicKey decodeDHPublicKey(byte[] encoded)
      throws InvalidKeySpecException
  {
    Object obj = invokeValueOf("gnu.javax.crypto.key.dh.GnuDHPublicKey",
                               encoded);
    return (DHPublicKey) obj;
  }

  /**
   * @param spec an instance of {@link DSAPrivateKeySpec} to decode.
   * @return an instance of {@link DSSPrivateKey} constructed from the
   *         information in the designated key-specification.
   */
  private static PrivateKey decodeDSSPrivateKey(DSAPrivateKeySpec spec)
  {
    BigInteger p = spec.getP();
    BigInteger q = spec.getQ();
    BigInteger g = spec.getG();
    BigInteger x = spec.getX();
    return new DSSPrivateKey(Registry.PKCS8_ENCODING_ID, p, q, g, x);
  }

  /**
   * @param spec an instance of {@link RSAPrivateCrtKeySpec} to decode.
   * @return an instance of {@link GnuRSAPrivateKey} constructed from the
   *         information in the designated key-specification.
   */
  private static PrivateKey decodeRSAPrivateKey(RSAPrivateCrtKeySpec spec)
  {
    BigInteger n = spec.getModulus();
    BigInteger e = spec.getPublicExponent();
    BigInteger d = spec.getPrivateExponent();
    BigInteger p = spec.getPrimeP();
    BigInteger q = spec.getPrimeQ();
    BigInteger dP = spec.getPrimeExponentP();
    BigInteger dQ = spec.getPrimeExponentQ();
    BigInteger qInv = spec.getCrtCoefficient();
    return new GnuRSAPrivateKey(Registry.PKCS8_ENCODING_ID,
                                n, e, d, p, q, dP, dQ, qInv);
  }

  /**
   * @param spec an instance of {@link DHPrivateKeySpec} to decode.
   * @return an instance of a {@link DHPrivateKey} constructed from the
   *         information in the designated key-specification.
   * @throws InvalidKeySpecException if no concrete implementation of the
   *           {@link DHPrivateKey} interface exists at run-time, or if an
   *           exception occurs during its instantiation.
   */
  private static DHPrivateKey decodeDHPrivateKey(DHPrivateKeySpec spec)
      throws InvalidKeySpecException
  {
    BigInteger p = spec.getP();
    BigInteger g = spec.getG();
    BigInteger x = spec.getX();
    Object[] params = new Object[] {Integer.valueOf(Registry.PKCS8_ENCODING_ID),
                                    null, p, g, x};
    Object obj = invokeConstructor("gnu.javax.crypto.key.dh.GnuDHPrivateKey",
                                   params);
    return (DHPrivateKey) obj;
  }

  /**
   * @param encoded the bytes to decode.
   * @return an instance of a {@link DHPrivateKey} constructed from the
   *         information in the designated key-specification.
   * @throws InvalidKeySpecException if no concrete implementation of the
   *           {@link DHPrivateKey} interface exists at run-time, or if an
   *           exception occurs during its instantiation.
   */
  private static DHPrivateKey decodeDHPrivateKey(byte[] encoded)
      throws InvalidKeySpecException
  {
    Object obj = invokeValueOf("gnu.javax.crypto.key.dh.GnuDHPrivateKey",
                               encoded);
    return (DHPrivateKey) obj;
  }
}