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