1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
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 sun.security.x509;
28 
29 import java.io.*;
30 import java.util.*;
31 import java.security.*;
32 
33 import sun.security.util.*;
34 
35 
36 /**
37  * This class identifies algorithms, such as cryptographic transforms, each
38  * of which may be associated with parameters.  Instances of this base class
39  * are used when this runtime environment has no special knowledge of the
40  * algorithm type, and may also be used in other cases.  Equivalence is
41  * defined according to OID and (where relevant) parameters.
42  *
43  * <P>Subclasses may be used, for example when when the algorithm ID has
44  * associated parameters which some code (e.g. code using public keys) needs
45  * to have parsed.  Two examples of such algorithms are Diffie-Hellman key
46  * exchange, and the Digital Signature Standard Algorithm (DSS/DSA).
47  *
48  * <P>The OID constants defined in this class correspond to some widely
49  * used algorithms, for which conventional string names have been defined.
50  * This class is not a general repository for OIDs, or for such string names.
51  * Note that the mappings between algorithm IDs and algorithm names is
52  * not one-to-one.
53  *
54  *
55  * @author David Brownell
56  * @author Amit Kapoor
57  * @author Hemma Prafullchandra
58  */
59 public class AlgorithmId implements Serializable, DerEncoder {
60 
61     /** use serialVersionUID from JDK 1.1. for interoperability */
62     private static final long serialVersionUID = 7205873507486557157L;
63 
64     /**
65      * The object identitifer being used for this algorithm.
66      */
67     private ObjectIdentifier algid;
68 
69     // The (parsed) parameters
70     private AlgorithmParameters algParams;
71     private boolean constructedFromDer = true;
72 
73     /**
74      * Parameters for this algorithm.  These are stored in unparsed
75      * DER-encoded form; subclasses can be made to automaticaly parse
76      * them so there is fast access to these parameters.
77      */
78     protected DerValue          params;
79 
80 
81     /**
82      * Constructs an algorithm ID which will be initialized
83      * separately, for example by deserialization.
84      * @deprecated use one of the other constructors.
85      */
86     @Deprecated
AlgorithmId()87     public AlgorithmId() { }
88 
89     /**
90      * Constructs a parameterless algorithm ID.
91      *
92      * @param oid the identifier for the algorithm
93      */
AlgorithmId(ObjectIdentifier oid)94     public AlgorithmId(ObjectIdentifier oid) {
95         algid = oid;
96     }
97 
98     /**
99      * Constructs an algorithm ID with algorithm parameters.
100      *
101      * @param oid the identifier for the algorithm.
102      * @param algparams the associated algorithm parameters.
103      */
AlgorithmId(ObjectIdentifier oid, AlgorithmParameters algparams)104     public AlgorithmId(ObjectIdentifier oid, AlgorithmParameters algparams) {
105         algid = oid;
106         algParams = algparams;
107         constructedFromDer = false;
108     }
109 
AlgorithmId(ObjectIdentifier oid, DerValue params)110     private AlgorithmId(ObjectIdentifier oid, DerValue params)
111             throws IOException {
112         this.algid = oid;
113         this.params = params;
114         if (this.params != null) {
115             decodeParams();
116         }
117     }
118 
decodeParams()119     protected void decodeParams() throws IOException {
120         String algidString = algid.toString();
121         try {
122             algParams = AlgorithmParameters.getInstance(algidString);
123         } catch (NoSuchAlgorithmException e) {
124             // BEGIN Android-changed
125             // It was searching for the EC parameters in an internal provider in the deleted package
126             // sun.security.ec before setting them to null. Since EC is in the OpenSSL provider,
127             // there's no need for such fallback. Setting it to null directly.
128             /*
129              * This algorithm parameter type is not supported, so we cannot
130              * parse the parameters.
131              */
132             algParams = null;
133             return;
134             // END Android-changed
135         }
136         // Decode (parse) the parameters
137         algParams.init(params.toByteArray());
138     }
139 
140     /**
141      * Marshal a DER-encoded "AlgorithmID" sequence on the DER stream.
142      */
encode(DerOutputStream out)143     public final void encode(DerOutputStream out) throws IOException {
144         derEncode(out);
145     }
146 
147     /**
148      * DER encode this object onto an output stream.
149      * Implements the <code>DerEncoder</code> interface.
150      *
151      * @param out
152      * the output stream on which to write the DER encoding.
153      *
154      * @exception IOException on encoding error.
155      */
derEncode(OutputStream out)156     public void derEncode (OutputStream out) throws IOException {
157         DerOutputStream bytes = new DerOutputStream();
158         DerOutputStream tmp = new DerOutputStream();
159 
160         bytes.putOID(algid);
161         // Setup params from algParams since no DER encoding is given
162         if (constructedFromDer == false) {
163             if (algParams != null) {
164                 params = new DerValue(algParams.getEncoded());
165             } else {
166                 params = null;
167             }
168         }
169         if (params == null) {
170             // Changes backed out for compatibility with Solaris
171 
172             // Several AlgorithmId should omit the whole parameter part when
173             // it's NULL. They are ---
174             // rfc3370 2.1: Implementations SHOULD generate SHA-1
175             // AlgorithmIdentifiers with absent parameters.
176             // rfc3447 C1: When id-sha1, id-sha224, id-sha256, id-sha384 and
177             // id-sha512 are used in an AlgorithmIdentifier the parameters
178             // (which are optional) SHOULD be omitted.
179             // rfc3279 2.3.2: The id-dsa algorithm syntax includes optional
180             // domain parameters... When omitted, the parameters component
181             // MUST be omitted entirely
182             // rfc3370 3.1: When the id-dsa-with-sha1 algorithm identifier
183             // is used, the AlgorithmIdentifier parameters field MUST be absent.
184             /*if (
185                 algid.equals((Object)SHA_oid) ||
186                 algid.equals((Object)SHA224_oid) ||
187                 algid.equals((Object)SHA256_oid) ||
188                 algid.equals((Object)SHA384_oid) ||
189                 algid.equals((Object)SHA512_oid) ||
190                 algid.equals((Object)DSA_oid) ||
191                 algid.equals((Object)sha1WithDSA_oid)) {
192                 ; // no parameter part encoded
193             } else {
194                 bytes.putNull();
195             }*/
196             bytes.putNull();
197         } else {
198             bytes.putDerValue(params);
199         }
200         tmp.write(DerValue.tag_Sequence, bytes);
201         out.write(tmp.toByteArray());
202     }
203 
204 
205     /**
206      * Returns the DER-encoded X.509 AlgorithmId as a byte array.
207      */
encode()208     public final byte[] encode() throws IOException {
209         DerOutputStream out = new DerOutputStream();
210         derEncode(out);
211         return out.toByteArray();
212     }
213 
214     /**
215      * Returns the ISO OID for this algorithm.  This is usually converted
216      * to a string and used as part of an algorithm name, for example
217      * "OID.1.3.14.3.2.13" style notation.  Use the <code>getName</code>
218      * call when you do not need to ensure cross-system portability
219      * of algorithm names, or need a user friendly name.
220      */
getOID()221     public final ObjectIdentifier getOID () {
222         return algid;
223     }
224 
225     /**
226      * Returns a name for the algorithm which may be more intelligible
227      * to humans than the algorithm's OID, but which won't necessarily
228      * be comprehensible on other systems.  For example, this might
229      * return a name such as "MD5withRSA" for a signature algorithm on
230      * some systems.  It also returns names like "OID.1.2.3.4", when
231      * no particular name for the algorithm is known.
232      */
getName()233     public String getName() {
234         String algName = nameTable.get(algid);
235         if (algName != null) {
236             return algName;
237         }
238         if ((params != null) && algid.equals((Object)specifiedWithECDSA_oid)) {
239             try {
240                 AlgorithmId paramsId =
241                         AlgorithmId.parse(new DerValue(getEncodedParams()));
242                 String paramsName = paramsId.getName();
243                 algName = makeSigAlg(paramsName, "EC");
244             } catch (IOException e) {
245                 // ignore
246             }
247         }
248 
249         // Try to update the name <-> OID mapping table.
250         synchronized (oidTable) {
251             reinitializeMappingTableLocked();
252             algName = nameTable.get(algid);
253         }
254 
255         return (algName == null) ? algid.toString() : algName;
256     }
257 
getParameters()258     public AlgorithmParameters getParameters() {
259         return algParams;
260     }
261 
262     /**
263      * Returns the DER encoded parameter, which can then be
264      * used to initialize java.security.AlgorithmParamters.
265      *
266      * @return DER encoded parameters, or null not present.
267      */
getEncodedParams()268     public byte[] getEncodedParams() throws IOException {
269         return (params == null) ? null : params.toByteArray();
270     }
271 
272     /**
273      * Returns true iff the argument indicates the same algorithm
274      * with the same parameters.
275      */
equals(AlgorithmId other)276     public boolean equals(AlgorithmId other) {
277         boolean paramsEqual =
278           (params == null ? other.params == null : params.equals(other.params));
279         return (algid.equals((Object)other.algid) && paramsEqual);
280     }
281 
282     /**
283      * Compares this AlgorithmID to another.  If algorithm parameters are
284      * available, they are compared.  Otherwise, just the object IDs
285      * for the algorithm are compared.
286      *
287      * @param other preferably an AlgorithmId, else an ObjectIdentifier
288      */
equals(Object other)289     public boolean equals(Object other) {
290         if (this == other) {
291             return true;
292         }
293         if (other instanceof AlgorithmId) {
294             return equals((AlgorithmId) other);
295         } else if (other instanceof ObjectIdentifier) {
296             return equals((ObjectIdentifier) other);
297         } else {
298             return false;
299         }
300     }
301 
302     /**
303      * Compares two algorithm IDs for equality.  Returns true iff
304      * they are the same algorithm, ignoring algorithm parameters.
305      */
equals(ObjectIdentifier id)306     public final boolean equals(ObjectIdentifier id) {
307         return algid.equals((Object)id);
308     }
309 
310     /**
311      * Returns a hashcode for this AlgorithmId.
312      *
313      * @return a hashcode for this AlgorithmId.
314      */
hashCode()315     public int hashCode() {
316         StringBuilder sbuf = new StringBuilder();
317         sbuf.append(algid.toString());
318         sbuf.append(paramsToString());
319         return sbuf.toString().hashCode();
320     }
321 
322     /**
323      * Provides a human-readable description of the algorithm parameters.
324      * This may be redefined by subclasses which parse those parameters.
325      */
paramsToString()326     protected String paramsToString() {
327         if (params == null) {
328             return "";
329         } else if (algParams != null) {
330             return algParams.toString();
331         } else {
332             return ", params unparsed";
333         }
334     }
335 
336     /**
337      * Returns a string describing the algorithm and its parameters.
338      */
toString()339     public String toString() {
340         return getName() + paramsToString();
341     }
342 
343     /**
344      * Parse (unmarshal) an ID from a DER sequence input value.  This form
345      * parsing might be used when expanding a value which has already been
346      * partially unmarshaled as a set or sequence member.
347      *
348      * @exception IOException on error.
349      * @param val the input value, which contains the algid and, if
350      *          there are any parameters, those parameters.
351      * @return an ID for the algorithm.  If the system is configured
352      *          appropriately, this may be an instance of a class
353      *          with some kind of special support for this algorithm.
354      *          In that case, you may "narrow" the type of the ID.
355      */
parse(DerValue val)356     public static AlgorithmId parse(DerValue val) throws IOException {
357         if (val.tag != DerValue.tag_Sequence) {
358             throw new IOException("algid parse error, not a sequence");
359         }
360 
361         /*
362          * Get the algorithm ID and any parameters.
363          */
364         ObjectIdentifier        algid;
365         DerValue                params;
366         DerInputStream          in = val.toDerInputStream();
367 
368         algid = in.getOID();
369         if (in.available() == 0) {
370             params = null;
371         } else {
372             params = in.getDerValue();
373             if (params.tag == DerValue.tag_Null) {
374                 if (params.length() != 0) {
375                     throw new IOException("invalid NULL");
376                 }
377                 params = null;
378             }
379             if (in.available() != 0) {
380                 throw new IOException("Invalid AlgorithmIdentifier: extra data");
381             }
382         }
383 
384         return new AlgorithmId(algid, params);
385     }
386 
387     /**
388      * Returns one of the algorithm IDs most commonly associated
389      * with this algorithm name.
390      *
391      * @param algname the name being used
392      * @deprecated use the short get form of this method.
393      * @exception NoSuchAlgorithmException on error.
394      */
395     @Deprecated
getAlgorithmId(String algname)396     public static AlgorithmId getAlgorithmId(String algname)
397             throws NoSuchAlgorithmException {
398         return get(algname);
399     }
400 
401     /**
402      * Returns one of the algorithm IDs most commonly associated
403      * with this algorithm name.
404      *
405      * @param algname the name being used
406      * @exception NoSuchAlgorithmException on error.
407      */
get(String algname)408     public static AlgorithmId get(String algname)
409             throws NoSuchAlgorithmException {
410         ObjectIdentifier oid;
411         try {
412             oid = algOID(algname);
413         } catch (IOException ioe) {
414             throw new NoSuchAlgorithmException
415                 ("Invalid ObjectIdentifier " + algname);
416         }
417 
418         if (oid == null) {
419             throw new NoSuchAlgorithmException
420                 ("unrecognized algorithm name: " + algname);
421         }
422         return new AlgorithmId(oid);
423     }
424 
425     /**
426      * Returns one of the algorithm IDs most commonly associated
427      * with this algorithm parameters.
428      *
429      * @param algparams the associated algorithm parameters.
430      * @exception NoSuchAlgorithmException on error.
431      */
get(AlgorithmParameters algparams)432     public static AlgorithmId get(AlgorithmParameters algparams)
433             throws NoSuchAlgorithmException {
434         ObjectIdentifier oid;
435         String algname = algparams.getAlgorithm();
436         try {
437             oid = algOID(algname);
438         } catch (IOException ioe) {
439             throw new NoSuchAlgorithmException
440                 ("Invalid ObjectIdentifier " + algname);
441         }
442         if (oid == null) {
443             throw new NoSuchAlgorithmException
444                 ("unrecognized algorithm name: " + algname);
445         }
446         return new AlgorithmId(oid, algparams);
447     }
448 
449     /*
450      * Translates from some common algorithm names to the
451      * OID with which they're usually associated ... this mapping
452      * is the reverse of the one below, except in those cases
453      * where synonyms are supported or where a given algorithm
454      * is commonly associated with multiple OIDs.
455      *
456      * XXX This method needs to be enhanced so that we can also pass the
457      * scope of the algorithm name to it, e.g., the algorithm name "DSA"
458      * may have a different OID when used as a "Signature" algorithm than when
459      * used as a "KeyPairGenerator" algorithm.
460      */
algOID(String name)461     private static ObjectIdentifier algOID(String name) throws IOException {
462         // See if algname is in printable OID ("dot-dot") notation
463         if (name.indexOf('.') != -1) {
464             if (name.startsWith("OID.")) {
465                 return new ObjectIdentifier(name.substring("OID.".length()));
466             } else {
467                 return new ObjectIdentifier(name);
468             }
469         }
470 
471         // Digesting algorithms
472         if (name.equalsIgnoreCase("MD5")) {
473             return AlgorithmId.MD5_oid;
474         }
475         if (name.equalsIgnoreCase("MD2")) {
476             return AlgorithmId.MD2_oid;
477         }
478         if (name.equalsIgnoreCase("SHA") || name.equalsIgnoreCase("SHA1")
479             || name.equalsIgnoreCase("SHA-1")) {
480             return AlgorithmId.SHA_oid;
481         }
482         if (name.equalsIgnoreCase("SHA-256") ||
483             name.equalsIgnoreCase("SHA256")) {
484             return AlgorithmId.SHA256_oid;
485         }
486         if (name.equalsIgnoreCase("SHA-384") ||
487             name.equalsIgnoreCase("SHA384")) {
488             return AlgorithmId.SHA384_oid;
489         }
490         if (name.equalsIgnoreCase("SHA-512") ||
491             name.equalsIgnoreCase("SHA512")) {
492             return AlgorithmId.SHA512_oid;
493         }
494         if (name.equalsIgnoreCase("SHA-224") ||
495             name.equalsIgnoreCase("SHA224")) {
496             return AlgorithmId.SHA224_oid;
497         }
498 
499         // Various public key algorithms
500         if (name.equalsIgnoreCase("RSA")) {
501             return AlgorithmId.RSAEncryption_oid;
502         }
503         if (name.equalsIgnoreCase("Diffie-Hellman")
504             || name.equalsIgnoreCase("DH")) {
505             return AlgorithmId.DH_oid;
506         }
507         if (name.equalsIgnoreCase("DSA")) {
508             return AlgorithmId.DSA_oid;
509         }
510         if (name.equalsIgnoreCase("EC")) {
511             return EC_oid;
512         }
513         if (name.equalsIgnoreCase("ECDH")) {
514             return AlgorithmId.ECDH_oid;
515         }
516 
517         // Secret key algorithms
518         if (name.equalsIgnoreCase("AES")) {
519             return AlgorithmId.AES_oid;
520         }
521 
522         // Common signature types
523         if (name.equalsIgnoreCase("MD5withRSA")
524             || name.equalsIgnoreCase("MD5/RSA")) {
525             return AlgorithmId.md5WithRSAEncryption_oid;
526         }
527         if (name.equalsIgnoreCase("MD2withRSA")
528             || name.equalsIgnoreCase("MD2/RSA")) {
529             return AlgorithmId.md2WithRSAEncryption_oid;
530         }
531         if (name.equalsIgnoreCase("SHAwithDSA")
532             || name.equalsIgnoreCase("SHA1withDSA")
533             || name.equalsIgnoreCase("SHA/DSA")
534             || name.equalsIgnoreCase("SHA1/DSA")
535             || name.equalsIgnoreCase("DSAWithSHA1")
536             || name.equalsIgnoreCase("DSS")
537             || name.equalsIgnoreCase("SHA-1/DSA")) {
538             return AlgorithmId.sha1WithDSA_oid;
539         }
540         if (name.equalsIgnoreCase("SHA224WithDSA")) {
541             return AlgorithmId.sha224WithDSA_oid;
542         }
543         if (name.equalsIgnoreCase("SHA256WithDSA")) {
544             return AlgorithmId.sha256WithDSA_oid;
545         }
546         if (name.equalsIgnoreCase("SHA1WithRSA")
547             || name.equalsIgnoreCase("SHA1/RSA")) {
548             return AlgorithmId.sha1WithRSAEncryption_oid;
549         }
550         if (name.equalsIgnoreCase("SHA1withECDSA")
551                 || name.equalsIgnoreCase("ECDSA")) {
552             return AlgorithmId.sha1WithECDSA_oid;
553         }
554         if (name.equalsIgnoreCase("SHA224withECDSA")) {
555             return AlgorithmId.sha224WithECDSA_oid;
556         }
557         if (name.equalsIgnoreCase("SHA256withECDSA")) {
558             return AlgorithmId.sha256WithECDSA_oid;
559         }
560         if (name.equalsIgnoreCase("SHA384withECDSA")) {
561             return AlgorithmId.sha384WithECDSA_oid;
562         }
563         if (name.equalsIgnoreCase("SHA512withECDSA")) {
564             return AlgorithmId.sha512WithECDSA_oid;
565         }
566 
567         // See if any of the installed providers supply a mapping from
568         // the given algorithm name to an OID string
569         synchronized (oidTable) {
570             reinitializeMappingTableLocked();
571             return oidTable.get(name.toUpperCase(Locale.ENGLISH));
572         }
573     }
574 
reinitializeMappingTableLocked()575     private static void reinitializeMappingTableLocked() {
576         // Android-changed: Update the table only if the OID changed. Also synchronize
577         // on oidTable for thread safety.
578         int currentVersion = Security.getVersion();
579         if (initOidTableVersion != currentVersion) {
580             Provider[] provs = Security.getProviders();
581             for (int i=0; i<provs.length; i++) {
582                 for (Enumeration<Object> enum_ = provs[i].keys();
583                      enum_.hasMoreElements(); ) {
584                     String alias = (String)enum_.nextElement();
585                     String upperCaseAlias = alias.toUpperCase(Locale.ENGLISH);
586                     int index;
587                     if (upperCaseAlias.startsWith("ALG.ALIAS")) {
588                         if ((index=upperCaseAlias.indexOf("OID.", 0)) != -1) {
589                             index += "OID.".length();
590                             if (index == alias.length()) {
591                                 // invalid alias entry
592                                 break;
593                             }
594                             String oidString = alias.substring(index);
595                             String stdAlgName = provs[i].getProperty(alias);
596                             if (stdAlgName != null) {
597                                 stdAlgName = stdAlgName.toUpperCase(Locale.ENGLISH);
598 
599                                 ObjectIdentifier oid = null;
600                                 try {
601                                     oid = new ObjectIdentifier(oidString);
602                                 } catch (IOException e) {
603                                     // Not an OID.
604                                 }
605 
606                                 if (oid != null) {
607                                     if (!oidTable.containsKey(stdAlgName)) {
608                                         oidTable.put(stdAlgName, oid);
609                                     }
610                                     if (!nameTable.containsKey(oid)) {
611                                         nameTable.put(oid, stdAlgName);
612                                     }
613                                 }
614                             }
615                         } else {
616                             // Android-changed: If the alias isn't specified with an explicit
617                             // "OID." in the name, we still attempt to parse it as one.
618                             final int sep = alias.indexOf('.', "ALG.ALIAS.".length());
619                             String suffix = alias.substring(sep + 1);
620 
621                             ObjectIdentifier oid = null;
622                             try {
623                                 oid = new ObjectIdentifier(suffix);
624                             } catch (IOException e) {
625                                 // Not an OID.
626                             }
627 
628                             if (oid != null) {
629                                 String stdAlgName = provs[i].getProperty(alias);
630                                 if (stdAlgName != null) {
631                                     stdAlgName = stdAlgName.toUpperCase(Locale.ENGLISH);
632                                     if (!oidTable.containsKey(stdAlgName)) {
633                                         oidTable.put(stdAlgName, oid);
634                                     }
635                                     if (!nameTable.containsKey(oid)) {
636                                         nameTable.put(oid, stdAlgName);
637                                     }
638                                 }
639                             }
640                         }
641                     }
642                 }
643             }
644 
645             initOidTableVersion = currentVersion;
646         }
647     }
648 
oid(int ... values)649     private static ObjectIdentifier oid(int ... values) {
650         return ObjectIdentifier.newInternal(values);
651     }
652 
653     private static int initOidTableVersion = -1;
654     private static final Map<String,ObjectIdentifier> oidTable =
655         new HashMap<String,ObjectIdentifier>(1);
656     private static final Map<ObjectIdentifier,String> nameTable =
657         new HashMap<ObjectIdentifier,String>();
658 
659     /*****************************************************************/
660 
661     /*
662      * HASHING ALGORITHMS
663      */
664 
665     /**
666      * Algorithm ID for the MD2 Message Digest Algorthm, from RFC 1319.
667      * OID = 1.2.840.113549.2.2
668      */
669     public static final ObjectIdentifier MD2_oid =
670     ObjectIdentifier.newInternal(new int[] {1, 2, 840, 113549, 2, 2});
671 
672     /**
673      * Algorithm ID for the MD5 Message Digest Algorthm, from RFC 1321.
674      * OID = 1.2.840.113549.2.5
675      */
676     public static final ObjectIdentifier MD5_oid =
677     ObjectIdentifier.newInternal(new int[] {1, 2, 840, 113549, 2, 5});
678 
679     /**
680      * Algorithm ID for the SHA1 Message Digest Algorithm, from FIPS 180-1.
681      * This is sometimes called "SHA", though that is often confusing since
682      * many people refer to FIPS 180 (which has an error) as defining SHA.
683      * OID = 1.3.14.3.2.26. Old SHA-0 OID: 1.3.14.3.2.18.
684      */
685     public static final ObjectIdentifier SHA_oid =
686     ObjectIdentifier.newInternal(new int[] {1, 3, 14, 3, 2, 26});
687 
688     public static final ObjectIdentifier SHA224_oid =
689     ObjectIdentifier.newInternal(new int[] {2, 16, 840, 1, 101, 3, 4, 2, 4});
690 
691     public static final ObjectIdentifier SHA256_oid =
692     ObjectIdentifier.newInternal(new int[] {2, 16, 840, 1, 101, 3, 4, 2, 1});
693 
694     public static final ObjectIdentifier SHA384_oid =
695     ObjectIdentifier.newInternal(new int[] {2, 16, 840, 1, 101, 3, 4, 2, 2});
696 
697     public static final ObjectIdentifier SHA512_oid =
698     ObjectIdentifier.newInternal(new int[] {2, 16, 840, 1, 101, 3, 4, 2, 3});
699 
700     /*
701      * COMMON PUBLIC KEY TYPES
702      */
703     private static final int DH_data[] = { 1, 2, 840, 113549, 1, 3, 1 };
704     private static final int DH_PKIX_data[] = { 1, 2, 840, 10046, 2, 1 };
705     private static final int DSA_OIW_data[] = { 1, 3, 14, 3, 2, 12 };
706     private static final int DSA_PKIX_data[] = { 1, 2, 840, 10040, 4, 1 };
707     private static final int RSA_data[] = { 2, 5, 8, 1, 1 };
708     private static final int RSAEncryption_data[] =
709                                  { 1, 2, 840, 113549, 1, 1, 1 };
710 
711     public static final ObjectIdentifier DH_oid;
712     public static final ObjectIdentifier DH_PKIX_oid;
713     public static final ObjectIdentifier DSA_oid;
714     public static final ObjectIdentifier DSA_OIW_oid;
715     public static final ObjectIdentifier EC_oid = oid(1, 2, 840, 10045, 2, 1);
716     public static final ObjectIdentifier ECDH_oid = oid(1, 3, 132, 1, 12);
717     public static final ObjectIdentifier RSA_oid;
718     public static final ObjectIdentifier RSAEncryption_oid;
719 
720     /*
721      * COMMON SECRET KEY TYPES
722      */
723     public static final ObjectIdentifier AES_oid =
724                                             oid(2, 16, 840, 1, 101, 3, 4, 1);
725 
726     /*
727      * COMMON SIGNATURE ALGORITHMS
728      */
729     private static final int md2WithRSAEncryption_data[] =
730                                        { 1, 2, 840, 113549, 1, 1, 2 };
731     private static final int md5WithRSAEncryption_data[] =
732                                        { 1, 2, 840, 113549, 1, 1, 4 };
733     private static final int sha1WithRSAEncryption_data[] =
734                                        { 1, 2, 840, 113549, 1, 1, 5 };
735     private static final int sha1WithRSAEncryption_OIW_data[] =
736                                        { 1, 3, 14, 3, 2, 29 };
737     private static final int sha224WithRSAEncryption_data[] =
738                                        { 1, 2, 840, 113549, 1, 1, 14 };
739     private static final int sha256WithRSAEncryption_data[] =
740                                        { 1, 2, 840, 113549, 1, 1, 11 };
741     private static final int sha384WithRSAEncryption_data[] =
742                                        { 1, 2, 840, 113549, 1, 1, 12 };
743     private static final int sha512WithRSAEncryption_data[] =
744                                        { 1, 2, 840, 113549, 1, 1, 13 };
745     private static final int shaWithDSA_OIW_data[] =
746                                        { 1, 3, 14, 3, 2, 13 };
747     private static final int sha1WithDSA_OIW_data[] =
748                                        { 1, 3, 14, 3, 2, 27 };
749     private static final int dsaWithSHA1_PKIX_data[] =
750                                        { 1, 2, 840, 10040, 4, 3 };
751 
752     public static final ObjectIdentifier md2WithRSAEncryption_oid;
753     public static final ObjectIdentifier md5WithRSAEncryption_oid;
754     public static final ObjectIdentifier sha1WithRSAEncryption_oid;
755     public static final ObjectIdentifier sha1WithRSAEncryption_OIW_oid;
756     public static final ObjectIdentifier sha224WithRSAEncryption_oid;
757     public static final ObjectIdentifier sha256WithRSAEncryption_oid;
758     public static final ObjectIdentifier sha384WithRSAEncryption_oid;
759     public static final ObjectIdentifier sha512WithRSAEncryption_oid;
760     public static final ObjectIdentifier shaWithDSA_OIW_oid;
761     public static final ObjectIdentifier sha1WithDSA_OIW_oid;
762     public static final ObjectIdentifier sha1WithDSA_oid;
763     public static final ObjectIdentifier sha224WithDSA_oid =
764                                             oid(2, 16, 840, 1, 101, 3, 4, 3, 1);
765     public static final ObjectIdentifier sha256WithDSA_oid =
766                                             oid(2, 16, 840, 1, 101, 3, 4, 3, 2);
767 
768     public static final ObjectIdentifier sha1WithECDSA_oid =
769                                             oid(1, 2, 840, 10045, 4, 1);
770     public static final ObjectIdentifier sha224WithECDSA_oid =
771                                             oid(1, 2, 840, 10045, 4, 3, 1);
772     public static final ObjectIdentifier sha256WithECDSA_oid =
773                                             oid(1, 2, 840, 10045, 4, 3, 2);
774     public static final ObjectIdentifier sha384WithECDSA_oid =
775                                             oid(1, 2, 840, 10045, 4, 3, 3);
776     public static final ObjectIdentifier sha512WithECDSA_oid =
777                                             oid(1, 2, 840, 10045, 4, 3, 4);
778     public static final ObjectIdentifier specifiedWithECDSA_oid =
779                                             oid(1, 2, 840, 10045, 4, 3);
780 
781     /**
782      * Algorithm ID for the PBE encryption algorithms from PKCS#5 and
783      * PKCS#12.
784      */
785     public static final ObjectIdentifier pbeWithMD5AndDES_oid =
786         ObjectIdentifier.newInternal(new int[]{1, 2, 840, 113549, 1, 5, 3});
787     public static final ObjectIdentifier pbeWithMD5AndRC2_oid =
788         ObjectIdentifier.newInternal(new int[] {1, 2, 840, 113549, 1, 5, 6});
789     public static final ObjectIdentifier pbeWithSHA1AndDES_oid =
790         ObjectIdentifier.newInternal(new int[] {1, 2, 840, 113549, 1, 5, 10});
791     public static final ObjectIdentifier pbeWithSHA1AndRC2_oid =
792         ObjectIdentifier.newInternal(new int[] {1, 2, 840, 113549, 1, 5, 11});
793     public static ObjectIdentifier pbeWithSHA1AndDESede_oid =
794         ObjectIdentifier.newInternal(new int[] {1, 2, 840, 113549, 1, 12, 1, 3});
795     public static ObjectIdentifier pbeWithSHA1AndRC2_40_oid =
796         ObjectIdentifier.newInternal(new int[] {1, 2, 840, 113549, 1, 12, 1, 6});
797 
798     static {
799     /*
800      * Note the preferred OIDs are named simply with no "OIW" or
801      * "PKIX" in them, even though they may point to data from these
802      * specs; e.g. SHA_oid, DH_oid, DSA_oid, SHA1WithDSA_oid...
803      */
804     /**
805      * Algorithm ID for Diffie Hellman Key agreement, from PKCS #3.
806      * Parameters include public values P and G, and may optionally specify
807      * the length of the private key X.  Alternatively, algorithm parameters
808      * may be derived from another source such as a Certificate Authority's
809      * certificate.
810      * OID = 1.2.840.113549.1.3.1
811      */
812         DH_oid = ObjectIdentifier.newInternal(DH_data);
813 
814     /**
815      * Algorithm ID for the Diffie Hellman Key Agreement (DH), from RFC 3279.
816      * Parameters may include public values P and G.
817      * OID = 1.2.840.10046.2.1
818      */
819         DH_PKIX_oid = ObjectIdentifier.newInternal(DH_PKIX_data);
820 
821     /**
822      * Algorithm ID for the Digital Signing Algorithm (DSA), from the
823      * NIST OIW Stable Agreements part 12.
824      * Parameters may include public values P, Q, and G; or these may be
825      * derived from
826      * another source such as a Certificate Authority's certificate.
827      * OID = 1.3.14.3.2.12
828      */
829         DSA_OIW_oid = ObjectIdentifier.newInternal(DSA_OIW_data);
830 
831     /**
832      * Algorithm ID for the Digital Signing Algorithm (DSA), from RFC 3279.
833      * Parameters may include public values P, Q, and G; or these may be
834      * derived from another source such as a Certificate Authority's
835      * certificate.
836      * OID = 1.2.840.10040.4.1
837      */
838         DSA_oid = ObjectIdentifier.newInternal(DSA_PKIX_data);
839 
840     /**
841      * Algorithm ID for RSA keys used for any purpose, as defined in X.509.
842      * The algorithm parameter is a single value, the number of bits in the
843      * public modulus.
844      * OID = 2.5.8.1.1
845      */
846         RSA_oid = ObjectIdentifier.newInternal(RSA_data);
847 
848     /**
849      * Algorithm ID for RSA keys used with RSA encryption, as defined
850      * in PKCS #1.  There are no parameters associated with this algorithm.
851      * OID = 1.2.840.113549.1.1.1
852      */
853         RSAEncryption_oid = ObjectIdentifier.newInternal(RSAEncryption_data);
854 
855     /**
856      * Identifies a signing algorithm where an MD2 digest is encrypted
857      * using an RSA private key; defined in PKCS #1.  Use of this
858      * signing algorithm is discouraged due to MD2 vulnerabilities.
859      * OID = 1.2.840.113549.1.1.2
860      */
861         md2WithRSAEncryption_oid =
862             ObjectIdentifier.newInternal(md2WithRSAEncryption_data);
863 
864     /**
865      * Identifies a signing algorithm where an MD5 digest is
866      * encrypted using an RSA private key; defined in PKCS #1.
867      * OID = 1.2.840.113549.1.1.4
868      */
869         md5WithRSAEncryption_oid =
870             ObjectIdentifier.newInternal(md5WithRSAEncryption_data);
871 
872     /**
873      * Identifies a signing algorithm where a SHA1 digest is
874      * encrypted using an RSA private key; defined by RSA DSI.
875      * OID = 1.2.840.113549.1.1.5
876      */
877         sha1WithRSAEncryption_oid =
878             ObjectIdentifier.newInternal(sha1WithRSAEncryption_data);
879 
880     /**
881      * Identifies a signing algorithm where a SHA1 digest is
882      * encrypted using an RSA private key; defined in NIST OIW.
883      * OID = 1.3.14.3.2.29
884      */
885         sha1WithRSAEncryption_OIW_oid =
886             ObjectIdentifier.newInternal(sha1WithRSAEncryption_OIW_data);
887 
888     /**
889      * Identifies a signing algorithm where a SHA224 digest is
890      * encrypted using an RSA private key; defined by PKCS #1.
891      * OID = 1.2.840.113549.1.1.14
892      */
893         sha224WithRSAEncryption_oid =
894             ObjectIdentifier.newInternal(sha224WithRSAEncryption_data);
895 
896     /**
897      * Identifies a signing algorithm where a SHA256 digest is
898      * encrypted using an RSA private key; defined by PKCS #1.
899      * OID = 1.2.840.113549.1.1.11
900      */
901         sha256WithRSAEncryption_oid =
902             ObjectIdentifier.newInternal(sha256WithRSAEncryption_data);
903 
904     /**
905      * Identifies a signing algorithm where a SHA384 digest is
906      * encrypted using an RSA private key; defined by PKCS #1.
907      * OID = 1.2.840.113549.1.1.12
908      */
909         sha384WithRSAEncryption_oid =
910             ObjectIdentifier.newInternal(sha384WithRSAEncryption_data);
911 
912     /**
913      * Identifies a signing algorithm where a SHA512 digest is
914      * encrypted using an RSA private key; defined by PKCS #1.
915      * OID = 1.2.840.113549.1.1.13
916      */
917         sha512WithRSAEncryption_oid =
918             ObjectIdentifier.newInternal(sha512WithRSAEncryption_data);
919 
920     /**
921      * Identifies the FIPS 186 "Digital Signature Standard" (DSS), where a
922      * SHA digest is signed using the Digital Signing Algorithm (DSA).
923      * This should not be used.
924      * OID = 1.3.14.3.2.13
925      */
926         shaWithDSA_OIW_oid = ObjectIdentifier.newInternal(shaWithDSA_OIW_data);
927 
928     /**
929      * Identifies the FIPS 186 "Digital Signature Standard" (DSS), where a
930      * SHA1 digest is signed using the Digital Signing Algorithm (DSA).
931      * OID = 1.3.14.3.2.27
932      */
933         sha1WithDSA_OIW_oid = ObjectIdentifier.newInternal(sha1WithDSA_OIW_data);
934 
935     /**
936      * Identifies the FIPS 186 "Digital Signature Standard" (DSS), where a
937      * SHA1 digest is signed using the Digital Signing Algorithm (DSA).
938      * OID = 1.2.840.10040.4.3
939      */
940         sha1WithDSA_oid = ObjectIdentifier.newInternal(dsaWithSHA1_PKIX_data);
941 
nameTable.put(MD5_oid, "MD5")942         nameTable.put(MD5_oid, "MD5");
nameTable.put(MD2_oid, "MD2")943         nameTable.put(MD2_oid, "MD2");
nameTable.put(SHA_oid, "SHA-1")944         nameTable.put(SHA_oid, "SHA-1");
nameTable.put(SHA224_oid, "SHA-224")945         nameTable.put(SHA224_oid, "SHA-224");
nameTable.put(SHA256_oid, "SHA-256")946         nameTable.put(SHA256_oid, "SHA-256");
nameTable.put(SHA384_oid, "SHA-384")947         nameTable.put(SHA384_oid, "SHA-384");
nameTable.put(SHA512_oid, "SHA-512")948         nameTable.put(SHA512_oid, "SHA-512");
nameTable.put(RSAEncryption_oid, "RSA")949         nameTable.put(RSAEncryption_oid, "RSA");
nameTable.put(RSA_oid, "RSA")950         nameTable.put(RSA_oid, "RSA");
nameTable.put(DH_oid, "Diffie-Hellman")951         nameTable.put(DH_oid, "Diffie-Hellman");
nameTable.put(DH_PKIX_oid, "Diffie-Hellman")952         nameTable.put(DH_PKIX_oid, "Diffie-Hellman");
nameTable.put(DSA_oid, "DSA")953         nameTable.put(DSA_oid, "DSA");
nameTable.put(DSA_OIW_oid, "DSA")954         nameTable.put(DSA_OIW_oid, "DSA");
nameTable.put(EC_oid, "EC")955         nameTable.put(EC_oid, "EC");
nameTable.put(ECDH_oid, "ECDH")956         nameTable.put(ECDH_oid, "ECDH");
957 
nameTable.put(AES_oid, "AES")958         nameTable.put(AES_oid, "AES");
959 
nameTable.put(sha1WithECDSA_oid, "SHA1withECDSA")960         nameTable.put(sha1WithECDSA_oid, "SHA1withECDSA");
nameTable.put(sha224WithECDSA_oid, "SHA224withECDSA")961         nameTable.put(sha224WithECDSA_oid, "SHA224withECDSA");
nameTable.put(sha256WithECDSA_oid, "SHA256withECDSA")962         nameTable.put(sha256WithECDSA_oid, "SHA256withECDSA");
nameTable.put(sha384WithECDSA_oid, "SHA384withECDSA")963         nameTable.put(sha384WithECDSA_oid, "SHA384withECDSA");
nameTable.put(sha512WithECDSA_oid, "SHA512withECDSA")964         nameTable.put(sha512WithECDSA_oid, "SHA512withECDSA");
nameTable.put(md5WithRSAEncryption_oid, "MD5withRSA")965         nameTable.put(md5WithRSAEncryption_oid, "MD5withRSA");
nameTable.put(md2WithRSAEncryption_oid, "MD2withRSA")966         nameTable.put(md2WithRSAEncryption_oid, "MD2withRSA");
nameTable.put(sha1WithDSA_oid, "SHA1withDSA")967         nameTable.put(sha1WithDSA_oid, "SHA1withDSA");
nameTable.put(sha1WithDSA_OIW_oid, "SHA1withDSA")968         nameTable.put(sha1WithDSA_OIW_oid, "SHA1withDSA");
nameTable.put(shaWithDSA_OIW_oid, "SHA1withDSA")969         nameTable.put(shaWithDSA_OIW_oid, "SHA1withDSA");
nameTable.put(sha224WithDSA_oid, "SHA224withDSA")970         nameTable.put(sha224WithDSA_oid, "SHA224withDSA");
nameTable.put(sha256WithDSA_oid, "SHA256withDSA")971         nameTable.put(sha256WithDSA_oid, "SHA256withDSA");
nameTable.put(sha1WithRSAEncryption_oid, "SHA1withRSA")972         nameTable.put(sha1WithRSAEncryption_oid, "SHA1withRSA");
nameTable.put(sha1WithRSAEncryption_OIW_oid, "SHA1withRSA")973         nameTable.put(sha1WithRSAEncryption_OIW_oid, "SHA1withRSA");
nameTable.put(sha224WithRSAEncryption_oid, "SHA224withRSA")974         nameTable.put(sha224WithRSAEncryption_oid, "SHA224withRSA");
nameTable.put(sha256WithRSAEncryption_oid, "SHA256withRSA")975         nameTable.put(sha256WithRSAEncryption_oid, "SHA256withRSA");
nameTable.put(sha384WithRSAEncryption_oid, "SHA384withRSA")976         nameTable.put(sha384WithRSAEncryption_oid, "SHA384withRSA");
nameTable.put(sha512WithRSAEncryption_oid, "SHA512withRSA")977         nameTable.put(sha512WithRSAEncryption_oid, "SHA512withRSA");
nameTable.put(pbeWithMD5AndDES_oid, "PBEWithMD5AndDES")978         nameTable.put(pbeWithMD5AndDES_oid, "PBEWithMD5AndDES");
nameTable.put(pbeWithMD5AndRC2_oid, "PBEWithMD5AndRC2")979         nameTable.put(pbeWithMD5AndRC2_oid, "PBEWithMD5AndRC2");
nameTable.put(pbeWithSHA1AndDES_oid, "PBEWithSHA1AndDES")980         nameTable.put(pbeWithSHA1AndDES_oid, "PBEWithSHA1AndDES");
nameTable.put(pbeWithSHA1AndRC2_oid, "PBEWithSHA1AndRC2")981         nameTable.put(pbeWithSHA1AndRC2_oid, "PBEWithSHA1AndRC2");
nameTable.put(pbeWithSHA1AndDESede_oid, "PBEWithSHA1AndDESede")982         nameTable.put(pbeWithSHA1AndDESede_oid, "PBEWithSHA1AndDESede");
nameTable.put(pbeWithSHA1AndRC2_40_oid, "PBEWithSHA1AndRC2_40")983         nameTable.put(pbeWithSHA1AndRC2_40_oid, "PBEWithSHA1AndRC2_40");
984     }
985 
986     /**
987      * Creates a signature algorithm name from a digest algorithm
988      * name and a encryption algorithm name.
989      */
makeSigAlg(String digAlg, String encAlg)990     public static String makeSigAlg(String digAlg, String encAlg) {
991         digAlg = digAlg.replace("-", "");
992         if (encAlg.equalsIgnoreCase("EC")) encAlg = "ECDSA";
993 
994         return digAlg + "with" + encAlg;
995     }
996 
997     /**
998      * Extracts the encryption algorithm name from a signature
999      * algorithm name.
1000       */
getEncAlgFromSigAlg(String signatureAlgorithm)1001     public static String getEncAlgFromSigAlg(String signatureAlgorithm) {
1002         signatureAlgorithm = signatureAlgorithm.toUpperCase(Locale.ENGLISH);
1003         int with = signatureAlgorithm.indexOf("WITH");
1004         String keyAlgorithm = null;
1005         if (with > 0) {
1006             int and = signatureAlgorithm.indexOf("AND", with + 4);
1007             if (and > 0) {
1008                 keyAlgorithm = signatureAlgorithm.substring(with + 4, and);
1009             } else {
1010                 keyAlgorithm = signatureAlgorithm.substring(with + 4);
1011             }
1012             if (keyAlgorithm.equalsIgnoreCase("ECDSA")) {
1013                 keyAlgorithm = "EC";
1014             }
1015         }
1016         return keyAlgorithm;
1017     }
1018 
1019     /**
1020      * Extracts the digest algorithm name from a signature
1021      * algorithm name.
1022       */
getDigAlgFromSigAlg(String signatureAlgorithm)1023     public static String getDigAlgFromSigAlg(String signatureAlgorithm) {
1024         signatureAlgorithm = signatureAlgorithm.toUpperCase(Locale.ENGLISH);
1025         int with = signatureAlgorithm.indexOf("WITH");
1026         if (with > 0) {
1027             return signatureAlgorithm.substring(0, with);
1028         }
1029         return null;
1030     }
1031 }
1032