1 /*
2  * Copyright (c) 1996, 2015, Oracle and/or its affiliates. All rights reserved.
3  * Copyright (C) 2014 The Android Open Source Project
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This code is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License version 2 only, as
8  * published by the Free Software Foundation.  Oracle designates this
9  * particular file as subject to the "Classpath" exception as provided
10  * by Oracle in the LICENSE file that accompanied this code.
11  *
12  * This code is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15  * version 2 for more details (a copy is included in the LICENSE file that
16  * accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License version
19  * 2 along with this work; if not, write to the Free Software Foundation,
20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21  *
22  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
23  * or visit www.oracle.com if you need additional information or have any
24  * questions.
25  */
26 
27 package java.security;
28 
29 import java.security.spec.AlgorithmParameterSpec;
30 import java.util.*;
31 import java.util.concurrent.ConcurrentHashMap;
32 import java.io.*;
33 import java.security.cert.Certificate;
34 import java.security.cert.X509Certificate;
35 
36 import java.nio.ByteBuffer;
37 
38 import java.security.Provider.Service;
39 
40 import javax.crypto.Cipher;
41 import javax.crypto.CipherSpi;
42 import javax.crypto.IllegalBlockSizeException;
43 import javax.crypto.BadPaddingException;
44 import javax.crypto.NoSuchPaddingException;
45 import sun.security.jca.*;
46 import sun.security.jca.GetInstance.Instance;
47 
48 /**
49  * The Signature class is used to provide applications the functionality
50  * of a digital signature algorithm. Digital signatures are used for
51  * authentication and integrity assurance of digital data.
52  *
53  * <p> The signature algorithm can be, among others, the NIST standard
54  * DSA, using DSA and SHA-1. The DSA algorithm using the
55  * SHA-1 message digest algorithm can be specified as {@code SHA1withDSA}.
56  * In the case of RSA, there are multiple choices for the message digest
57  * algorithm, so the signing algorithm could be specified as, for example,
58  * {@code MD2withRSA}, {@code MD5withRSA}, or {@code SHA1withRSA}.
59  * The algorithm name must be specified, as there is no default.
60  *
61  * <p> A Signature object can be used to generate and verify digital
62  * signatures.
63  *
64  * <p> There are three phases to the use of a Signature object for
65  * either signing data or verifying a signature:<ol>
66  *
67  * <li>Initialization, with either
68  *
69  *     <ul>
70  *
71  *     <li>a public key, which initializes the signature for
72  *     verification (see {@link #initVerify(PublicKey) initVerify}), or
73  *
74  *     <li>a private key (and optionally a Secure Random Number Generator),
75  *     which initializes the signature for signing
76  *     (see {@link #initSign(PrivateKey)}
77  *     and {@link #initSign(PrivateKey, SecureRandom)}).
78  *
79  *     </ul>
80  *
81  * <li>Updating
82  *
83  * <p>Depending on the type of initialization, this will update the
84  * bytes to be signed or verified. See the
85  * {@link #update(byte) update} methods.
86  *
87  * <li>Signing or Verifying a signature on all updated bytes. See the
88  * {@link #sign() sign} methods and the {@link #verify(byte[]) verify}
89  * method.
90  *
91  * </ol>
92  *
93  * <p>Note that this class is abstract and extends from
94  * {@code SignatureSpi} for historical reasons.
95  * Application developers should only take notice of the methods defined in
96  * this {@code Signature} class; all the methods in
97  * the superclass are intended for cryptographic service providers who wish to
98  * supply their own implementations of digital signature algorithms.
99  *
100  * <p> Android provides the following {@code Signature} algorithms:
101  * <table>
102  *   <thead>
103  *     <tr>
104  *       <th>Algorithm</th>
105  *       <th>Supported API Levels</th>
106  *     </tr>
107  *   </thead>
108  *   <tbody>
109  *     <tr>
110  *       <td>DSA</td>
111  *       <td>1+</td>
112  *     </tr>
113  *     <tr>
114  *       <td>DSAwithSHA1</td>
115  *       <td>1+</td>
116  *     </tr>
117  *     <tr class="deprecated">
118  *       <td>DSS</td>
119  *       <td>1-19</td>
120  *     </tr>
121  *     <tr>
122  *       <td>ECDSA</td>
123  *       <td>11+</td>
124  *     </tr>
125  *     <tr>
126  *       <td>ECDSAwithSHA1</td>
127  *       <td>11+</td>
128  *     </tr>
129  *     <tr>
130  *       <td>Ed25519</td>
131  *       <td>33+</td>
132  *     </tr>
133  *     <tr class="deprecated">
134  *       <td>MD2withRSA</td>
135  *       <td>1-3</td>
136  *     </tr>
137  *     <tr class="deprecated">
138  *       <td>MD4withRSA</td>
139  *       <td>1-8</td>
140  *     </tr>
141  *     <tr>
142  *       <td>MD5withRSA</td>
143  *       <td>1+</td>
144  *     </tr>
145  *     <tr class="deprecated">
146  *       <td>MD5withRSA/ISO9796-2</td>
147  *       <td>1-8</td>
148  *     </tr>
149  *     <tr>
150  *       <td>NONEwithDSA</td>
151  *       <td>1+</td>
152  *     </tr>
153  *     <tr>
154  *       <td>NONEwithECDSA</td>
155  *       <td>11+</td>
156  *     </tr>
157  *     <tr>
158  *       <td>NONEwithRSA</td>
159  *       <td>17+</td>
160  *     </tr>
161  *     <tr class="deprecated">
162  *       <td>RSASSA-PSS</td>
163  *       <td>1-8</td>
164  *     </tr>
165  *     <tr>
166  *       <td>SHA1withDSA</td>
167  *       <td>1+</td>
168  *     </tr>
169  *     <tr>
170  *       <td>SHA1withECDSA</td>
171  *       <td>11+</td>
172  *     </tr>
173  *     <tr>
174  *       <td>SHA1withRSA</td>
175  *       <td>1+</td>
176  *     </tr>
177  *     <tr class="deprecated">
178  *       <td>SHA1withRSA/ISO9796-2</td>
179  *       <td>1-8</td>
180  *     </tr>
181  *     <tr>
182  *       <td>SHA1withRSA/PSS</td>
183  *       <td>23+</td>
184  *     </tr>
185  *     <tr>
186  *       <td>SHA224withDSA</td>
187  *       <td>20+</td>
188  *     </tr>
189  *     <tr>
190  *       <td>SHA224withECDSA</td>
191  *       <td>20+</td>
192  *     </tr>
193  *     <tr>
194  *       <td>SHA224withRSA</td>
195  *       <td>20+</td>
196  *     </tr>
197  *     <tr>
198  *       <td>SHA224withRSA/PSS</td>
199  *       <td>23+</td>
200  *     </tr>
201  *     <tr>
202  *       <td>SHA256withDSA</td>
203  *       <td>1+</td>
204  *     </tr>
205  *     <tr>
206  *       <td>SHA256withECDSA</td>
207  *       <td>11+</td>
208  *     </tr>
209  *     <tr>
210  *       <td>SHA256withRSA</td>
211  *       <td>1+</td>
212  *     </tr>
213  *     <tr>
214  *       <td>SHA256withRSA/PSS</td>
215  *       <td>23+</td>
216  *     </tr>
217  *     <tr>
218  *       <td>SHA384withECDSA</td>
219  *       <td>11+</td>
220  *     </tr>
221  *     <tr>
222  *       <td>SHA384withRSA</td>
223  *       <td>1+</td>
224  *     </tr>
225  *     <tr>
226  *       <td>SHA384withRSA/PSS</td>
227  *       <td>23+</td>
228  *     </tr>
229  *     <tr>
230  *       <td>SHA512withECDSA</td>
231  *       <td>11+</td>
232  *     </tr>
233  *     <tr>
234  *       <td>SHA512withRSA</td>
235  *       <td>1+</td>
236  *     </tr>
237  *     <tr>
238  *       <td>SHA512withRSA/PSS</td>
239  *       <td>23+</td>
240  *     </tr>
241  *   </tbody>
242  * </table>
243  *
244  * These algorithms are described in the <a href=
245  * "{@docRoot}/../technotes/guides/security/StandardNames.html#Signature">
246  * Signature section</a> of the
247  * Java Cryptography Architecture Standard Algorithm Name Documentation.
248  *
249  * @author Benjamin Renaud
250  *
251  */
252 
253 public abstract class Signature extends SignatureSpi {
254 
255     // BEGIN Android-removed: this debugging mechanism is not supported in Android.
256     /*
257     private static final Debug debug =
258                         Debug.getInstance("jca", "Signature");
259 
260     private static final Debug pdebug =
261                         Debug.getInstance("provider", "Provider");
262     private static final boolean skipDebug =
263         Debug.isOn("engine=") && !Debug.isOn("signature");
264     // END Android-removed: this debugging mechanism is not supported in Android.
265     */
266 
267     /*
268      * The algorithm for this signature object.
269      * This value is used to map an OID to the particular algorithm.
270      * The mapping is done in AlgorithmObject.algOID(String algorithm)
271      */
272     private String algorithm;
273 
274     // The provider
275     Provider provider;
276 
277     /**
278      * Possible {@link #state} value, signifying that
279      * this signature object has not yet been initialized.
280      */
281     protected final static int UNINITIALIZED = 0;
282 
283     /**
284      * Possible {@link #state} value, signifying that
285      * this signature object has been initialized for signing.
286      */
287     protected final static int SIGN = 2;
288 
289     /**
290      * Possible {@link #state} value, signifying that
291      * this signature object has been initialized for verification.
292      */
293     protected final static int VERIFY = 3;
294 
295     /**
296      * Current state of this signature object.
297      */
298     protected int state = UNINITIALIZED;
299 
300     /**
301      * Creates a Signature object for the specified algorithm.
302      *
303      * @param algorithm the standard string name of the algorithm.
304      * See the Signature section in the <a href=
305      * "{@docRoot}/../technotes/guides/security/StandardNames.html#Signature">
306      * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
307      * for information about standard algorithm names.
308      */
Signature(String algorithm)309     protected Signature(String algorithm) {
310         this.algorithm = algorithm;
311     }
312 
313     // name of the special signature alg
314     private final static String RSA_SIGNATURE = "NONEwithRSA";
315 
316     // name of the equivalent cipher alg
317     private final static String RSA_CIPHER = "RSA/ECB/PKCS1Padding";
318 
319     // all the services we need to lookup for compatibility with Cipher
320     private final static List<ServiceId> rsaIds = Arrays.asList(
321         new ServiceId[] {
322             new ServiceId("Signature", "NONEwithRSA"),
323             new ServiceId("Cipher", "RSA/ECB/PKCS1Padding"),
324             new ServiceId("Cipher", "RSA/ECB"),
325             new ServiceId("Cipher", "RSA//PKCS1Padding"),
326             new ServiceId("Cipher", "RSA"),
327         }
328     );
329 
330     /**
331      * Returns a Signature object that implements the specified signature
332      * algorithm.
333      *
334      * <p> This method traverses the list of registered security Providers,
335      * starting with the most preferred Provider.
336      * A new Signature object encapsulating the
337      * SignatureSpi implementation from the first
338      * Provider that supports the specified algorithm is returned.
339      *
340      * <p> Note that the list of registered providers may be retrieved via
341      * the {@link Security#getProviders() Security.getProviders()} method.
342      *
343      * @param algorithm the standard name of the algorithm requested.
344      * See the Signature section in the <a href=
345      * "{@docRoot}/../technotes/guides/security/StandardNames.html#Signature">
346      * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
347      * for information about standard algorithm names.
348      *
349      * @return the new Signature object.
350      *
351      * @exception NoSuchAlgorithmException if no Provider supports a
352      *          Signature implementation for the
353      *          specified algorithm.
354      *
355      * @see Provider
356      */
getInstance(String algorithm)357     public static Signature getInstance(String algorithm)
358             throws NoSuchAlgorithmException {
359         List<Service> list;
360         if (algorithm.equalsIgnoreCase(RSA_SIGNATURE)) {
361             list = GetInstance.getServices(rsaIds);
362         } else {
363             list = GetInstance.getServices("Signature", algorithm);
364         }
365         Iterator<Service> t = list.iterator();
366         if (t.hasNext() == false) {
367             throw new NoSuchAlgorithmException
368                 (algorithm + " Signature not available");
369         }
370         // try services until we find an Spi or a working Signature subclass
371         NoSuchAlgorithmException failure;
372         do {
373             Service s = t.next();
374             if (isSpi(s)) {
375                 // Android-changed: Delegate constructor only takes algorithm.
376                 // return new Delegate(s, t, algorithm);
377                 return new Delegate(algorithm);
378             } else {
379                 // must be a subclass of Signature, disable dynamic selection
380                 try {
381                     Instance instance =
382                         GetInstance.getInstance(s, SignatureSpi.class);
383                     return getInstance(instance, algorithm);
384                 } catch (NoSuchAlgorithmException e) {
385                     failure = e;
386                 }
387             }
388         } while (t.hasNext());
389         throw failure;
390     }
391 
getInstance(Instance instance, String algorithm)392     private static Signature getInstance(Instance instance, String algorithm) {
393         Signature sig;
394         if (instance.impl instanceof Signature) {
395             sig = (Signature)instance.impl;
396             sig.algorithm = algorithm;
397         } else {
398             SignatureSpi spi = (SignatureSpi)instance.impl;
399             sig = new Delegate(spi, algorithm);
400         }
401         sig.provider = instance.provider;
402         return sig;
403     }
404 
405     private final static Map<String,Boolean> signatureInfo;
406 
407     static {
408         signatureInfo = new ConcurrentHashMap<String,Boolean>();
409         Boolean TRUE = Boolean.TRUE;
410         // pre-initialize with values for our SignatureSpi implementations
411         signatureInfo.put("sun.security.provider.DSA$RawDSA", TRUE);
412         signatureInfo.put("sun.security.provider.DSA$SHA1withDSA", TRUE);
413         signatureInfo.put("sun.security.rsa.RSASignature$MD2withRSA", TRUE);
414         signatureInfo.put("sun.security.rsa.RSASignature$MD5withRSA", TRUE);
415         signatureInfo.put("sun.security.rsa.RSASignature$SHA1withRSA", TRUE);
416         signatureInfo.put("sun.security.rsa.RSASignature$SHA256withRSA", TRUE);
417         signatureInfo.put("sun.security.rsa.RSASignature$SHA384withRSA", TRUE);
418         signatureInfo.put("sun.security.rsa.RSASignature$SHA512withRSA", TRUE);
419         signatureInfo.put("com.sun.net.ssl.internal.ssl.RSASignature", TRUE);
420         signatureInfo.put("sun.security.pkcs11.P11Signature", TRUE);
421     }
422 
isSpi(Service s)423     private static boolean isSpi(Service s) {
424         if (s.getType().equals("Cipher")) {
425             // must be a CipherSpi, which we can wrap with the CipherAdapter
426             return true;
427         }
428         String className = s.getClassName();
429         Boolean result = signatureInfo.get(className);
430         if (result == null) {
431             try {
432                 Object instance = s.newInstance(null);
433                 // Signature extends SignatureSpi
434                 // so it is a "real" Spi if it is an
435                 // instance of SignatureSpi but not Signature
436                 boolean r = (instance instanceof SignatureSpi)
437                                 && (instance instanceof Signature == false);
438                 // BEGIN Android-removed: this debugging mechanism is not supported in Android.
439                 /*
440                 if ((debug != null) && (r == false)) {
441                     debug.println("Not a SignatureSpi " + className);
442                     debug.println("Delayed provider selection may not be "
443                         + "available for algorithm " + s.getAlgorithm());
444                 }
445                 */
446                 // END Android-removed: this debugging mechanism is not supported in Android.
447                 result = Boolean.valueOf(r);
448                 signatureInfo.put(className, result);
449             } catch (Exception e) {
450                 // something is wrong, assume not an SPI
451                 return false;
452             }
453         }
454         return result.booleanValue();
455     }
456 
457     /**
458      * Returns a Signature object that implements the specified signature
459      * algorithm.
460      *
461      * <p> A new Signature object encapsulating the
462      * SignatureSpi implementation from the specified provider
463      * is returned.  The specified provider must be registered
464      * in the security provider list.
465      *
466      * <p> Note that the list of registered providers may be retrieved via
467      * the {@link Security#getProviders() Security.getProviders()} method.
468      *
469      * @param algorithm the name of the algorithm requested.
470      * See the Signature section in the <a href=
471      * "{@docRoot}/../technotes/guides/security/StandardNames.html#Signature">
472      * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
473      * for information about standard algorithm names.
474      *
475      * @param provider the name of the provider.
476      *
477      * @return the new Signature object.
478      *
479      * @exception NoSuchAlgorithmException if a SignatureSpi
480      *          implementation for the specified algorithm is not
481      *          available from the specified provider.
482      *
483      * @exception NoSuchProviderException if the specified provider is not
484      *          registered in the security provider list.
485      *
486      * @exception IllegalArgumentException if the provider name is null
487      *          or empty.
488      *
489      * @see Provider
490      */
getInstance(String algorithm, String provider)491     public static Signature getInstance(String algorithm, String provider)
492             throws NoSuchAlgorithmException, NoSuchProviderException {
493         if (algorithm.equalsIgnoreCase(RSA_SIGNATURE)) {
494             // exception compatibility with existing code
495             if ((provider == null) || (provider.length() == 0)) {
496                 throw new IllegalArgumentException("missing provider");
497             }
498             Provider p = Security.getProvider(provider);
499             if (p == null) {
500                 throw new NoSuchProviderException
501                     ("no such provider: " + provider);
502             }
503             return getInstanceRSA(p);
504         }
505         // Android-added: Check for Bouncy Castle deprecation
506         Providers.checkBouncyCastleDeprecation(provider, "Signature", algorithm);
507         Instance instance = GetInstance.getInstance
508                 ("Signature", SignatureSpi.class, algorithm, provider);
509         return getInstance(instance, algorithm);
510     }
511 
512     /**
513      * Returns a Signature object that implements the specified
514      * signature algorithm.
515      *
516      * <p> A new Signature object encapsulating the
517      * SignatureSpi implementation from the specified Provider
518      * object is returned.  Note that the specified Provider object
519      * does not have to be registered in the provider list.
520      *
521      * @param algorithm the name of the algorithm requested.
522      * See the Signature section in the <a href=
523      * "{@docRoot}/../technotes/guides/security/StandardNames.html#Signature">
524      * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
525      * for information about standard algorithm names.
526      *
527      * @param provider the provider.
528      *
529      * @return the new Signature object.
530      *
531      * @exception NoSuchAlgorithmException if a SignatureSpi
532      *          implementation for the specified algorithm is not available
533      *          from the specified Provider object.
534      *
535      * @exception IllegalArgumentException if the provider is null.
536      *
537      * @see Provider
538      *
539      * @since 1.4
540      */
getInstance(String algorithm, Provider provider)541     public static Signature getInstance(String algorithm, Provider provider)
542             throws NoSuchAlgorithmException {
543         if (algorithm.equalsIgnoreCase(RSA_SIGNATURE)) {
544             // exception compatibility with existing code
545             if (provider == null) {
546                 throw new IllegalArgumentException("missing provider");
547             }
548             return getInstanceRSA(provider);
549         }
550         // Android-added: Check for Bouncy Castle deprecation
551         Providers.checkBouncyCastleDeprecation(provider, "Signature", algorithm);
552         Instance instance = GetInstance.getInstance
553                 ("Signature", SignatureSpi.class, algorithm, provider);
554         return getInstance(instance, algorithm);
555     }
556 
557     // return an implementation for NONEwithRSA, which is a special case
558     // because of the Cipher.RSA/ECB/PKCS1Padding compatibility wrapper
getInstanceRSA(Provider p)559     private static Signature getInstanceRSA(Provider p)
560             throws NoSuchAlgorithmException {
561         // try Signature first
562         Service s = p.getService("Signature", RSA_SIGNATURE);
563         if (s != null) {
564             Instance instance = GetInstance.getInstance(s, SignatureSpi.class);
565             return getInstance(instance, RSA_SIGNATURE);
566         }
567         // check Cipher
568         try {
569             Cipher c = Cipher.getInstance(RSA_CIPHER, p);
570             return new Delegate(new CipherAdapter(c), RSA_SIGNATURE);
571         } catch (GeneralSecurityException e) {
572             // throw Signature style exception message to avoid confusion,
573             // but append Cipher exception as cause
574             throw new NoSuchAlgorithmException("no such algorithm: "
575                 + RSA_SIGNATURE + " for provider " + p.getName(), e);
576         }
577     }
578 
579     /**
580      * Returns the provider of this signature object.
581      *
582      * @return the provider of this signature object
583      */
getProvider()584     public final Provider getProvider() {
585         chooseFirstProvider();
586         return this.provider;
587     }
588 
chooseFirstProvider()589     void chooseFirstProvider() {
590         // empty, overridden in Delegate
591     }
592 
593     /**
594      * Initializes this object for verification. If this method is called
595      * again with a different argument, it negates the effect
596      * of this call.
597      *
598      * @param publicKey the public key of the identity whose signature is
599      * going to be verified.
600      *
601      * @exception InvalidKeyException if the key is invalid.
602      */
initVerify(PublicKey publicKey)603     public final void initVerify(PublicKey publicKey)
604             throws InvalidKeyException {
605         engineInitVerify(publicKey);
606         state = VERIFY;
607 
608         // BEGIN Android-removed: this debugging mechanism is not supported in Android.
609         /*
610         if (!skipDebug && pdebug != null) {
611             pdebug.println("Signature." + algorithm +
612                 " verification algorithm from: " + this.provider.getName());
613         }
614         */
615         // END Android-removed: this debugging mechanism is not supported in Android.
616     }
617 
618     /**
619      * Initializes this object for verification, using the public key from
620      * the given certificate.
621      * <p>If the certificate is of type X.509 and has a <i>key usage</i>
622      * extension field marked as critical, and the value of the <i>key usage</i>
623      * extension field implies that the public key in
624      * the certificate and its corresponding private key are not
625      * supposed to be used for digital signatures, an
626      * {@code InvalidKeyException} is thrown.
627      *
628      * @param certificate the certificate of the identity whose signature is
629      * going to be verified.
630      *
631      * @exception InvalidKeyException  if the public key in the certificate
632      * is not encoded properly or does not include required  parameter
633      * information or cannot be used for digital signature purposes.
634      * @since 1.3
635      */
initVerify(Certificate certificate)636     public final void initVerify(Certificate certificate)
637             throws InvalidKeyException {
638         // If the certificate is of type X509Certificate,
639         // we should check whether it has a Key Usage
640         // extension marked as critical.
641         if (certificate instanceof java.security.cert.X509Certificate) {
642             // Check whether the cert has a key usage extension
643             // marked as a critical extension.
644             // The OID for KeyUsage extension is 2.5.29.15.
645             X509Certificate cert = (X509Certificate)certificate;
646             Set<String> critSet = cert.getCriticalExtensionOIDs();
647 
648             if (critSet != null && !critSet.isEmpty()
649                 && critSet.contains("2.5.29.15")) {
650                 boolean[] keyUsageInfo = cert.getKeyUsage();
651                 // keyUsageInfo[0] is for digitalSignature.
652                 if ((keyUsageInfo != null) && (keyUsageInfo[0] == false))
653                     throw new InvalidKeyException("Wrong key usage");
654             }
655         }
656 
657         PublicKey publicKey = certificate.getPublicKey();
658         engineInitVerify(publicKey);
659         state = VERIFY;
660 
661         // BEGIN Android-removed: this debugging mechanism is not supported in Android.
662         /*
663         if (!skipDebug && pdebug != null) {
664             pdebug.println("Signature." + algorithm +
665                 " verification algorithm from: " + this.provider.getName());
666         }
667         */
668         // END Android-removed: this debugging mechanism is not supported in Android.
669     }
670 
671     /**
672      * Initialize this object for signing. If this method is called
673      * again with a different argument, it negates the effect
674      * of this call.
675      *
676      * @param privateKey the private key of the identity whose signature
677      * is going to be generated.
678      *
679      * @exception InvalidKeyException if the key is invalid.
680      */
initSign(PrivateKey privateKey)681     public final void initSign(PrivateKey privateKey)
682             throws InvalidKeyException {
683         engineInitSign(privateKey);
684         state = SIGN;
685 
686         // BEGIN Android-removed: this debugging mechanism is not supported in Android.
687         /*
688         if (!skipDebug && pdebug != null) {
689             pdebug.println("Signature." + algorithm +
690                 " signing algorithm from: " + this.provider.getName());
691         }
692         */
693         // END Android-removed: this debugging mechanism is not supported in Android.
694     }
695 
696     /**
697      * Initialize this object for signing. If this method is called
698      * again with a different argument, it negates the effect
699      * of this call.
700      *
701      * @param privateKey the private key of the identity whose signature
702      * is going to be generated.
703      *
704      * @param random the source of randomness for this signature.
705      *
706      * @exception InvalidKeyException if the key is invalid.
707      */
initSign(PrivateKey privateKey, SecureRandom random)708     public final void initSign(PrivateKey privateKey, SecureRandom random)
709             throws InvalidKeyException {
710         engineInitSign(privateKey, random);
711         state = SIGN;
712 
713         // BEGIN Android-removed: this debugging mechanism is not supported in Android.
714         /*
715         if (!skipDebug && pdebug != null) {
716             pdebug.println("Signature." + algorithm +
717                 " signing algorithm from: " + this.provider.getName());
718         }
719         */
720         // END Android-removed: this debugging mechanism is not supported in Android.
721     }
722 
723     /**
724      * Returns the signature bytes of all the data updated.
725      * The format of the signature depends on the underlying
726      * signature scheme.
727      *
728      * <p>A call to this method resets this signature object to the state
729      * it was in when previously initialized for signing via a
730      * call to {@code initSign(PrivateKey)}. That is, the object is
731      * reset and available to generate another signature from the same
732      * signer, if desired, via new calls to {@code update} and
733      * {@code sign}.
734      *
735      * @return the signature bytes of the signing operation's result.
736      *
737      * @exception SignatureException if this signature object is not
738      * initialized properly or if this signature algorithm is unable to
739      * process the input data provided.
740      */
sign()741     public final byte[] sign() throws SignatureException {
742         if (state == SIGN) {
743             return engineSign();
744         }
745         throw new SignatureException("object not initialized for " +
746                                      "signing");
747     }
748 
749     /**
750      * Finishes the signature operation and stores the resulting signature
751      * bytes in the provided buffer {@code outbuf}, starting at
752      * {@code offset}.
753      * The format of the signature depends on the underlying
754      * signature scheme.
755      *
756      * <p>This signature object is reset to its initial state (the state it
757      * was in after a call to one of the {@code initSign} methods) and
758      * can be reused to generate further signatures with the same private key.
759      *
760      * @param outbuf buffer for the signature result.
761      *
762      * @param offset offset into {@code outbuf} where the signature is
763      * stored.
764      *
765      * @param len number of bytes within {@code outbuf} allotted for the
766      * signature.
767      *
768      * @return the number of bytes placed into {@code outbuf}.
769      *
770      * @exception SignatureException if this signature object is not
771      * initialized properly, if this signature algorithm is unable to
772      * process the input data provided, or if {@code len} is less
773      * than the actual signature length.
774      *
775      * @since 1.2
776      */
sign(byte[] outbuf, int offset, int len)777     public final int sign(byte[] outbuf, int offset, int len)
778         throws SignatureException {
779         if (outbuf == null) {
780             throw new IllegalArgumentException("No output buffer given");
781         }
782         if (offset < 0 || len < 0) {
783             throw new IllegalArgumentException("offset or len is less than 0");
784         }
785         if (outbuf.length - offset < len) {
786             throw new IllegalArgumentException
787                 ("Output buffer too small for specified offset and length");
788         }
789         if (state != SIGN) {
790             throw new SignatureException("object not initialized for " +
791                                          "signing");
792         }
793         return engineSign(outbuf, offset, len);
794     }
795 
796     /**
797      * Verifies the passed-in signature.
798      *
799      * <p>A call to this method resets this signature object to the state
800      * it was in when previously initialized for verification via a
801      * call to {@code initVerify(PublicKey)}. That is, the object is
802      * reset and available to verify another signature from the identity
803      * whose public key was specified in the call to {@code initVerify}.
804      *
805      * @param signature the signature bytes to be verified.
806      *
807      * @return true if the signature was verified, false if not.
808      *
809      * @exception SignatureException if this signature object is not
810      * initialized properly, the passed-in signature is improperly
811      * encoded or of the wrong type, if this signature algorithm is unable to
812      * process the input data provided, etc.
813      */
verify(byte[] signature)814     public final boolean verify(byte[] signature) throws SignatureException {
815         if (state == VERIFY) {
816             return engineVerify(signature);
817         }
818         throw new SignatureException("object not initialized for " +
819                                      "verification");
820     }
821 
822     /**
823      * Verifies the passed-in signature in the specified array
824      * of bytes, starting at the specified offset.
825      *
826      * <p>A call to this method resets this signature object to the state
827      * it was in when previously initialized for verification via a
828      * call to {@code initVerify(PublicKey)}. That is, the object is
829      * reset and available to verify another signature from the identity
830      * whose public key was specified in the call to {@code initVerify}.
831      *
832      *
833      * @param signature the signature bytes to be verified.
834      * @param offset the offset to start from in the array of bytes.
835      * @param length the number of bytes to use, starting at offset.
836      *
837      * @return true if the signature was verified, false if not.
838      *
839      * @exception SignatureException if this signature object is not
840      * initialized properly, the passed-in signature is improperly
841      * encoded or of the wrong type, if this signature algorithm is unable to
842      * process the input data provided, etc.
843      * @exception IllegalArgumentException if the {@code signature}
844      * byte array is null, or the {@code offset} or {@code length}
845      * is less than 0, or the sum of the {@code offset} and
846      * {@code length} is greater than the length of the
847      * {@code signature} byte array.
848      * @since 1.4
849      */
verify(byte[] signature, int offset, int length)850     public final boolean verify(byte[] signature, int offset, int length)
851         throws SignatureException {
852         if (state == VERIFY) {
853             if (signature == null) {
854                 throw new IllegalArgumentException("signature is null");
855             }
856             if (offset < 0 || length < 0) {
857                 throw new IllegalArgumentException
858                     ("offset or length is less than 0");
859             }
860             if (signature.length - offset < length) {
861                 throw new IllegalArgumentException
862                     ("signature too small for specified offset and length");
863             }
864 
865             return engineVerify(signature, offset, length);
866         }
867         throw new SignatureException("object not initialized for " +
868                                      "verification");
869     }
870 
871     /**
872      * Updates the data to be signed or verified by a byte.
873      *
874      * @param b the byte to use for the update.
875      *
876      * @exception SignatureException if this signature object is not
877      * initialized properly.
878      */
update(byte b)879     public final void update(byte b) throws SignatureException {
880         if (state == VERIFY || state == SIGN) {
881             engineUpdate(b);
882         } else {
883             throw new SignatureException("object not initialized for "
884                                          + "signature or verification");
885         }
886     }
887 
888     /**
889      * Updates the data to be signed or verified, using the specified
890      * array of bytes.
891      *
892      * @param data the byte array to use for the update.
893      *
894      * @exception SignatureException if this signature object is not
895      * initialized properly.
896      */
update(byte[] data)897     public final void update(byte[] data) throws SignatureException {
898         update(data, 0, data.length);
899     }
900 
901     /**
902      * Updates the data to be signed or verified, using the specified
903      * array of bytes, starting at the specified offset.
904      *
905      * @param data the array of bytes.
906      * @param off the offset to start from in the array of bytes.
907      * @param len the number of bytes to use, starting at offset.
908      *
909      * @exception SignatureException if this signature object is not
910      * initialized properly.
911      */
update(byte[] data, int off, int len)912     public final void update(byte[] data, int off, int len)
913             throws SignatureException {
914         if (state == SIGN || state == VERIFY) {
915             if (data == null) {
916                 throw new IllegalArgumentException("data is null");
917             }
918             if (off < 0 || len < 0) {
919                 throw new IllegalArgumentException("off or len is less than 0");
920             }
921             if (data.length - off < len) {
922                 throw new IllegalArgumentException
923                     ("data too small for specified offset and length");
924             }
925             engineUpdate(data, off, len);
926         } else {
927             throw new SignatureException("object not initialized for "
928                                          + "signature or verification");
929         }
930     }
931 
932     /**
933      * Updates the data to be signed or verified using the specified
934      * ByteBuffer. Processes the {@code data.remaining()} bytes
935      * starting at at {@code data.position()}.
936      * Upon return, the buffer's position will be equal to its limit;
937      * its limit will not have changed.
938      *
939      * @param data the ByteBuffer
940      *
941      * @exception SignatureException if this signature object is not
942      * initialized properly.
943      * @since 1.5
944      */
update(ByteBuffer data)945     public final void update(ByteBuffer data) throws SignatureException {
946         if ((state != SIGN) && (state != VERIFY)) {
947             throw new SignatureException("object not initialized for "
948                                          + "signature or verification");
949         }
950         if (data == null) {
951             throw new NullPointerException();
952         }
953         engineUpdate(data);
954     }
955 
956     /**
957      * Returns the name of the algorithm for this signature object.
958      *
959      * @return the name of the algorithm for this signature object.
960      */
getAlgorithm()961     public final String getAlgorithm() {
962         return this.algorithm;
963     }
964 
965     /**
966      * Returns a string representation of this signature object,
967      * providing information that includes the state of the object
968      * and the name of the algorithm used.
969      *
970      * @return a string representation of this signature object.
971      */
toString()972     public String toString() {
973         String initState = "";
974         switch (state) {
975         case UNINITIALIZED:
976             initState = "<not initialized>";
977             break;
978         case VERIFY:
979             initState = "<initialized for verifying>";
980             break;
981         case SIGN:
982             initState = "<initialized for signing>";
983             break;
984         }
985         return "Signature object: " + getAlgorithm() + initState;
986     }
987 
988     /**
989      * Sets the specified algorithm parameter to the specified value.
990      * This method supplies a general-purpose mechanism through
991      * which it is possible to set the various parameters of this object.
992      * A parameter may be any settable parameter for the algorithm, such as
993      * a parameter size, or a source of random bits for signature generation
994      * (if appropriate), or an indication of whether or not to perform
995      * a specific but optional computation. A uniform algorithm-specific
996      * naming scheme for each parameter is desirable but left unspecified
997      * at this time.
998      *
999      * @param param the string identifier of the parameter.
1000      * @param value the parameter value.
1001      *
1002      * @exception InvalidParameterException if {@code param} is an
1003      * invalid parameter for this signature algorithm engine,
1004      * the parameter is already set
1005      * and cannot be set again, a security exception occurs, and so on.
1006      *
1007      * @see #getParameter
1008      *
1009      * @deprecated Use
1010      * {@link #setParameter(java.security.spec.AlgorithmParameterSpec)
1011      * setParameter}.
1012      */
1013     @Deprecated
setParameter(String param, Object value)1014     public final void setParameter(String param, Object value)
1015             throws InvalidParameterException {
1016         engineSetParameter(param, value);
1017     }
1018 
1019     /**
1020      * Initializes this signature engine with the specified parameter set.
1021      *
1022      * @param params the parameters
1023      *
1024      * @exception InvalidAlgorithmParameterException if the given parameters
1025      * are inappropriate for this signature engine
1026      *
1027      * @see #getParameters
1028      */
setParameter(AlgorithmParameterSpec params)1029     public final void setParameter(AlgorithmParameterSpec params)
1030             throws InvalidAlgorithmParameterException {
1031         engineSetParameter(params);
1032     }
1033 
1034     /**
1035      * Returns the parameters used with this signature object.
1036      *
1037      * <p>The returned parameters may be the same that were used to initialize
1038      * this signature, or may contain a combination of default and randomly
1039      * generated parameter values used by the underlying signature
1040      * implementation if this signature requires algorithm parameters but
1041      * was not initialized with any.
1042      *
1043      * @return the parameters used with this signature, or null if this
1044      * signature does not use any parameters.
1045      *
1046      * @see #setParameter(AlgorithmParameterSpec)
1047      * @since 1.4
1048      */
getParameters()1049     public final AlgorithmParameters getParameters() {
1050         return engineGetParameters();
1051     }
1052 
1053     /**
1054      * Gets the value of the specified algorithm parameter. This method
1055      * supplies a general-purpose mechanism through which it is possible to
1056      * get the various parameters of this object. A parameter may be any
1057      * settable parameter for the algorithm, such as a parameter size, or
1058      * a source of random bits for signature generation (if appropriate),
1059      * or an indication of whether or not to perform a specific but optional
1060      * computation. A uniform algorithm-specific naming scheme for each
1061      * parameter is desirable but left unspecified at this time.
1062      *
1063      * @param param the string name of the parameter.
1064      *
1065      * @return the object that represents the parameter value, or null if
1066      * there is none.
1067      *
1068      * @exception InvalidParameterException if {@code param} is an invalid
1069      * parameter for this engine, or another exception occurs while
1070      * trying to get this parameter.
1071      *
1072      * @see #setParameter(String, Object)
1073      *
1074      * @deprecated Deprecated.
1075      */
1076     @Deprecated
1077     // Android-changed: add "Deprecated."
getParameter(String param)1078     public final Object getParameter(String param)
1079             throws InvalidParameterException {
1080         return engineGetParameter(param);
1081     }
1082 
1083     /**
1084      * Returns a clone if the implementation is cloneable.
1085      *
1086      * @return a clone if the implementation is cloneable.
1087      *
1088      * @exception CloneNotSupportedException if this is called
1089      * on an implementation that does not support {@code Cloneable}.
1090      */
clone()1091     public Object clone() throws CloneNotSupportedException {
1092         if (this instanceof Cloneable) {
1093             return super.clone();
1094         } else {
1095             throw new CloneNotSupportedException();
1096         }
1097     }
1098 
1099     // BEGIN Android-added: Allow access to the current SPI for testing purposes.
1100     /**
1101      * Returns the {@code SignatureSpi} backing this {@code Signature}.
1102      *
1103      * @hide
1104      */
getCurrentSpi()1105     public SignatureSpi getCurrentSpi() {
1106       return null;
1107     }
1108     // END Android-added: Allow access to the current SPI for testing purposes.
1109 
1110     /*
1111      * The following class allows providers to extend from SignatureSpi
1112      * rather than from Signature. It represents a Signature with an
1113      * encapsulated, provider-supplied SPI object (of type SignatureSpi).
1114      * If the provider implementation is an instance of SignatureSpi, the
1115      * getInstance() methods above return an instance of this class, with
1116      * the SPI object encapsulated.
1117      *
1118      * Note: All SPI methods from the original Signature class have been
1119      * moved up the hierarchy into a new class (SignatureSpi), which has
1120      * been interposed in the hierarchy between the API (Signature)
1121      * and its original parent (Object).
1122      */
1123 
1124     @SuppressWarnings("deprecation")
1125     private static class Delegate extends Signature {
1126 
1127         // The provider implementation (delegate)
1128         // filled in once the provider is selected
1129         // BEGIN Android-note: Note on sigSpi invariants.
1130         // (Not necessarily Android specific)
1131         // Invariant to be preserved: sigSpi cannot be changed once it was assigned to something
1132         // different than null and lock is null. That is only the case when sigSpi is specified
1133         // in the constructor.
1134         // END Android-note: Note on sigSpi invariants.
1135         private SignatureSpi sigSpi;
1136 
1137         // lock for mutex during provider selection
1138         private final Object lock;
1139 
1140         // BEGIN Android-removed: Redo the provider selection logic to allow reselecting provider.
1141         // When only the algorithm is specified, we want to allow the Signature provider for that
1142         // algorithm to change if multiple providers exist and they support different subsets of
1143         // keys.  To that end, we don't hold an iterator and exhaust it when we need to choose
1144         // a provider like the upstream implementation, we reestablish the list of providers
1145         // each time.
1146         /*
1147         // next service to try in provider selection
1148         // null once provider is selected
1149         private Service firstService;
1150 
1151         // remaining services to try in provider selection
1152         // null once provider is selected
1153         private Iterator<Service> serviceIterator;
1154         */
1155         // END Android-removed: Redo the provider selection logic to allow reselecting provider.
1156 
1157         // constructor
Delegate(SignatureSpi sigSpi, String algorithm)1158         Delegate(SignatureSpi sigSpi, String algorithm) {
1159             super(algorithm);
1160             this.sigSpi = sigSpi;
1161             this.lock = null; // no lock needed
1162         }
1163 
1164         // used with delayed provider selection
1165         // Android-changed: Remove Service and Iterator from constructor args.
Delegate(String algorithm)1166         Delegate(String algorithm) {
1167             super(algorithm);
1168             this.lock = new Object();
1169         }
1170 
1171         /**
1172          * Returns a clone if the delegate is cloneable.
1173          *
1174          * @return a clone if the delegate is cloneable.
1175          *
1176          * @exception CloneNotSupportedException if this is called on a
1177          * delegate that does not support {@code Cloneable}.
1178          */
clone()1179         public Object clone() throws CloneNotSupportedException {
1180             chooseFirstProvider();
1181             if (sigSpi instanceof Cloneable) {
1182                 SignatureSpi sigSpiClone = (SignatureSpi)sigSpi.clone();
1183                 // Because 'algorithm' and 'provider' are private
1184                 // members of our supertype, we must perform a cast to
1185                 // access them.
1186                 Signature that =
1187                     new Delegate(sigSpiClone, ((Signature)this).algorithm);
1188                 that.provider = ((Signature)this).provider;
1189                 return that;
1190             } else {
1191                 throw new CloneNotSupportedException();
1192             }
1193         }
1194 
newInstance(Service s)1195         private static SignatureSpi newInstance(Service s)
1196                 throws NoSuchAlgorithmException {
1197             if (s.getType().equals("Cipher")) {
1198                 // must be NONEwithRSA
1199                 try {
1200                     Cipher c = Cipher.getInstance(RSA_CIPHER, s.getProvider());
1201                     return new CipherAdapter(c);
1202                 } catch (NoSuchPaddingException e) {
1203                     throw new NoSuchAlgorithmException(e);
1204                 }
1205             } else {
1206                 Object o = s.newInstance(null);
1207                 if (o instanceof SignatureSpi == false) {
1208                     throw new NoSuchAlgorithmException
1209                         ("Not a SignatureSpi: " + o.getClass().getName());
1210                 }
1211                 return (SignatureSpi)o;
1212             }
1213         }
1214 
1215         // max number of debug warnings to print from chooseFirstProvider()
1216         private static int warnCount = 10;
1217 
1218         /**
1219          * Choose the Spi from the first provider available. Used if
1220          * delayed provider selection is not possible because initSign()/
1221          * initVerify() is not the first method called.
1222          */
chooseFirstProvider()1223         void chooseFirstProvider() {
1224             if (sigSpi != null) {
1225                 return;
1226             }
1227             synchronized (lock) {
1228                 if (sigSpi != null) {
1229                     return;
1230                 }
1231                 // BEGIN Android-removed: this debugging mechanism is not supported in Android.
1232                 /*
1233                 if (debug != null) {
1234                     int w = --warnCount;
1235                     if (w >= 0) {
1236                         debug.println("Signature.init() not first method "
1237                             + "called, disabling delayed provider selection");
1238                         if (w == 0) {
1239                             debug.println("Further warnings of this type will "
1240                                 + "be suppressed");
1241                         }
1242                         new Exception("Call trace").printStackTrace();
1243                     }
1244                 }
1245                 */
1246                 // END Android-removed: this debugging mechanism is not supported in Android.
1247                 Exception lastException = null;
1248 // BEGIN Android-changed: Provider selection; loop over a new list each time.
1249                 List<Service> list;
1250                 if (((Signature)this).algorithm.equalsIgnoreCase(RSA_SIGNATURE)) {
1251                     list = GetInstance.getServices(rsaIds);
1252                 } else {
1253                     list = GetInstance.getServices("Signature",
1254                             ((Signature)this).algorithm);
1255                 }
1256                 for (Service s : list) {
1257 // END Android-changed: Provider selection; loop over a new list each time.
1258                     if (isSpi(s) == false) {
1259                         continue;
1260                     }
1261                     try {
1262                         sigSpi = newInstance(s);
1263                         provider = s.getProvider();
1264                         // Android-removed: Provider selection; loop over a new list each time.
1265                         /*
1266                         // not needed any more
1267                         firstService = null;
1268                         serviceIterator = null;
1269                         */
1270                         return;
1271                     } catch (NoSuchAlgorithmException e) {
1272                         lastException = e;
1273                     }
1274                 }
1275                 ProviderException e = new ProviderException
1276                         ("Could not construct SignatureSpi instance");
1277                 if (lastException != null) {
1278                     e.initCause(lastException);
1279                 }
1280                 throw e;
1281             }
1282         }
1283 
chooseProvider(int type, Key key, SecureRandom random)1284         private void chooseProvider(int type, Key key, SecureRandom random)
1285                 throws InvalidKeyException {
1286             synchronized (lock) {
1287                 // Android-changed: Use the currently-selected provider only if no key was provided.
1288                 // if (sigSpi != null) {
1289                 if (sigSpi != null && key == null) {
1290                     init(sigSpi, type, key, random);
1291                     return;
1292                 }
1293                 Exception lastException = null;
1294 // BEGIN Android-changed: Provider selection; loop over a new list each time.
1295                 List<Service> list;
1296                 if (((Signature)this).algorithm.equalsIgnoreCase(RSA_SIGNATURE)) {
1297                     list = GetInstance.getServices(rsaIds);
1298                 } else {
1299                     list = GetInstance.getServices("Signature",
1300                             ((Signature)this).algorithm);
1301                 }
1302                 for (Service s : list) {
1303 // END Android-changed: Provider selection; loop over a new list each time.
1304                     // if provider says it does not support this key, ignore it
1305                     if (s.supportsParameter(key) == false) {
1306                         continue;
1307                     }
1308                     // if instance is not a SignatureSpi, ignore it
1309                     if (isSpi(s) == false) {
1310                         continue;
1311                     }
1312                     try {
1313                         SignatureSpi spi = newInstance(s);
1314                         init(spi, type, key, random);
1315                         provider = s.getProvider();
1316                         sigSpi = spi;
1317                         // Android-removed: Provider selection; loop over a new list each time.
1318                         /*
1319                         firstService = null;
1320                         serviceIterator = null;
1321                         */
1322                         return;
1323                     } catch (Exception e) {
1324                         // NoSuchAlgorithmException from newInstance()
1325                         // InvalidKeyException from init()
1326                         // RuntimeException (ProviderException) from init()
1327                         if (lastException == null) {
1328                             lastException = e;
1329                         }
1330                         // Android-added: Throw InvalidKeyException immediately.
1331                         if (lastException instanceof InvalidKeyException) {
1332                           throw (InvalidKeyException)lastException;
1333                         }
1334                     }
1335                 }
1336                 // no working provider found, fail
1337                 if (lastException instanceof InvalidKeyException) {
1338                     throw (InvalidKeyException)lastException;
1339                 }
1340                 if (lastException instanceof RuntimeException) {
1341                     throw (RuntimeException)lastException;
1342                 }
1343                 String k = (key != null) ? key.getClass().getName() : "(null)";
1344                 throw new InvalidKeyException
1345                     ("No installed provider supports this key: "
1346                     + k, lastException);
1347             }
1348         }
1349 
1350         private final static int I_PUB     = 1;
1351         private final static int I_PRIV    = 2;
1352         private final static int I_PRIV_SR = 3;
1353 
init(SignatureSpi spi, int type, Key key, SecureRandom random)1354         private void init(SignatureSpi spi, int type, Key  key,
1355                 SecureRandom random) throws InvalidKeyException {
1356             switch (type) {
1357             case I_PUB:
1358                 spi.engineInitVerify((PublicKey)key);
1359                 break;
1360             case I_PRIV:
1361                 spi.engineInitSign((PrivateKey)key);
1362                 break;
1363             case I_PRIV_SR:
1364                 spi.engineInitSign((PrivateKey)key, random);
1365                 break;
1366             default:
1367                 throw new AssertionError("Internal error: " + type);
1368             }
1369         }
1370 
engineInitVerify(PublicKey publicKey)1371         protected void engineInitVerify(PublicKey publicKey)
1372                 throws InvalidKeyException {
1373             // Android-changed: Use the currently-selected provider only if no key was provided.
1374             // if (sigSpi != null) {
1375             if (sigSpi != null && (lock == null || publicKey == null)) {
1376                 sigSpi.engineInitVerify(publicKey);
1377             } else {
1378                 chooseProvider(I_PUB, publicKey, null);
1379             }
1380         }
1381 
engineInitSign(PrivateKey privateKey)1382         protected void engineInitSign(PrivateKey privateKey)
1383                 throws InvalidKeyException {
1384             // Android-changed: Use the currently-selected provider only if no key was provided.
1385             // if (sigSpi != null) {
1386             if (sigSpi != null && (lock == null || privateKey == null)) {
1387                 sigSpi.engineInitSign(privateKey);
1388             } else {
1389                 chooseProvider(I_PRIV, privateKey, null);
1390             }
1391         }
1392 
engineInitSign(PrivateKey privateKey, SecureRandom sr)1393         protected void engineInitSign(PrivateKey privateKey, SecureRandom sr)
1394                 throws InvalidKeyException {
1395             // Android-changed: Use the currently-selected provider only if no key was provided.
1396             // if (sigSpi != null) {
1397             if (sigSpi != null  && (lock == null || privateKey == null)) {
1398                 sigSpi.engineInitSign(privateKey, sr);
1399             } else {
1400                 chooseProvider(I_PRIV_SR, privateKey, sr);
1401             }
1402         }
1403 
engineUpdate(byte b)1404         protected void engineUpdate(byte b) throws SignatureException {
1405             chooseFirstProvider();
1406             sigSpi.engineUpdate(b);
1407         }
1408 
engineUpdate(byte[] b, int off, int len)1409         protected void engineUpdate(byte[] b, int off, int len)
1410                 throws SignatureException {
1411             chooseFirstProvider();
1412             sigSpi.engineUpdate(b, off, len);
1413         }
1414 
engineUpdate(ByteBuffer data)1415         protected void engineUpdate(ByteBuffer data) {
1416             chooseFirstProvider();
1417             sigSpi.engineUpdate(data);
1418         }
1419 
engineSign()1420         protected byte[] engineSign() throws SignatureException {
1421             chooseFirstProvider();
1422             return sigSpi.engineSign();
1423         }
1424 
engineSign(byte[] outbuf, int offset, int len)1425         protected int engineSign(byte[] outbuf, int offset, int len)
1426                 throws SignatureException {
1427             chooseFirstProvider();
1428             return sigSpi.engineSign(outbuf, offset, len);
1429         }
1430 
engineVerify(byte[] sigBytes)1431         protected boolean engineVerify(byte[] sigBytes)
1432                 throws SignatureException {
1433             chooseFirstProvider();
1434             return sigSpi.engineVerify(sigBytes);
1435         }
1436 
engineVerify(byte[] sigBytes, int offset, int length)1437         protected boolean engineVerify(byte[] sigBytes, int offset, int length)
1438                 throws SignatureException {
1439             chooseFirstProvider();
1440             return sigSpi.engineVerify(sigBytes, offset, length);
1441         }
1442 
engineSetParameter(String param, Object value)1443         protected void engineSetParameter(String param, Object value)
1444                 throws InvalidParameterException {
1445             chooseFirstProvider();
1446             sigSpi.engineSetParameter(param, value);
1447         }
1448 
engineSetParameter(AlgorithmParameterSpec params)1449         protected void engineSetParameter(AlgorithmParameterSpec params)
1450                 throws InvalidAlgorithmParameterException {
1451             chooseFirstProvider();
1452             sigSpi.engineSetParameter(params);
1453         }
1454 
engineGetParameter(String param)1455         protected Object engineGetParameter(String param)
1456                 throws InvalidParameterException {
1457             chooseFirstProvider();
1458             return sigSpi.engineGetParameter(param);
1459         }
1460 
engineGetParameters()1461         protected AlgorithmParameters engineGetParameters() {
1462             chooseFirstProvider();
1463             return sigSpi.engineGetParameters();
1464         }
1465 
1466         // BEGIN Android-added: Allow access to the current SPI for testing purposes.
1467         @Override
getCurrentSpi()1468         public SignatureSpi getCurrentSpi() {
1469             if (lock == null) {
1470                 return sigSpi;
1471             }
1472             synchronized (lock) {
1473                 return sigSpi;
1474             }
1475         }
1476         // END Android-added: Allow access to the current SPI for testing purposes.
1477     }
1478 
1479     // adapter for RSA/ECB/PKCS1Padding ciphers
1480     @SuppressWarnings("deprecation")
1481     private static class CipherAdapter extends SignatureSpi {
1482 
1483         private final Cipher cipher;
1484 
1485         private ByteArrayOutputStream data;
1486 
CipherAdapter(Cipher cipher)1487         CipherAdapter(Cipher cipher) {
1488             this.cipher = cipher;
1489         }
1490 
engineInitVerify(PublicKey publicKey)1491         protected void engineInitVerify(PublicKey publicKey)
1492                 throws InvalidKeyException {
1493             cipher.init(Cipher.DECRYPT_MODE, publicKey);
1494             if (data == null) {
1495                 data = new ByteArrayOutputStream(128);
1496             } else {
1497                 data.reset();
1498             }
1499         }
1500 
engineInitSign(PrivateKey privateKey)1501         protected void engineInitSign(PrivateKey privateKey)
1502                 throws InvalidKeyException {
1503             cipher.init(Cipher.ENCRYPT_MODE, privateKey);
1504             data = null;
1505         }
1506 
engineInitSign(PrivateKey privateKey, SecureRandom random)1507         protected void engineInitSign(PrivateKey privateKey,
1508                 SecureRandom random) throws InvalidKeyException {
1509             cipher.init(Cipher.ENCRYPT_MODE, privateKey, random);
1510             data = null;
1511         }
1512 
engineUpdate(byte b)1513         protected void engineUpdate(byte b) throws SignatureException {
1514             engineUpdate(new byte[] {b}, 0, 1);
1515         }
1516 
engineUpdate(byte[] b, int off, int len)1517         protected void engineUpdate(byte[] b, int off, int len)
1518                 throws SignatureException {
1519             if (data != null) {
1520                 data.write(b, off, len);
1521                 return;
1522             }
1523             byte[] out = cipher.update(b, off, len);
1524             if ((out != null) && (out.length != 0)) {
1525                 throw new SignatureException
1526                     ("Cipher unexpectedly returned data");
1527             }
1528         }
1529 
engineSign()1530         protected byte[] engineSign() throws SignatureException {
1531             try {
1532                 return cipher.doFinal();
1533             } catch (IllegalBlockSizeException e) {
1534                 throw new SignatureException("doFinal() failed", e);
1535             } catch (BadPaddingException e) {
1536                 throw new SignatureException("doFinal() failed", e);
1537             }
1538         }
1539 
engineVerify(byte[] sigBytes)1540         protected boolean engineVerify(byte[] sigBytes)
1541                 throws SignatureException {
1542             try {
1543                 byte[] out = cipher.doFinal(sigBytes);
1544                 byte[] dataBytes = data.toByteArray();
1545                 data.reset();
1546                 return MessageDigest.isEqual(out, dataBytes);
1547             } catch (BadPaddingException e) {
1548                 // e.g. wrong public key used
1549                 // return false rather than throwing exception
1550                 return false;
1551             } catch (IllegalBlockSizeException e) {
1552                 throw new SignatureException("doFinal() failed", e);
1553             }
1554         }
1555 
engineSetParameter(String param, Object value)1556         protected void engineSetParameter(String param, Object value)
1557                 throws InvalidParameterException {
1558             throw new InvalidParameterException("Parameters not supported");
1559         }
1560 
engineGetParameter(String param)1561         protected Object engineGetParameter(String param)
1562                 throws InvalidParameterException {
1563             throw new InvalidParameterException("Parameters not supported");
1564         }
1565 
1566     }
1567 
1568 }
1569