FileDocCategorySizeDatePackage
Signature.javaAPI DocJava SE 6 API42195Tue Jun 10 00:25:46 BST 2008java.security

Signature

public abstract class Signature extends SignatureSpi
This Signature class is used to provide applications the functionality of a digital signature algorithm. Digital signatures are used for authentication and integrity assurance of digital data.

The signature algorithm can be, among others, the NIST standard DSA, using DSA and SHA-1. The DSA algorithm using the SHA-1 message digest algorithm can be specified as SHA1withDSA. In the case of RSA, there are multiple choices for the message digest algorithm, so the signing algorithm could be specified as, for example, MD2withRSA, MD5withRSA, or SHA1withRSA. The algorithm name must be specified, as there is no default.

A Signature object can be used to generate and verify digital signatures.

There are three phases to the use of a Signature object for either signing data or verifying a signature:

  1. Initialization, with either
    • a public key, which initializes the signature for verification (see {@link #initVerify(PublicKey) initVerify}), or
    • a private key (and optionally a Secure Random Number Generator), which initializes the signature for signing (see {@link #initSign(PrivateKey)} and {@link #initSign(PrivateKey, SecureRandom)}).

  2. Updating

    Depending on the type of initialization, this will update the bytes to be signed or verified. See the {@link #update(byte) update} methods.

  3. Signing or Verifying a signature on all updated bytes. See the {@link #sign() sign} methods and the {@link #verify(byte[]) verify} method.

Note that this class is abstract and extends from SignatureSpi for historical reasons. Application developers should only take notice of the methods defined in this Signature class; all the methods in the superclass are intended for cryptographic service providers who wish to supply their own implementations of digital signature algorithms.

author
Benjamin Renaud
version
1.103, 04/21/06

Fields Summary
private static final Debug
debug
private String
algorithm
Provider
provider
protected static final int
UNINITIALIZED
Possible {@link #state} value, signifying that this signature object has not yet been initialized.
protected static final int
SIGN
Possible {@link #state} value, signifying that this signature object has been initialized for signing.
protected static final int
VERIFY
Possible {@link #state} value, signifying that this signature object has been initialized for verification.
protected int
state
Current state of this signature object.
private static final String
RSA_SIGNATURE
private static final String
RSA_CIPHER
private static final List
rsaIds
private static final Map
signatureInfo
Constructors Summary
protected Signature(String algorithm)
Creates a Signature object for the specified algorithm.

param
algorithm the standard string name of the algorithm. See Appendix A in the Java Cryptography Architecture API Specification & Reference for information about standard algorithm names.


                                                  
       
	this.algorithm = algorithm;
    
Methods Summary
voidchooseFirstProvider()

	// empty, overridden in Delegate
    
public java.lang.Objectclone()
Returns a clone if the implementation is cloneable.

return
a clone if the implementation is cloneable.
exception
CloneNotSupportedException if this is called on an implementation that does not support Cloneable.

	if (this instanceof Cloneable) {
	    return super.clone();
	} else {
	    throw new CloneNotSupportedException();
	}
    
public final java.lang.StringgetAlgorithm()
Returns the name of the algorithm for this signature object.

return
the name of the algorithm for this signature object.

	return this.algorithm;
    
public static java.security.SignaturegetInstance(java.lang.String algorithm)
Returns a Signature object that implements the specified signature algorithm.

This method traverses the list of registered security Providers, starting with the most preferred Provider. A new Signature object encapsulating the SignatureSpi implementation from the first Provider that supports the specified algorithm is returned.

Note that the list of registered providers may be retrieved via the {@link Security#getProviders() Security.getProviders()} method.

param
algorithm the standard name of the algorithm requested. See Appendix A in the Java Cryptography Architecture API Specification & Reference for information about standard algorithm names.
return
the new Signature object.
exception
NoSuchAlgorithmException if no Provider supports a Signature implementation for the specified algorithm.
see
Provider


                                                                                                                                              
         
	      
	List list;
	if (algorithm.equalsIgnoreCase(RSA_SIGNATURE)) {
	    list = GetInstance.getServices(rsaIds);
	} else {
	    list = GetInstance.getServices("Signature", algorithm);
	}
	Iterator t = list.iterator();
	if (t.hasNext() == false) {
	    throw new NoSuchAlgorithmException
	    	(algorithm + " Signature not available");
	}
	// try services until we find an Spi or a working Signature subclass
	NoSuchAlgorithmException failure;
	do {
	    Service s = (Service)t.next();
	    if (isSpi(s)) {
		return new Delegate(s, t, algorithm);
	    } else {
		// must be a subclass of Signature, disable dynamic selection
		try {
		    Instance instance = 
		    	GetInstance.getInstance(s, SignatureSpi.class);
		    return getInstance(instance, algorithm);
		} catch (NoSuchAlgorithmException e) {
		    failure = e;
		}
	    }
	} while (t.hasNext());
	throw failure;
    
private static java.security.SignaturegetInstance(sun.security.jca.GetInstance.Instance instance, java.lang.String algorithm)

	Signature sig;
	if (instance.impl instanceof Signature) {
	    sig = (Signature)instance.impl;
	} else {
	    SignatureSpi spi = (SignatureSpi)instance.impl;
	    sig = new Delegate(spi, algorithm);
	}
	sig.provider = instance.provider;
	return sig;
    
public static java.security.SignaturegetInstance(java.lang.String algorithm, java.lang.String provider)
Returns a Signature object that implements the specified signature algorithm.

A new Signature object encapsulating the SignatureSpi implementation from the specified provider is returned. The specified provider must be registered in the security provider list.

Note that the list of registered providers may be retrieved via the {@link Security#getProviders() Security.getProviders()} method.

param
algorithm the name of the algorithm requested. See Appendix A in the Java Cryptography Architecture API Specification & Reference for information about standard algorithm names.
param
provider the name of the provider.
return
the new Signature object.
exception
NoSuchAlgorithmException if a SignatureSpi implementation for the specified algorithm is not available from the specified provider.
exception
NoSuchProviderException if the specified provider is not registered in the security provider list.
exception
IllegalArgumentException if the provider name is null or empty.
see
Provider

	if (algorithm.equalsIgnoreCase(RSA_SIGNATURE)) {
	    // exception compatibility with existing code
	    if ((provider == null) || (provider.length() == 0)) {
		throw new IllegalArgumentException("missing provider");
	    }
	    Provider p = Security.getProvider(provider);
	    if (p == null) {
		throw new NoSuchProviderException
		    ("no such provider: " + provider);
	    }
	    return getInstanceRSA(p);
	}
	Instance instance = GetInstance.getInstance
		("Signature", SignatureSpi.class, algorithm, provider);
	return getInstance(instance, algorithm);
    
public static java.security.SignaturegetInstance(java.lang.String algorithm, java.security.Provider provider)
Returns a Signature object that implements the specified signature algorithm.

A new Signature object encapsulating the SignatureSpi implementation from the specified Provider object is returned. Note that the specified Provider object does not have to be registered in the provider list.

param
algorithm the name of the algorithm requested. See Appendix A in the Java Cryptography Architecture API Specification & Reference for information about standard algorithm names.
param
provider the provider.
return
the new Signature object.
exception
NoSuchAlgorithmException if a SignatureSpi implementation for the specified algorithm is not available from the specified Provider object.
exception
IllegalArgumentException if the provider is null.
see
Provider
since
1.4

	if (algorithm.equalsIgnoreCase(RSA_SIGNATURE)) {
	    // exception compatibility with existing code
	    if (provider == null) {
		throw new IllegalArgumentException("missing provider");
	    }
	    return getInstanceRSA(provider);
	}
	Instance instance = GetInstance.getInstance
		("Signature", SignatureSpi.class, algorithm, provider);
	return getInstance(instance, algorithm);
    
private static java.security.SignaturegetInstanceRSA(java.security.Provider p)

	// try Signature first
	Service s = p.getService("Signature", RSA_SIGNATURE);
	if (s != null) {
	    Instance instance = GetInstance.getInstance(s, SignatureSpi.class);
	    return getInstance(instance, RSA_SIGNATURE);
	}
	// check Cipher
	try {
	    Cipher c = Cipher.getInstance(RSA_CIPHER, p);
	    return new Delegate(new CipherAdapter(c), RSA_SIGNATURE);
	} catch (GeneralSecurityException e) {
	    // throw Signature style exception message to avoid confusion,
	    // but append Cipher exception as cause
	    throw new NoSuchAlgorithmException("no such algorithm: "
		+ RSA_SIGNATURE + " for provider " + p.getName(), e);
	}
    
public final java.lang.ObjectgetParameter(java.lang.String param)
Gets the value of the specified algorithm parameter. This method supplies a general-purpose mechanism through which it is possible to get the various parameters of this object. A parameter may be any settable parameter for the algorithm, such as a parameter size, or a source of random bits for signature generation (if appropriate), or an indication of whether or not to perform a specific but optional computation. A uniform algorithm-specific naming scheme for each parameter is desirable but left unspecified at this time.

param
param the string name of the parameter.
return
the object that represents the parameter value, or null if there is none.
exception
InvalidParameterException if param is an invalid parameter for this engine, or another exception occurs while trying to get this parameter.
see
#setParameter(String, Object)
deprecated

	return engineGetParameter(param);
    
public final java.security.AlgorithmParametersgetParameters()
Returns the parameters used with this signature object.

The returned parameters may be the same that were used to initialize this signature, or may contain a combination of default and randomly generated parameter values used by the underlying signature implementation if this signature requires algorithm parameters but was not initialized with any.

return
the parameters used with this signature, or null if this signature does not use any parameters.
see
#setParameter(AlgorithmParameterSpec)
since
1.4

	return engineGetParameters();
    
public final java.security.ProvidergetProvider()
Returns the provider of this signature object.

return
the provider of this signature object

	chooseFirstProvider();
	return this.provider;
    
public final voidinitSign(java.security.PrivateKey privateKey)
Initialize this object for signing. If this method is called again with a different argument, it negates the effect of this call.

param
privateKey the private key of the identity whose signature is going to be generated.
exception
InvalidKeyException if the key is invalid.

	engineInitSign(privateKey);
	state = SIGN;
    
public final voidinitSign(java.security.PrivateKey privateKey, java.security.SecureRandom random)
Initialize this object for signing. If this method is called again with a different argument, it negates the effect of this call.

param
privateKey the private key of the identity whose signature is going to be generated.
param
random the source of randomness for this signature.
exception
InvalidKeyException if the key is invalid.

	engineInitSign(privateKey, random);
	state = SIGN;
    
public final voidinitVerify(java.security.PublicKey publicKey)
Initializes this object for verification. If this method is called again with a different argument, it negates the effect of this call.

param
publicKey the public key of the identity whose signature is going to be verified.
exception
InvalidKeyException if the key is invalid.

	engineInitVerify(publicKey);
	state = VERIFY;
    
public final voidinitVerify(java.security.cert.Certificate certificate)
Initializes this object for verification, using the public key from the given certificate.

If the certificate is of type X.509 and has a key usage extension field marked as critical, and the value of the key usage extension field implies that the public key in the certificate and its corresponding private key are not supposed to be used for digital signatures, an InvalidKeyException is thrown.

param
certificate the certificate of the identity whose signature is going to be verified.
exception
InvalidKeyException if the public key in the certificate is not encoded properly or does not include required parameter information or cannot be used for digital signature purposes.
since
1.3

	// If the certificate is of type X509Certificate,
	// we should check whether it has a Key Usage
	// extension marked as critical.
	if (certificate instanceof java.security.cert.X509Certificate) {
	    // Check whether the cert has a key usage extension
	    // marked as a critical extension.
	    // The OID for KeyUsage extension is 2.5.29.15.
	    X509Certificate cert = (X509Certificate)certificate;
	    Set critSet = cert.getCriticalExtensionOIDs();

	    if (critSet != null && !critSet.isEmpty()
		&& critSet.contains("2.5.29.15")) {
		boolean[] keyUsageInfo = cert.getKeyUsage();
		// keyUsageInfo[0] is for digitalSignature.
		if ((keyUsageInfo != null) && (keyUsageInfo[0] == false))
		    throw new InvalidKeyException("Wrong key usage");
	    }
	}
	    
	PublicKey publicKey = certificate.getPublicKey();
	engineInitVerify(publicKey);
	state = VERIFY;
    
private static booleanisSpi(java.security.Provider.Service s)

    	signatureInfo = new ConcurrentHashMap<String,Boolean>();
	Boolean TRUE = Boolean.TRUE;
	// pre-initialize with values for our SignatureSpi implementations
	signatureInfo.put("sun.security.provider.DSA$RawDSA", TRUE);
	signatureInfo.put("sun.security.provider.DSA$SHA1withDSA", TRUE);
	signatureInfo.put("sun.security.rsa.RSASignature$MD2withRSA", TRUE);
	signatureInfo.put("sun.security.rsa.RSASignature$MD5withRSA", TRUE);
	signatureInfo.put("sun.security.rsa.RSASignature$SHA1withRSA", TRUE);
	signatureInfo.put("sun.security.rsa.RSASignature$SHA256withRSA", TRUE);
	signatureInfo.put("sun.security.rsa.RSASignature$SHA384withRSA", TRUE);
	signatureInfo.put("sun.security.rsa.RSASignature$SHA512withRSA", TRUE);
	signatureInfo.put("com.sun.net.ssl.internal.ssl.RSASignature", TRUE);
	signatureInfo.put("sun.security.pkcs11.P11Signature", TRUE);
    
	if (s.getType().equals("Cipher")) {
	    // must be a CipherSpi, which we can wrap with the CipherAdapter
	    return true;
	}
	String className = s.getClassName();
	Boolean result = signatureInfo.get(className);
	if (result == null) {
	    try {
		Object instance = s.newInstance(null);
		// Signature extends SignatureSpi
		// so it is a "real" Spi if it is an 
		// instance of SignatureSpi but not Signature
		boolean r = (instance instanceof SignatureSpi) 
				&& (instance instanceof Signature == false);
		if ((debug != null) && (r == false)) {
		    debug.println("Not a SignatureSpi " + className);
		    debug.println("Delayed provider selection may not be "
		    	+ "available for algorithm " + s.getAlgorithm());
		}
		result = Boolean.valueOf(r);
		signatureInfo.put(className, result);
	    } catch (Exception e) {
		// something is wrong, assume not an SPI
		return false;
	    }
	}
	return result.booleanValue();
    
public final voidsetParameter(java.lang.String param, java.lang.Object value)
Sets the specified algorithm parameter to the specified value. This method supplies a general-purpose mechanism through which it is possible to set the various parameters of this object. A parameter may be any settable parameter for the algorithm, such as a parameter size, or a source of random bits for signature generation (if appropriate), or an indication of whether or not to perform a specific but optional computation. A uniform algorithm-specific naming scheme for each parameter is desirable but left unspecified at this time.

param
param the string identifier of the parameter.
param
value the parameter value.
exception
InvalidParameterException if param is an invalid parameter for this signature algorithm engine, the parameter is already set and cannot be set again, a security exception occurs, and so on.
see
#getParameter
deprecated
Use {@link #setParameter(java.security.spec.AlgorithmParameterSpec) setParameter}.

	engineSetParameter(param, value);
    
public final voidsetParameter(java.security.spec.AlgorithmParameterSpec params)
Initializes this signature engine with the specified parameter set.

param
params the parameters
exception
InvalidAlgorithmParameterException if the given parameters are inappropriate for this signature engine
see
#getParameters

	engineSetParameter(params);
    
public final byte[]sign()
Returns the signature bytes of all the data updated. The format of the signature depends on the underlying signature scheme.

A call to this method resets this signature object to the state it was in when previously initialized for signing via a call to initSign(PrivateKey). That is, the object is reset and available to generate another signature from the same signer, if desired, via new calls to update and sign.

return
the signature bytes of the signing operation's result.
exception
SignatureException if this signature object is not initialized properly or if this signature algorithm is unable to process the input data provided.

	if (state == SIGN) {
	    return engineSign();
	}
	throw new SignatureException("object not initialized for " +
				     "signing");
    
public final intsign(byte[] outbuf, int offset, int len)
Finishes the signature operation and stores the resulting signature bytes in the provided buffer outbuf, starting at offset. The format of the signature depends on the underlying signature scheme.

This signature object is reset to its initial state (the state it was in after a call to one of the initSign methods) and can be reused to generate further signatures with the same private key.

param
outbuf buffer for the signature result.
param
offset offset into outbuf where the signature is stored.
param
len number of bytes within outbuf allotted for the signature.
return
the number of bytes placed into outbuf.
exception
SignatureException if this signature object is not initialized properly, if this signature algorithm is unable to process the input data provided, or if len is less than the actual signature length.
since
1.2

	if (outbuf == null) {
	    throw new IllegalArgumentException("No output buffer given");
	}
	if (outbuf.length - offset < len) {
	    throw new IllegalArgumentException
		("Output buffer too small for specified offset and length");
	}
	if (state != SIGN) {
	    throw new SignatureException("object not initialized for " +
					 "signing");
	}
	return engineSign(outbuf, offset, len);
    
public java.lang.StringtoString()
Returns a string representation of this signature object, providing information that includes the state of the object and the name of the algorithm used.

return
a string representation of this signature object.

	String initState = "";
	switch (state) {
	case UNINITIALIZED:
	    initState = "<not initialized>";
	    break;
	case VERIFY:
	    initState = "<initialized for verifying>";
	    break;	      
	case SIGN:
	    initState = "<initialized for signing>";
	    break;	      
	}
	return "Signature object: " + getAlgorithm() + initState;
    
public final voidupdate(byte b)
Updates the data to be signed or verified by a byte.

param
b the byte to use for the update.
exception
SignatureException if this signature object is not initialized properly.

	if (state == VERIFY || state == SIGN) {
	    engineUpdate(b);
	} else {
	    throw new SignatureException("object not initialized for "
					 + "signature or verification");
	}
    
public final voidupdate(byte[] data)
Updates the data to be signed or verified, using the specified array of bytes.

param
data the byte array to use for the update.
exception
SignatureException if this signature object is not initialized properly.

	update(data, 0, data.length);
    
public final voidupdate(byte[] data, int off, int len)
Updates the data to be signed or verified, using the specified array of bytes, starting at the specified offset.

param
data the array of bytes.
param
off the offset to start from in the array of bytes.
param
len the number of bytes to use, starting at offset.
exception
SignatureException if this signature object is not initialized properly.

	if (state == SIGN || state == VERIFY) {
	    engineUpdate(data, off, len);
	} else {
	    throw new SignatureException("object not initialized for "
					 + "signature or verification");
	}
    
public final voidupdate(java.nio.ByteBuffer data)
Updates the data to be signed or verified using the specified ByteBuffer. Processes the data.remaining() bytes starting at at data.position(). Upon return, the buffer's position will be equal to its limit; its limit will not have changed.

param
data the ByteBuffer
exception
SignatureException if this signature object is not initialized properly.
since
1.5

	if ((state != SIGN) && (state != VERIFY)) {
	    throw new SignatureException("object not initialized for "
					 + "signature or verification");
	}
	if (data == null) {
	    throw new NullPointerException();
	}
	engineUpdate(data);
    
public final booleanverify(byte[] signature)
Verifies the passed-in signature.

A call to this method resets this signature object to the state it was in when previously initialized for verification via a call to initVerify(PublicKey). That is, the object is reset and available to verify another signature from the identity whose public key was specified in the call to initVerify.

param
signature the signature bytes to be verified.
return
true if the signature was verified, false if not.
exception
SignatureException if this signature object is not initialized properly, the passed-in signature is improperly encoded or of the wrong type, if this signature algorithm is unable to process the input data provided, etc.

	if (state == VERIFY) {
	    return engineVerify(signature);
	}
	throw new SignatureException("object not initialized for " +
				     "verification");
    
public final booleanverify(byte[] signature, int offset, int length)
Verifies the passed-in signature in the specified array of bytes, starting at the specified offset.

A call to this method resets this signature object to the state it was in when previously initialized for verification via a call to initVerify(PublicKey). That is, the object is reset and available to verify another signature from the identity whose public key was specified in the call to initVerify.

param
signature the signature bytes to be verified.
param
offset the offset to start from in the array of bytes.
param
length the number of bytes to use, starting at offset.
return
true if the signature was verified, false if not.
exception
SignatureException if this signature object is not initialized properly, the passed-in signature is improperly encoded or of the wrong type, if this signature algorithm is unable to process the input data provided, etc.
exception
IllegalArgumentException if the signature byte array is null, or the offset or length is less than 0, or the sum of the offset and length is greater than the length of the signature byte array.
since
1.4

	if (state == VERIFY) {
	    if ((signature == null) || (offset < 0) || (length < 0) ||
		(offset + length > signature.length)) {
		throw new IllegalArgumentException("Bad arguments");
	    }

	    return engineVerify(signature, offset, length);
	}
	throw new SignatureException("object not initialized for " +
				     "verification");