algorithmid.java

来自「This is a resource based on j2me embedde」· Java 代码 · 共 774 行 · 第 1/2 页

JAVA
774
字号
/* * @(#)AlgorithmId.java	1.93 06/10/11 * * Copyright  1990-2008 Sun Microsystems, Inc. All Rights Reserved.   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER   *    * This program is free software; you can redistribute it and/or   * modify it under the terms of the GNU General Public License version   * 2 only, as published by the Free Software Foundation.    *    * This program is distributed in the hope that it will be useful, but   * WITHOUT ANY WARRANTY; without even the implied warranty of   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU   * General Public License version 2 for more details (a copy is   * included at /legal/license.txt).    *    * You should have received a copy of the GNU General Public License   * version 2 along with this work; if not, write to the Free Software   * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA   * 02110-1301 USA    *    * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa   * Clara, CA 95054 or visit www.sun.com if you need additional   * information or have any questions.  * */package sun.security.x509;import java.io.*;import java.security.*;import java.util.Hashtable;import java.util.Enumeration;import sun.security.util.*;/** * This class identifies algorithms, such as cryptographic transforms, each * of which may be associated with parameters.  Instances of this base class * are used when this runtime environment has no special knowledge of the * algorithm type, and may also be used in other cases.  Equivalence is * defined according to OID and (where relevant) parameters. * * <P>Subclasses may be used, for example when when the algorithm ID has * associated parameters which some code (e.g. code using public keys) needs * to have parsed.  Two examples of such algorithms are Diffie-Hellman key * exchange, and the Digital Signature Standard Algorithm (DSS/DSA). * * <P>The OID constants defined in this class correspond to some widely * used algorithms, for which conventional string names have been defined. * This class is not a general repository for OIDs, or for such string names. * Note that the mappings between algorithm IDs and algorithm names is * not one-to-one. * * @version 1.84 * * @author David Brownell * @author Amit Kapoor * @author Hemma Prafullchandra */public class AlgorithmId implements Serializable, DerEncoder {    /** use serialVersionUID from JDK 1.1. for interoperability */    private static final long serialVersionUID = 7205873507486557157L;    private static boolean initOidTable = false;    private static Hashtable oidTable;    /**     * The object identitifer being used for this algorithm.     */    private ObjectIdentifier	algid;    // The (parsed) parameters    private AlgorithmParameters algParams;    private boolean constructedFromDer = true;    /**     * Parameters for this algorithm.  These are stored in unparsed     * DER-encoded form; subclasses can be made to automaticaly parse     * them so there is fast access to these parameters.     */    protected DerValue		params;    /**     * Returns one of the algorithm IDs most commonly associated     * with this algorithm name.     *     * @param algname the name being used     * @deprecated use the short get form of this method.     * @exception NoSuchAlgorithmException on error.     */    public static AlgorithmId getAlgorithmId(String algname)    throws NoSuchAlgorithmException    {	return get(algname);    }    public AlgorithmParameters getParameters() {	return this.algParams;    }    /**     * Returns one of the algorithm IDs most commonly associated     * with this algorithm name.     *     * @param algname the name being used     * @exception NoSuchAlgorithmException on error.     */    public static AlgorithmId get(String algname)    throws NoSuchAlgorithmException    {	ObjectIdentifier oid = null;	try {	    oid = algOID(algname);	} catch (IOException ioe) {	    throw new NoSuchAlgorithmException		("Invalid ObjectIdentifier " + algname);	}	if (oid == null)	    throw new NoSuchAlgorithmException		("unrecognized algorithm name: " + algname);	return new AlgorithmId(oid);    }    /**     * Returns one of the algorithm IDs most commonly associated     * with this algorithm parameters.     *     * @param algparams the associated algorithm parameters.     * @exception NoSuchAlgorithmException on error.     */    public static AlgorithmId get(AlgorithmParameters algparams)    throws NoSuchAlgorithmException    {        ObjectIdentifier oid = null;	String algname = algparams.getAlgorithm();        try {            oid = algOID(algname);       } catch (IOException ioe) {            throw new NoSuchAlgorithmException                ("Invalid ObjectIdentifier " + algname);        }	if (oid == null) {	    throw new NoSuchAlgorithmException                ("unrecognized algorithm name: " + algname);	}        return new AlgorithmId(oid, algparams);     }    /**     * Parse (unmarshal) an ID from a DER sequence input value.  This form     * parsing might be used when expanding a value which has already been     * partially unmarshaled as a set or sequence member.     *     * @exception IOException on error.     * @param val the input value, which contains the algid and, if     *		there are any parameters, those parameters.     * @return an ID for the algorithm.  If the system is configured     * 		appropriately, this may be an instance of a class     *		with some kind of special support for this algorithm.     *		In that case, you may "narrow" the type of the ID.     */    public static AlgorithmId parse(DerValue val)    throws IOException    {	if (val.tag != DerValue.tag_Sequence)	    throw new IOException("algid parse error, not a sequence");	/*	 * Get the algorithm ID and any parameters.	 */	ObjectIdentifier	algid;	DerValue		params;	DerInputStream		in = val.toDerInputStream();	algid = in.getOID();	if (in.available() == 0)	    params = null;	else {	    params = in.getDerValue();	    if (params.tag == DerValue.tag_Null)		params = null;	}	/*	 * Figure out what class (if any) knows about this oid's	 * parameters.  Make one, and give it the data to decode.	 */	AlgorithmId alg = new AlgorithmId(algid, params);        if (params != null)	    alg.decodeParams();	return alg;    }    /**     * Constructs a parameterless algorithm ID.     *     * @param oid the identifier for the algorithm     */    public AlgorithmId(ObjectIdentifier oid) {	algid = oid;    }    /**     * Constructs an algorithm ID with algorithm parameters.     *     * @param oid the identifier for the algorithm.     * @param algparams the associated algorithm parameters.     */    public AlgorithmId(ObjectIdentifier oid,	AlgorithmParameters algparams) {        algid = oid;	algParams = algparams;	constructedFromDer = false;    }                 private AlgorithmId(ObjectIdentifier oid, DerValue params)    throws IOException {	this.algid = oid;	this.params = params;        if (this.params != null)	    decodeParams();    }    /**     * Constructs an algorithm ID which will be initialized     * separately, for example by deserialization.     * @deprecated use one of the other constructors.     */    public AlgorithmId() { }    protected void decodeParams() throws IOException {	try {	    this.algParams = AlgorithmParameters.getInstance		(this.algid.toString());	} catch (NoSuchAlgorithmException e) {	    /*	     * This algorithm parameter type is not supported, so we cannot	     * parse the parameters.	     */	    this.algParams = null;	    return;	}	// Decode (parse) the parameters	this.algParams.init(this.params.toByteArray());    }    /**     * Marshal a DER-encoded "AlgorithmID" sequence on the DER stream.     */    public final void encode(DerOutputStream out)    throws IOException    {	derEncode(out);    }    /**     * DER encode this object onto an output stream.     * Implements the <code>DerEncoder</code> interface.     *     * @param out     * the output stream on which to write the DER encoding.     *     * @exception IOException on encoding error.     */    public void derEncode (OutputStream out) throws IOException    {	DerOutputStream	bytes = new DerOutputStream();	DerOutputStream	tmp = new DerOutputStream();	bytes.putOID(algid);	// Setup params from algParams since no DER encoding is given	if (constructedFromDer == false) {	    if (algParams != null) {		params = new DerValue(algParams.getEncoded());	    } else {		params = null;	    }	}	if (params == null)	    bytes.putNull();	else	    bytes.putDerValue(params);	tmp.write(DerValue.tag_Sequence, bytes);	out.write(tmp.toByteArray());    }// FIXME: cleaning required    /**     * Returns the DER-encoded X.509 AlgorithmId as a byte array.     */    public final byte[] encode() throws IOException    {	DerOutputStream out = new DerOutputStream ();	DerOutputStream bytes = new DerOutputStream ();	bytes.putOID(algid);	if (params == null)	    bytes.putNull();	else	    bytes.putDerValue(params);	out.write(DerValue.tag_Sequence, bytes);	return out.toByteArray();    }    /*     * Translates from some common algorithm names to the     * OID with which they're usually associated ... this mapping     * is the reverse of the one below, except in those cases     * where synonyms are supported or where a given algorithm     * is commonly associated with multiple OIDs.     *     * TODO: This method needs to be enhanced so that we can also pass the     * scope of the algorithm name to it, e.g., the algorithm name "DSA"     * may have a different OID when used as a "Signature" algorithm than when     * used as a "KeyPairGenerator" algorithm.     */    private static ObjectIdentifier algOID (String name) 	throws IOException    {	// See if algname is in printable OID ("dot-dot") notation	if (name.indexOf('.') != -1) {	    if (name.startsWith("OID."))		return new ObjectIdentifier(name.substring("OID.".length()));	    else		return new ObjectIdentifier(name);	}	// Digesting algorithms	if (name.equalsIgnoreCase("MD5"))	    return AlgorithmId.MD5_oid;	if (name.equalsIgnoreCase("MD2"))	    return AlgorithmId.MD2_oid;	if (name.equalsIgnoreCase("SHA") || name.equalsIgnoreCase("SHA1")	    || name.equalsIgnoreCase("SHA-1"))	    return AlgorithmId.SHA_oid;	// Various public key algorithms	if (name.equalsIgnoreCase("RSA"))	    return AlgorithmId.RSAEncryption_oid;	if (name.equalsIgnoreCase("Diffie-Hellman")	    || name.equalsIgnoreCase("DH"))	     return AlgorithmId.DH_oid;	if (name.equalsIgnoreCase("DSA"))	    return AlgorithmId.DSA_oid;	// Common signature types	if (name.equalsIgnoreCase("MD5withRSA")	    || name.equalsIgnoreCase("MD5/RSA"))	    return AlgorithmId.md5WithRSAEncryption_oid;	if (name.equalsIgnoreCase("MD2withRSA")	    || name.equalsIgnoreCase("MD2/RSA"))	    return AlgorithmId.md2WithRSAEncryption_oid;	if (name.equalsIgnoreCase("SHAwithDSA")	    || name.equalsIgnoreCase("SHA1withDSA")            || name.equalsIgnoreCase("SHA/DSA")	    || name.equalsIgnoreCase("SHA1/DSA")	    || name.equalsIgnoreCase("DSAWithSHA1"))	    return AlgorithmId.sha1WithDSA_oid;	if (name.equalsIgnoreCase("SHA1WithRSA")	    || name.equalsIgnoreCase("SHA1/RSA"))	    return AlgorithmId.sha1WithRSAEncryption_oid;	// See if any of the installed providers supply a mapping from	// the given algorithm name to an OID string	String oidString;	if (!initOidTable) {	    Provider[] provs = Security.getProviders();	    for (int i=0; i<provs.length; i++) {		for (Enumeration enum_ = provs[i].keys();		     enum_.hasMoreElements(); ) {		    String alias = (String)enum_.nextElement();		    int index;		    if (alias.toUpperCase().startsWith("ALG.ALIAS") &&			(index=alias.toUpperCase().indexOf("OID.", 0)) != -1) {			index += "OID.".length();			if (index == alias.length()) {			    // invalid alias entry			    break;

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?