/* * Copyright (c) 1996, 2015, Oracle and/or its affiliates. All rights reserved. * Copyright (C) 2014 The Android Open Source Project * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code 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. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 in the LICENSE file that * accompanied this code). * * 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.security; import java.security.spec.AlgorithmParameterSpec; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.io.*; import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.nio.ByteBuffer; import java.security.Provider.Service; import javax.crypto.Cipher; import javax.crypto.CipherSpi; import javax.crypto.IllegalBlockSizeException; import javax.crypto.BadPaddingException; import javax.crypto.NoSuchPaddingException; import sun.security.jca.*; import sun.security.jca.GetInstance.Instance; /** * The 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 {@code 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, * {@code MD2withRSA}, {@code MD5withRSA}, or {@code 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:
Depending on the type of initialization, this will update the * bytes to be signed or verified. See the * {@link #update(byte) update} methods. * *
Note that this class is abstract and extends from * {@code SignatureSpi} for historical reasons. * Application developers should only take notice of the methods defined in * this {@code 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. * *
Android provides the following {@code Signature} algorithms: *
Algorithm | *Supported API Levels | *
---|---|
DSA | *1+ | *
DSAwithSHA1 | *1+ | *
DSS | *1-19 | *
ECDSA | *11+ | *
ECDSAwithSHA1 | *11+ | *
MD2withRSA | *1-3 | *
MD4withRSA | *1-8 | *
MD5withRSA | *1+ | *
MD5withRSA/ISO9796-2 | *1-8 | *
NONEwithDSA | *1+ | *
NONEwithECDSA | *11+ | *
NONEwithRSA | *17+ | *
RSASSA-PSS | *1-8 | *
SHA1withDSA | *1+ | *
SHA1withECDSA | *11+ | *
SHA1withRSA | *1+ | *
SHA1withRSA/ISO9796-2 | *1-8 | *
SHA1withRSA/PSS | *23+ | *
SHA224withDSA | *20+ | *
SHA224withECDSA | *20+ | *
SHA224withRSA | *20+ | *
SHA224withRSA/PSS | *23+ | *
SHA256withDSA | *1+ | *
SHA256withECDSA | *11+ | *
SHA256withRSA | *1+ | *
SHA256withRSA/PSS | *23+ | *
SHA384withECDSA | *11+ | *
SHA384withRSA | *1+ | *
SHA384withRSA/PSS | *23+ | *
SHA512withECDSA | *11+ | *
SHA512withRSA | *1+ | *
SHA512withRSA/PSS | *23+ | *
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 the Signature section in the
* Java Cryptography Architecture Standard Algorithm Name Documentation
* 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
*/
public static Signature getInstance(String algorithm)
throws NoSuchAlgorithmException {
List 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 the Signature section in the
* Java Cryptography Architecture Standard Algorithm Name Documentation
* 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
*/
public static Signature getInstance(String algorithm, String provider)
throws NoSuchAlgorithmException, NoSuchProviderException {
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);
}
/**
* 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 the Signature section in the
* Java Cryptography Architecture Standard Algorithm Name Documentation
* 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
*/
public static Signature getInstance(String algorithm, Provider provider)
throws NoSuchAlgorithmException {
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);
}
// return an implementation for NONEwithRSA, which is a special case
// because of the Cipher.RSA/ECB/PKCS1Padding compatibility wrapper
private static Signature getInstanceRSA(Provider p)
throws NoSuchAlgorithmException {
// 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);
}
}
/**
* Returns the provider of this signature object.
*
* @return the provider of this signature object
*/
public final Provider getProvider() {
chooseFirstProvider();
return this.provider;
}
void chooseFirstProvider() {
// empty, overridden in Delegate
}
/**
* 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.
*/
public final void initVerify(PublicKey publicKey)
throws InvalidKeyException {
engineInitVerify(publicKey);
state = VERIFY;
// BEGIN Android-removed: this debugging mechanism is not supported in Android.
/*
if (!skipDebug && pdebug != null) {
pdebug.println("Signature." + algorithm +
" verification algorithm from: " + this.provider.getName());
}
*/
// END Android-removed: this debugging mechanism is not supported in Android.
}
/**
* 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
* {@code 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
*/
public final void initVerify(Certificate certificate)
throws InvalidKeyException {
// 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 A call to this method resets this signature object to the state
* it was in when previously initialized for signing via a
* call to {@code initSign(PrivateKey)}. That is, the object is
* reset and available to generate another signature from the same
* signer, if desired, via new calls to {@code update} and
* {@code 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.
*/
public final byte[] sign() throws SignatureException {
if (state == SIGN) {
return engineSign();
}
throw new SignatureException("object not initialized for " +
"signing");
}
/**
* Finishes the signature operation and stores the resulting signature
* bytes in the provided buffer {@code outbuf}, starting at
* {@code 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 {@code 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 {@code outbuf} where the signature is
* stored.
*
* @param len number of bytes within {@code outbuf} allotted for the
* signature.
*
* @return the number of bytes placed into {@code 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 {@code len} is less
* than the actual signature length.
*
* @since 1.2
*/
public final int sign(byte[] outbuf, int offset, int len)
throws SignatureException {
if (outbuf == null) {
throw new IllegalArgumentException("No output buffer given");
}
if (offset < 0 || len < 0) {
throw new IllegalArgumentException("offset or len is less than 0");
}
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);
}
/**
* 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 {@code 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 {@code 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.
*/
public final boolean verify(byte[] signature) throws SignatureException {
if (state == VERIFY) {
return engineVerify(signature);
}
throw new SignatureException("object not initialized for " +
"verification");
}
/**
* 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 {@code 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 {@code 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 {@code signature}
* byte array is null, or the {@code offset} or {@code length}
* is less than 0, or the sum of the {@code offset} and
* {@code length} is greater than the length of the
* {@code signature} byte array.
* @since 1.4
*/
public final boolean verify(byte[] signature, int offset, int length)
throws SignatureException {
if (state == VERIFY) {
if (signature == null) {
throw new IllegalArgumentException("signature is null");
}
if (offset < 0 || length < 0) {
throw new IllegalArgumentException
("offset or length is less than 0");
}
if (signature.length - offset < length) {
throw new IllegalArgumentException
("signature too small for specified offset and length");
}
return engineVerify(signature, offset, length);
}
throw new SignatureException("object not initialized for " +
"verification");
}
/**
* 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.
*/
public final void update(byte b) throws SignatureException {
if (state == VERIFY || state == SIGN) {
engineUpdate(b);
} else {
throw new SignatureException("object not initialized for "
+ "signature or verification");
}
}
/**
* 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.
*/
public final void update(byte[] data) throws SignatureException {
update(data, 0, data.length);
}
/**
* 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.
*/
public final void update(byte[] data, int off, int len)
throws SignatureException {
if (state == SIGN || state == VERIFY) {
if (data == null) {
throw new IllegalArgumentException("data is null");
}
if (off < 0 || len < 0) {
throw new IllegalArgumentException("off or len is less than 0");
}
if (data.length - off < len) {
throw new IllegalArgumentException
("data too small for specified offset and length");
}
engineUpdate(data, off, len);
} else {
throw new SignatureException("object not initialized for "
+ "signature or verification");
}
}
/**
* Updates the data to be signed or verified using the specified
* ByteBuffer. Processes the {@code data.remaining()} bytes
* starting at at {@code 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
*/
public final void update(ByteBuffer data) throws SignatureException {
if ((state != SIGN) && (state != VERIFY)) {
throw new SignatureException("object not initialized for "
+ "signature or verification");
}
if (data == null) {
throw new NullPointerException();
}
engineUpdate(data);
}
/**
* Returns the name of the algorithm for this signature object.
*
* @return the name of the algorithm for this signature object.
*/
public final String getAlgorithm() {
return this.algorithm;
}
/**
* 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.
*/
public String toString() {
String initState = "";
switch (state) {
case UNINITIALIZED:
initState = " 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
*/
public final AlgorithmParameters getParameters() {
return engineGetParameters();
}
/**
* 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 {@code param} is an invalid
* parameter for this engine, or another exception occurs while
* trying to get this parameter.
*
* @see #setParameter(String, Object)
*
* @deprecated Deprecated.
*/
@Deprecated
// Android-changed: add "Deprecated."
public final Object getParameter(String param)
throws InvalidParameterException {
return engineGetParameter(param);
}
/**
* 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 {@code Cloneable}.
*/
public Object clone() throws CloneNotSupportedException {
if (this instanceof Cloneable) {
return super.clone();
} else {
throw new CloneNotSupportedException();
}
}
// BEGIN Android-added: Allow access to the current SPI for testing purposes.
/**
* Returns the {@code SignatureSpi} backing this {@code Signature}.
*
* @hide
*/
public SignatureSpi getCurrentSpi() {
return null;
}
// END Android-added: Allow access to the current SPI for testing purposes.
/*
* The following class allows providers to extend from SignatureSpi
* rather than from Signature. It represents a Signature with an
* encapsulated, provider-supplied SPI object (of type SignatureSpi).
* If the provider implementation is an instance of SignatureSpi, the
* getInstance() methods above return an instance of this class, with
* the SPI object encapsulated.
*
* Note: All SPI methods from the original Signature class have been
* moved up the hierarchy into a new class (SignatureSpi), which has
* been interposed in the hierarchy between the API (Signature)
* and its original parent (Object).
*/
@SuppressWarnings("deprecation")
private static class Delegate extends Signature {
// The provider implementation (delegate)
// filled in once the provider is selected
// BEGIN Android-note: Note on sigSpi invariants.
// (Not necessarily Android specific)
// Invariant to be preserved: sigSpi cannot be changed once it was assigned to something
// different than null and lock is null. That is only the case when sigSpi is specified
// in the constructor.
// END Android-note: Note on sigSpi invariants.
private SignatureSpi sigSpi;
// lock for mutex during provider selection
private final Object lock;
// BEGIN Android-removed: Redo the provider selection logic to allow reselecting provider.
// When only the algorithm is specified, we want to allow the Signature provider for that
// algorithm to change if multiple providers exist and they support different subsets of
// keys. To that end, we don't hold an iterator and exhaust it when we need to choose
// a provider like the upstream implementation, we reestablish the list of providers
// each time.
/*
// next service to try in provider selection
// null once provider is selected
private Service firstService;
// remaining services to try in provider selection
// null once provider is selected
private Iterator