0N/A/*
5301N/A * Copyright (c) 1996, 2012, Oracle and/or its affiliates. All rights reserved.
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
2362N/A * published by the Free Software Foundation. Oracle designates this
0N/A * particular file as subject to the "Classpath" exception as provided
2362N/A * by Oracle in the LICENSE file that accompanied this code.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2362N/A * or visit www.oracle.com if you need additional information or have any
2362N/A * questions.
0N/A */
0N/A
0N/Apackage java.security;
0N/A
0N/Aimport java.security.spec.AlgorithmParameterSpec;
0N/Aimport java.util.*;
0N/Aimport java.util.concurrent.ConcurrentHashMap;
0N/Aimport java.io.*;
0N/Aimport java.security.cert.Certificate;
0N/Aimport java.security.cert.X509Certificate;
0N/A
0N/Aimport java.nio.ByteBuffer;
0N/A
0N/Aimport java.security.Provider.Service;
0N/A
0N/Aimport javax.crypto.Cipher;
0N/Aimport javax.crypto.CipherSpi;
0N/Aimport javax.crypto.IllegalBlockSizeException;
0N/Aimport javax.crypto.BadPaddingException;
0N/Aimport javax.crypto.NoSuchPaddingException;
0N/A
0N/Aimport sun.security.util.Debug;
0N/Aimport sun.security.jca.*;
0N/Aimport sun.security.jca.GetInstance.Instance;
0N/A
0N/A/**
3465N/A * The Signature class is used to provide applications the functionality
0N/A * of a digital signature algorithm. Digital signatures are used for
0N/A * authentication and integrity assurance of digital data.
0N/A *
0N/A * <p> The signature algorithm can be, among others, the NIST standard
0N/A * DSA, using DSA and SHA-1. The DSA algorithm using the
0N/A * SHA-1 message digest algorithm can be specified as <tt>SHA1withDSA</tt>.
0N/A * In the case of RSA, there are multiple choices for the message digest
0N/A * algorithm, so the signing algorithm could be specified as, for example,
0N/A * <tt>MD2withRSA</tt>, <tt>MD5withRSA</tt>, or <tt>SHA1withRSA</tt>.
0N/A * The algorithm name must be specified, as there is no default.
0N/A *
0N/A * <p> A Signature object can be used to generate and verify digital
0N/A * signatures.
0N/A *
0N/A * <p> There are three phases to the use of a Signature object for
0N/A * either signing data or verifying a signature:<ol>
0N/A *
0N/A * <li>Initialization, with either
0N/A *
0N/A * <ul>
0N/A *
0N/A * <li>a public key, which initializes the signature for
0N/A * verification (see {@link #initVerify(PublicKey) initVerify}), or
0N/A *
0N/A * <li>a private key (and optionally a Secure Random Number Generator),
0N/A * which initializes the signature for signing
0N/A * (see {@link #initSign(PrivateKey)}
0N/A * and {@link #initSign(PrivateKey, SecureRandom)}).
0N/A *
0N/A * </ul><p>
0N/A *
0N/A * <li>Updating<p>
0N/A *
0N/A * <p>Depending on the type of initialization, this will update the
0N/A * bytes to be signed or verified. See the
0N/A * {@link #update(byte) update} methods.<p>
0N/A *
0N/A * <li>Signing or Verifying a signature on all updated bytes. See the
0N/A * {@link #sign() sign} methods and the {@link #verify(byte[]) verify}
0N/A * method.
0N/A *
0N/A * </ol>
0N/A *
0N/A * <p>Note that this class is abstract and extends from
0N/A * <code>SignatureSpi</code> for historical reasons.
0N/A * Application developers should only take notice of the methods defined in
0N/A * this <code>Signature</code> class; all the methods in
0N/A * the superclass are intended for cryptographic service providers who wish to
0N/A * supply their own implementations of digital signature algorithms.
0N/A *
3465N/A * <p> Every implementation of the Java platform is required to support the
3465N/A * following standard <code>Signature</code> algorithms:
3465N/A * <ul>
3465N/A * <li><tt>SHA1withDSA</tt></li>
3465N/A * <li><tt>SHA1withRSA</tt></li>
3465N/A * <li><tt>SHA256withRSA</tt></li>
3465N/A * </ul>
3465N/A * These algorithms are described in the <a href=
3465N/A * "{@docRoot}/../technotes/guides/security/StandardNames.html#Signature">
3465N/A * Signature section</a> of the
3465N/A * Java Cryptography Architecture Standard Algorithm Name Documentation.
3465N/A * Consult the release documentation for your implementation to see if any
3465N/A * other algorithms are supported.
3465N/A *
0N/A * @author Benjamin Renaud
0N/A *
0N/A */
0N/A
0N/Apublic abstract class Signature extends SignatureSpi {
0N/A
0N/A private static final Debug debug =
0N/A Debug.getInstance("jca", "Signature");
0N/A
0N/A /*
0N/A * The algorithm for this signature object.
0N/A * This value is used to map an OID to the particular algorithm.
0N/A * The mapping is done in AlgorithmObject.algOID(String algorithm)
0N/A */
0N/A private String algorithm;
0N/A
0N/A // The provider
0N/A Provider provider;
0N/A
0N/A /**
0N/A * Possible {@link #state} value, signifying that
0N/A * this signature object has not yet been initialized.
0N/A */
0N/A protected final static int UNINITIALIZED = 0;
0N/A
0N/A /**
0N/A * Possible {@link #state} value, signifying that
0N/A * this signature object has been initialized for signing.
0N/A */
0N/A protected final static int SIGN = 2;
0N/A
0N/A /**
0N/A * Possible {@link #state} value, signifying that
0N/A * this signature object has been initialized for verification.
0N/A */
0N/A protected final static int VERIFY = 3;
0N/A
0N/A /**
0N/A * Current state of this signature object.
0N/A */
0N/A protected int state = UNINITIALIZED;
0N/A
0N/A /**
0N/A * Creates a Signature object for the specified algorithm.
0N/A *
0N/A * @param algorithm the standard string name of the algorithm.
3465N/A * See the Signature section in the <a href=
3465N/A * "{@docRoot}/../technotes/guides/security/StandardNames.html#Signature">
3465N/A * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
0N/A * for information about standard algorithm names.
0N/A */
0N/A protected Signature(String algorithm) {
0N/A this.algorithm = algorithm;
0N/A }
0N/A
0N/A // name of the special signature alg
0N/A private final static String RSA_SIGNATURE = "NONEwithRSA";
0N/A
0N/A // name of the equivalent cipher alg
0N/A private final static String RSA_CIPHER = "RSA/ECB/PKCS1Padding";
0N/A
0N/A // all the services we need to lookup for compatibility with Cipher
0N/A private final static List<ServiceId> rsaIds = Arrays.asList(
0N/A new ServiceId[] {
0N/A new ServiceId("Signature", "NONEwithRSA"),
0N/A new ServiceId("Cipher", "RSA/ECB/PKCS1Padding"),
0N/A new ServiceId("Cipher", "RSA/ECB"),
0N/A new ServiceId("Cipher", "RSA//PKCS1Padding"),
0N/A new ServiceId("Cipher", "RSA"),
0N/A }
0N/A );
0N/A
0N/A /**
0N/A * Returns a Signature object that implements the specified signature
0N/A * algorithm.
0N/A *
0N/A * <p> This method traverses the list of registered security Providers,
0N/A * starting with the most preferred Provider.
0N/A * A new Signature object encapsulating the
0N/A * SignatureSpi implementation from the first
0N/A * Provider that supports the specified algorithm is returned.
0N/A *
0N/A * <p> Note that the list of registered providers may be retrieved via
0N/A * the {@link Security#getProviders() Security.getProviders()} method.
0N/A *
0N/A * @param algorithm the standard name of the algorithm requested.
3465N/A * See the Signature section in the <a href=
3465N/A * "{@docRoot}/../technotes/guides/security/StandardNames.html#Signature">
3465N/A * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
0N/A * for information about standard algorithm names.
0N/A *
0N/A * @return the new Signature object.
0N/A *
0N/A * @exception NoSuchAlgorithmException if no Provider supports a
0N/A * Signature implementation for the
0N/A * specified algorithm.
0N/A *
0N/A * @see Provider
0N/A */
0N/A public static Signature getInstance(String algorithm)
0N/A throws NoSuchAlgorithmException {
0N/A List<Service> list;
0N/A if (algorithm.equalsIgnoreCase(RSA_SIGNATURE)) {
0N/A list = GetInstance.getServices(rsaIds);
0N/A } else {
0N/A list = GetInstance.getServices("Signature", algorithm);
0N/A }
0N/A Iterator<Service> t = list.iterator();
0N/A if (t.hasNext() == false) {
0N/A throw new NoSuchAlgorithmException
0N/A (algorithm + " Signature not available");
0N/A }
0N/A // try services until we find an Spi or a working Signature subclass
0N/A NoSuchAlgorithmException failure;
0N/A do {
0N/A Service s = t.next();
0N/A if (isSpi(s)) {
0N/A return new Delegate(s, t, algorithm);
0N/A } else {
0N/A // must be a subclass of Signature, disable dynamic selection
0N/A try {
0N/A Instance instance =
0N/A GetInstance.getInstance(s, SignatureSpi.class);
0N/A return getInstance(instance, algorithm);
0N/A } catch (NoSuchAlgorithmException e) {
0N/A failure = e;
0N/A }
0N/A }
0N/A } while (t.hasNext());
0N/A throw failure;
0N/A }
0N/A
0N/A private static Signature getInstance(Instance instance, String algorithm) {
0N/A Signature sig;
0N/A if (instance.impl instanceof Signature) {
0N/A sig = (Signature)instance.impl;
0N/A } else {
0N/A SignatureSpi spi = (SignatureSpi)instance.impl;
0N/A sig = new Delegate(spi, algorithm);
0N/A }
0N/A sig.provider = instance.provider;
0N/A return sig;
0N/A }
0N/A
0N/A private final static Map<String,Boolean> signatureInfo;
0N/A
0N/A static {
0N/A signatureInfo = new ConcurrentHashMap<String,Boolean>();
0N/A Boolean TRUE = Boolean.TRUE;
0N/A // pre-initialize with values for our SignatureSpi implementations
0N/A signatureInfo.put("sun.security.provider.DSA$RawDSA", TRUE);
0N/A signatureInfo.put("sun.security.provider.DSA$SHA1withDSA", TRUE);
0N/A signatureInfo.put("sun.security.rsa.RSASignature$MD2withRSA", TRUE);
0N/A signatureInfo.put("sun.security.rsa.RSASignature$MD5withRSA", TRUE);
0N/A signatureInfo.put("sun.security.rsa.RSASignature$SHA1withRSA", TRUE);
0N/A signatureInfo.put("sun.security.rsa.RSASignature$SHA256withRSA", TRUE);
0N/A signatureInfo.put("sun.security.rsa.RSASignature$SHA384withRSA", TRUE);
0N/A signatureInfo.put("sun.security.rsa.RSASignature$SHA512withRSA", TRUE);
0N/A signatureInfo.put("com.sun.net.ssl.internal.ssl.RSASignature", TRUE);
0N/A signatureInfo.put("sun.security.pkcs11.P11Signature", TRUE);
0N/A }
0N/A
0N/A private static boolean isSpi(Service s) {
0N/A if (s.getType().equals("Cipher")) {
0N/A // must be a CipherSpi, which we can wrap with the CipherAdapter
0N/A return true;
0N/A }
0N/A String className = s.getClassName();
0N/A Boolean result = signatureInfo.get(className);
0N/A if (result == null) {
0N/A try {
0N/A Object instance = s.newInstance(null);
0N/A // Signature extends SignatureSpi
0N/A // so it is a "real" Spi if it is an
0N/A // instance of SignatureSpi but not Signature
0N/A boolean r = (instance instanceof SignatureSpi)
0N/A && (instance instanceof Signature == false);
0N/A if ((debug != null) && (r == false)) {
0N/A debug.println("Not a SignatureSpi " + className);
0N/A debug.println("Delayed provider selection may not be "
0N/A + "available for algorithm " + s.getAlgorithm());
0N/A }
0N/A result = Boolean.valueOf(r);
0N/A signatureInfo.put(className, result);
0N/A } catch (Exception e) {
0N/A // something is wrong, assume not an SPI
0N/A return false;
0N/A }
0N/A }
0N/A return result.booleanValue();
0N/A }
0N/A
0N/A /**
0N/A * Returns a Signature object that implements the specified signature
0N/A * algorithm.
0N/A *
0N/A * <p> A new Signature object encapsulating the
0N/A * SignatureSpi implementation from the specified provider
0N/A * is returned. The specified provider must be registered
0N/A * in the security provider list.
0N/A *
0N/A * <p> Note that the list of registered providers may be retrieved via
0N/A * the {@link Security#getProviders() Security.getProviders()} method.
0N/A *
0N/A * @param algorithm the name of the algorithm requested.
3465N/A * See the Signature section in the <a href=
3465N/A * "{@docRoot}/../technotes/guides/security/StandardNames.html#Signature">
3465N/A * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
0N/A * for information about standard algorithm names.
0N/A *
0N/A * @param provider the name of the provider.
0N/A *
0N/A * @return the new Signature object.
0N/A *
0N/A * @exception NoSuchAlgorithmException if a SignatureSpi
0N/A * implementation for the specified algorithm is not
0N/A * available from the specified provider.
0N/A *
0N/A * @exception NoSuchProviderException if the specified provider is not
0N/A * registered in the security provider list.
0N/A *
0N/A * @exception IllegalArgumentException if the provider name is null
0N/A * or empty.
0N/A *
0N/A * @see Provider
0N/A */
0N/A public static Signature getInstance(String algorithm, String provider)
0N/A throws NoSuchAlgorithmException, NoSuchProviderException {
0N/A if (algorithm.equalsIgnoreCase(RSA_SIGNATURE)) {
0N/A // exception compatibility with existing code
0N/A if ((provider == null) || (provider.length() == 0)) {
0N/A throw new IllegalArgumentException("missing provider");
0N/A }
0N/A Provider p = Security.getProvider(provider);
0N/A if (p == null) {
0N/A throw new NoSuchProviderException
0N/A ("no such provider: " + provider);
0N/A }
0N/A return getInstanceRSA(p);
0N/A }
0N/A Instance instance = GetInstance.getInstance
0N/A ("Signature", SignatureSpi.class, algorithm, provider);
0N/A return getInstance(instance, algorithm);
0N/A }
0N/A
0N/A /**
0N/A * Returns a Signature object that implements the specified
0N/A * signature algorithm.
0N/A *
0N/A * <p> A new Signature object encapsulating the
0N/A * SignatureSpi implementation from the specified Provider
0N/A * object is returned. Note that the specified Provider object
0N/A * does not have to be registered in the provider list.
0N/A *
0N/A * @param algorithm the name of the algorithm requested.
3465N/A * See the Signature section in the <a href=
3465N/A * "{@docRoot}/../technotes/guides/security/StandardNames.html#Signature">
3465N/A * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
0N/A * for information about standard algorithm names.
0N/A *
0N/A * @param provider the provider.
0N/A *
0N/A * @return the new Signature object.
0N/A *
0N/A * @exception NoSuchAlgorithmException if a SignatureSpi
0N/A * implementation for the specified algorithm is not available
0N/A * from the specified Provider object.
0N/A *
0N/A * @exception IllegalArgumentException if the provider is null.
0N/A *
0N/A * @see Provider
0N/A *
0N/A * @since 1.4
0N/A */
0N/A public static Signature getInstance(String algorithm, Provider provider)
0N/A throws NoSuchAlgorithmException {
0N/A if (algorithm.equalsIgnoreCase(RSA_SIGNATURE)) {
0N/A // exception compatibility with existing code
0N/A if (provider == null) {
0N/A throw new IllegalArgumentException("missing provider");
0N/A }
0N/A return getInstanceRSA(provider);
0N/A }
0N/A Instance instance = GetInstance.getInstance
0N/A ("Signature", SignatureSpi.class, algorithm, provider);
0N/A return getInstance(instance, algorithm);
0N/A }
0N/A
0N/A // return an implementation for NONEwithRSA, which is a special case
0N/A // because of the Cipher.RSA/ECB/PKCS1Padding compatibility wrapper
0N/A private static Signature getInstanceRSA(Provider p)
0N/A throws NoSuchAlgorithmException {
0N/A // try Signature first
0N/A Service s = p.getService("Signature", RSA_SIGNATURE);
0N/A if (s != null) {
0N/A Instance instance = GetInstance.getInstance(s, SignatureSpi.class);
0N/A return getInstance(instance, RSA_SIGNATURE);
0N/A }
0N/A // check Cipher
0N/A try {
0N/A Cipher c = Cipher.getInstance(RSA_CIPHER, p);
0N/A return new Delegate(new CipherAdapter(c), RSA_SIGNATURE);
0N/A } catch (GeneralSecurityException e) {
0N/A // throw Signature style exception message to avoid confusion,
0N/A // but append Cipher exception as cause
0N/A throw new NoSuchAlgorithmException("no such algorithm: "
0N/A + RSA_SIGNATURE + " for provider " + p.getName(), e);
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns the provider of this signature object.
0N/A *
0N/A * @return the provider of this signature object
0N/A */
0N/A public final Provider getProvider() {
0N/A chooseFirstProvider();
0N/A return this.provider;
0N/A }
0N/A
0N/A void chooseFirstProvider() {
0N/A // empty, overridden in Delegate
0N/A }
0N/A
0N/A /**
0N/A * Initializes this object for verification. If this method is called
0N/A * again with a different argument, it negates the effect
0N/A * of this call.
0N/A *
0N/A * @param publicKey the public key of the identity whose signature is
0N/A * going to be verified.
0N/A *
0N/A * @exception InvalidKeyException if the key is invalid.
0N/A */
0N/A public final void initVerify(PublicKey publicKey)
0N/A throws InvalidKeyException {
0N/A engineInitVerify(publicKey);
0N/A state = VERIFY;
0N/A }
0N/A
0N/A /**
0N/A * Initializes this object for verification, using the public key from
0N/A * the given certificate.
0N/A * <p>If the certificate is of type X.509 and has a <i>key usage</i>
0N/A * extension field marked as critical, and the value of the <i>key usage</i>
0N/A * extension field implies that the public key in
0N/A * the certificate and its corresponding private key are not
0N/A * supposed to be used for digital signatures, an
0N/A * <code>InvalidKeyException</code> is thrown.
0N/A *
0N/A * @param certificate the certificate of the identity whose signature is
0N/A * going to be verified.
0N/A *
0N/A * @exception InvalidKeyException if the public key in the certificate
0N/A * is not encoded properly or does not include required parameter
0N/A * information or cannot be used for digital signature purposes.
0N/A * @since 1.3
0N/A */
0N/A public final void initVerify(Certificate certificate)
0N/A throws InvalidKeyException {
0N/A // If the certificate is of type X509Certificate,
0N/A // we should check whether it has a Key Usage
0N/A // extension marked as critical.
0N/A if (certificate instanceof java.security.cert.X509Certificate) {
0N/A // Check whether the cert has a key usage extension
0N/A // marked as a critical extension.
0N/A // The OID for KeyUsage extension is 2.5.29.15.
0N/A X509Certificate cert = (X509Certificate)certificate;
0N/A Set<String> critSet = cert.getCriticalExtensionOIDs();
0N/A
0N/A if (critSet != null && !critSet.isEmpty()
0N/A && critSet.contains("2.5.29.15")) {
0N/A boolean[] keyUsageInfo = cert.getKeyUsage();
0N/A // keyUsageInfo[0] is for digitalSignature.
0N/A if ((keyUsageInfo != null) && (keyUsageInfo[0] == false))
0N/A throw new InvalidKeyException("Wrong key usage");
0N/A }
0N/A }
0N/A
0N/A PublicKey publicKey = certificate.getPublicKey();
0N/A engineInitVerify(publicKey);
0N/A state = VERIFY;
0N/A }
0N/A
0N/A /**
0N/A * Initialize this object for signing. If this method is called
0N/A * again with a different argument, it negates the effect
0N/A * of this call.
0N/A *
0N/A * @param privateKey the private key of the identity whose signature
0N/A * is going to be generated.
0N/A *
0N/A * @exception InvalidKeyException if the key is invalid.
0N/A */
0N/A public final void initSign(PrivateKey privateKey)
0N/A throws InvalidKeyException {
0N/A engineInitSign(privateKey);
0N/A state = SIGN;
0N/A }
0N/A
0N/A /**
0N/A * Initialize this object for signing. If this method is called
0N/A * again with a different argument, it negates the effect
0N/A * of this call.
0N/A *
0N/A * @param privateKey the private key of the identity whose signature
0N/A * is going to be generated.
0N/A *
0N/A * @param random the source of randomness for this signature.
0N/A *
0N/A * @exception InvalidKeyException if the key is invalid.
0N/A */
0N/A public final void initSign(PrivateKey privateKey, SecureRandom random)
0N/A throws InvalidKeyException {
0N/A engineInitSign(privateKey, random);
0N/A state = SIGN;
0N/A }
0N/A
0N/A /**
0N/A * Returns the signature bytes of all the data updated.
0N/A * The format of the signature depends on the underlying
0N/A * signature scheme.
0N/A *
0N/A * <p>A call to this method resets this signature object to the state
0N/A * it was in when previously initialized for signing via a
0N/A * call to <code>initSign(PrivateKey)</code>. That is, the object is
0N/A * reset and available to generate another signature from the same
0N/A * signer, if desired, via new calls to <code>update</code> and
0N/A * <code>sign</code>.
0N/A *
0N/A * @return the signature bytes of the signing operation's result.
0N/A *
0N/A * @exception SignatureException if this signature object is not
0N/A * initialized properly or if this signature algorithm is unable to
0N/A * process the input data provided.
0N/A */
0N/A public final byte[] sign() throws SignatureException {
0N/A if (state == SIGN) {
0N/A return engineSign();
0N/A }
0N/A throw new SignatureException("object not initialized for " +
0N/A "signing");
0N/A }
0N/A
0N/A /**
0N/A * Finishes the signature operation and stores the resulting signature
0N/A * bytes in the provided buffer <code>outbuf</code>, starting at
0N/A * <code>offset</code>.
0N/A * The format of the signature depends on the underlying
0N/A * signature scheme.
0N/A *
0N/A * <p>This signature object is reset to its initial state (the state it
0N/A * was in after a call to one of the <code>initSign</code> methods) and
0N/A * can be reused to generate further signatures with the same private key.
0N/A *
0N/A * @param outbuf buffer for the signature result.
0N/A *
0N/A * @param offset offset into <code>outbuf</code> where the signature is
0N/A * stored.
0N/A *
0N/A * @param len number of bytes within <code>outbuf</code> allotted for the
0N/A * signature.
0N/A *
0N/A * @return the number of bytes placed into <code>outbuf</code>.
0N/A *
0N/A * @exception SignatureException if this signature object is not
0N/A * initialized properly, if this signature algorithm is unable to
0N/A * process the input data provided, or if <code>len</code> is less
0N/A * than the actual signature length.
0N/A *
0N/A * @since 1.2
0N/A */
0N/A public final int sign(byte[] outbuf, int offset, int len)
0N/A throws SignatureException {
0N/A if (outbuf == null) {
0N/A throw new IllegalArgumentException("No output buffer given");
0N/A }
0N/A if (outbuf.length - offset < len) {
0N/A throw new IllegalArgumentException
0N/A ("Output buffer too small for specified offset and length");
0N/A }
0N/A if (state != SIGN) {
0N/A throw new SignatureException("object not initialized for " +
0N/A "signing");
0N/A }
0N/A return engineSign(outbuf, offset, len);
0N/A }
0N/A
0N/A /**
0N/A * Verifies the passed-in signature.
0N/A *
0N/A * <p>A call to this method resets this signature object to the state
0N/A * it was in when previously initialized for verification via a
0N/A * call to <code>initVerify(PublicKey)</code>. That is, the object is
0N/A * reset and available to verify another signature from the identity
0N/A * whose public key was specified in the call to <code>initVerify</code>.
0N/A *
0N/A * @param signature the signature bytes to be verified.
0N/A *
0N/A * @return true if the signature was verified, false if not.
0N/A *
0N/A * @exception SignatureException if this signature object is not
0N/A * initialized properly, the passed-in signature is improperly
0N/A * encoded or of the wrong type, if this signature algorithm is unable to
0N/A * process the input data provided, etc.
0N/A */
0N/A public final boolean verify(byte[] signature) throws SignatureException {
0N/A if (state == VERIFY) {
0N/A return engineVerify(signature);
0N/A }
0N/A throw new SignatureException("object not initialized for " +
0N/A "verification");
0N/A }
0N/A
0N/A /**
0N/A * Verifies the passed-in signature in the specified array
0N/A * of bytes, starting at the specified offset.
0N/A *
0N/A * <p>A call to this method resets this signature object to the state
0N/A * it was in when previously initialized for verification via a
0N/A * call to <code>initVerify(PublicKey)</code>. That is, the object is
0N/A * reset and available to verify another signature from the identity
0N/A * whose public key was specified in the call to <code>initVerify</code>.
0N/A *
0N/A *
0N/A * @param signature the signature bytes to be verified.
0N/A * @param offset the offset to start from in the array of bytes.
0N/A * @param length the number of bytes to use, starting at offset.
0N/A *
0N/A * @return true if the signature was verified, false if not.
0N/A *
0N/A * @exception SignatureException if this signature object is not
0N/A * initialized properly, the passed-in signature is improperly
0N/A * encoded or of the wrong type, if this signature algorithm is unable to
0N/A * process the input data provided, etc.
0N/A * @exception IllegalArgumentException if the <code>signature</code>
0N/A * byte array is null, or the <code>offset</code> or <code>length</code>
0N/A * is less than 0, or the sum of the <code>offset</code> and
0N/A * <code>length</code> is greater than the length of the
0N/A * <code>signature</code> byte array.
0N/A * @since 1.4
0N/A */
0N/A public final boolean verify(byte[] signature, int offset, int length)
0N/A throws SignatureException {
0N/A if (state == VERIFY) {
0N/A if ((signature == null) || (offset < 0) || (length < 0) ||
5301N/A (length > signature.length - offset)) {
0N/A throw new IllegalArgumentException("Bad arguments");
0N/A }
0N/A
0N/A return engineVerify(signature, offset, length);
0N/A }
0N/A throw new SignatureException("object not initialized for " +
0N/A "verification");
0N/A }
0N/A
0N/A /**
0N/A * Updates the data to be signed or verified by a byte.
0N/A *
0N/A * @param b the byte to use for the update.
0N/A *
0N/A * @exception SignatureException if this signature object is not
0N/A * initialized properly.
0N/A */
0N/A public final void update(byte b) throws SignatureException {
0N/A if (state == VERIFY || state == SIGN) {
0N/A engineUpdate(b);
0N/A } else {
0N/A throw new SignatureException("object not initialized for "
0N/A + "signature or verification");
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Updates the data to be signed or verified, using the specified
0N/A * array of bytes.
0N/A *
0N/A * @param data the byte array to use for the update.
0N/A *
0N/A * @exception SignatureException if this signature object is not
0N/A * initialized properly.
0N/A */
0N/A public final void update(byte[] data) throws SignatureException {
0N/A update(data, 0, data.length);
0N/A }
0N/A
0N/A /**
0N/A * Updates the data to be signed or verified, using the specified
0N/A * array of bytes, starting at the specified offset.
0N/A *
0N/A * @param data the array of bytes.
0N/A * @param off the offset to start from in the array of bytes.
0N/A * @param len the number of bytes to use, starting at offset.
0N/A *
0N/A * @exception SignatureException if this signature object is not
0N/A * initialized properly.
0N/A */
0N/A public final void update(byte[] data, int off, int len)
0N/A throws SignatureException {
0N/A if (state == SIGN || state == VERIFY) {
0N/A engineUpdate(data, off, len);
0N/A } else {
0N/A throw new SignatureException("object not initialized for "
0N/A + "signature or verification");
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Updates the data to be signed or verified using the specified
0N/A * ByteBuffer. Processes the <code>data.remaining()</code> bytes
0N/A * starting at at <code>data.position()</code>.
0N/A * Upon return, the buffer's position will be equal to its limit;
0N/A * its limit will not have changed.
0N/A *
0N/A * @param data the ByteBuffer
0N/A *
0N/A * @exception SignatureException if this signature object is not
0N/A * initialized properly.
0N/A * @since 1.5
0N/A */
0N/A public final void update(ByteBuffer data) throws SignatureException {
0N/A if ((state != SIGN) && (state != VERIFY)) {
0N/A throw new SignatureException("object not initialized for "
0N/A + "signature or verification");
0N/A }
0N/A if (data == null) {
0N/A throw new NullPointerException();
0N/A }
0N/A engineUpdate(data);
0N/A }
0N/A
0N/A /**
0N/A * Returns the name of the algorithm for this signature object.
0N/A *
0N/A * @return the name of the algorithm for this signature object.
0N/A */
0N/A public final String getAlgorithm() {
0N/A return this.algorithm;
0N/A }
0N/A
0N/A /**
0N/A * Returns a string representation of this signature object,
0N/A * providing information that includes the state of the object
0N/A * and the name of the algorithm used.
0N/A *
0N/A * @return a string representation of this signature object.
0N/A */
0N/A public String toString() {
0N/A String initState = "";
0N/A switch (state) {
0N/A case UNINITIALIZED:
0N/A initState = "<not initialized>";
0N/A break;
0N/A case VERIFY:
0N/A initState = "<initialized for verifying>";
0N/A break;
0N/A case SIGN:
0N/A initState = "<initialized for signing>";
0N/A break;
0N/A }
0N/A return "Signature object: " + getAlgorithm() + initState;
0N/A }
0N/A
0N/A /**
0N/A * Sets the specified algorithm parameter to the specified value.
0N/A * This method supplies a general-purpose mechanism through
0N/A * which it is possible to set the various parameters of this object.
0N/A * A parameter may be any settable parameter for the algorithm, such as
0N/A * a parameter size, or a source of random bits for signature generation
0N/A * (if appropriate), or an indication of whether or not to perform
0N/A * a specific but optional computation. A uniform algorithm-specific
0N/A * naming scheme for each parameter is desirable but left unspecified
0N/A * at this time.
0N/A *
0N/A * @param param the string identifier of the parameter.
0N/A * @param value the parameter value.
0N/A *
0N/A * @exception InvalidParameterException if <code>param</code> is an
0N/A * invalid parameter for this signature algorithm engine,
0N/A * the parameter is already set
0N/A * and cannot be set again, a security exception occurs, and so on.
0N/A *
0N/A * @see #getParameter
0N/A *
0N/A * @deprecated Use
0N/A * {@link #setParameter(java.security.spec.AlgorithmParameterSpec)
0N/A * setParameter}.
0N/A */
0N/A @Deprecated
0N/A public final void setParameter(String param, Object value)
0N/A throws InvalidParameterException {
0N/A engineSetParameter(param, value);
0N/A }
0N/A
0N/A /**
0N/A * Initializes this signature engine with the specified parameter set.
0N/A *
0N/A * @param params the parameters
0N/A *
0N/A * @exception InvalidAlgorithmParameterException if the given parameters
0N/A * are inappropriate for this signature engine
0N/A *
0N/A * @see #getParameters
0N/A */
0N/A public final void setParameter(AlgorithmParameterSpec params)
0N/A throws InvalidAlgorithmParameterException {
0N/A engineSetParameter(params);
0N/A }
0N/A
0N/A /**
0N/A * Returns the parameters used with this signature object.
0N/A *
0N/A * <p>The returned parameters may be the same that were used to initialize
0N/A * this signature, or may contain a combination of default and randomly
0N/A * generated parameter values used by the underlying signature
0N/A * implementation if this signature requires algorithm parameters but
0N/A * was not initialized with any.
0N/A *
0N/A * @return the parameters used with this signature, or null if this
0N/A * signature does not use any parameters.
0N/A *
0N/A * @see #setParameter(AlgorithmParameterSpec)
0N/A * @since 1.4
0N/A */
0N/A public final AlgorithmParameters getParameters() {
0N/A return engineGetParameters();
0N/A }
0N/A
0N/A /**
0N/A * Gets the value of the specified algorithm parameter. This method
0N/A * supplies a general-purpose mechanism through which it is possible to
0N/A * get the various parameters of this object. A parameter may be any
0N/A * settable parameter for the algorithm, such as a parameter size, or
0N/A * a source of random bits for signature generation (if appropriate),
0N/A * or an indication of whether or not to perform a specific but optional
0N/A * computation. A uniform algorithm-specific naming scheme for each
0N/A * parameter is desirable but left unspecified at this time.
0N/A *
0N/A * @param param the string name of the parameter.
0N/A *
0N/A * @return the object that represents the parameter value, or null if
0N/A * there is none.
0N/A *
0N/A * @exception InvalidParameterException if <code>param</code> is an invalid
0N/A * parameter for this engine, or another exception occurs while
0N/A * trying to get this parameter.
0N/A *
0N/A * @see #setParameter(String, Object)
0N/A *
0N/A * @deprecated
0N/A */
0N/A @Deprecated
0N/A public final Object getParameter(String param)
0N/A throws InvalidParameterException {
0N/A return engineGetParameter(param);
0N/A }
0N/A
0N/A /**
0N/A * Returns a clone if the implementation is cloneable.
0N/A *
0N/A * @return a clone if the implementation is cloneable.
0N/A *
0N/A * @exception CloneNotSupportedException if this is called
0N/A * on an implementation that does not support <code>Cloneable</code>.
0N/A */
0N/A public Object clone() throws CloneNotSupportedException {
0N/A if (this instanceof Cloneable) {
0N/A return super.clone();
0N/A } else {
0N/A throw new CloneNotSupportedException();
0N/A }
0N/A }
0N/A
0N/A /*
0N/A * The following class allows providers to extend from SignatureSpi
0N/A * rather than from Signature. It represents a Signature with an
0N/A * encapsulated, provider-supplied SPI object (of type SignatureSpi).
0N/A * If the provider implementation is an instance of SignatureSpi, the
0N/A * getInstance() methods above return an instance of this class, with
0N/A * the SPI object encapsulated.
0N/A *
0N/A * Note: All SPI methods from the original Signature class have been
0N/A * moved up the hierarchy into a new class (SignatureSpi), which has
0N/A * been interposed in the hierarchy between the API (Signature)
0N/A * and its original parent (Object).
0N/A */
0N/A
0N/A private static class Delegate extends Signature {
0N/A
0N/A // The provider implementation (delegate)
0N/A // filled in once the provider is selected
0N/A private SignatureSpi sigSpi;
0N/A
0N/A // lock for mutex during provider selection
0N/A private final Object lock;
0N/A
0N/A // next service to try in provider selection
0N/A // null once provider is selected
0N/A private Service firstService;
0N/A
0N/A // remaining services to try in provider selection
0N/A // null once provider is selected
0N/A private Iterator<Service> serviceIterator;
0N/A
0N/A // constructor
0N/A Delegate(SignatureSpi sigSpi, String algorithm) {
0N/A super(algorithm);
0N/A this.sigSpi = sigSpi;
0N/A this.lock = null; // no lock needed
0N/A }
0N/A
0N/A // used with delayed provider selection
0N/A Delegate(Service service,
0N/A Iterator<Service> iterator, String algorithm) {
0N/A super(algorithm);
0N/A this.firstService = service;
0N/A this.serviceIterator = iterator;
0N/A this.lock = new Object();
0N/A }
0N/A
0N/A /**
0N/A * Returns a clone if the delegate is cloneable.
0N/A *
0N/A * @return a clone if the delegate is cloneable.
0N/A *
0N/A * @exception CloneNotSupportedException if this is called on a
0N/A * delegate that does not support <code>Cloneable</code>.
0N/A */
0N/A public Object clone() throws CloneNotSupportedException {
0N/A chooseFirstProvider();
0N/A if (sigSpi instanceof Cloneable) {
0N/A SignatureSpi sigSpiClone = (SignatureSpi)sigSpi.clone();
0N/A // Because 'algorithm' and 'provider' are private
0N/A // members of our supertype, we must perform a cast to
0N/A // access them.
0N/A Signature that =
0N/A new Delegate(sigSpiClone, ((Signature)this).algorithm);
0N/A that.provider = ((Signature)this).provider;
0N/A return that;
0N/A } else {
0N/A throw new CloneNotSupportedException();
0N/A }
0N/A }
0N/A
0N/A private static SignatureSpi newInstance(Service s)
0N/A throws NoSuchAlgorithmException {
0N/A if (s.getType().equals("Cipher")) {
0N/A // must be NONEwithRSA
0N/A try {
0N/A Cipher c = Cipher.getInstance(RSA_CIPHER, s.getProvider());
0N/A return new CipherAdapter(c);
0N/A } catch (NoSuchPaddingException e) {
0N/A throw new NoSuchAlgorithmException(e);
0N/A }
0N/A } else {
0N/A Object o = s.newInstance(null);
0N/A if (o instanceof SignatureSpi == false) {
0N/A throw new NoSuchAlgorithmException
0N/A ("Not a SignatureSpi: " + o.getClass().getName());
0N/A }
0N/A return (SignatureSpi)o;
0N/A }
0N/A }
0N/A
0N/A // max number of debug warnings to print from chooseFirstProvider()
0N/A private static int warnCount = 10;
0N/A
0N/A /**
0N/A * Choose the Spi from the first provider available. Used if
0N/A * delayed provider selection is not possible because initSign()/
0N/A * initVerify() is not the first method called.
0N/A */
0N/A void chooseFirstProvider() {
0N/A if (sigSpi != null) {
0N/A return;
0N/A }
0N/A synchronized (lock) {
0N/A if (sigSpi != null) {
0N/A return;
0N/A }
0N/A if (debug != null) {
0N/A int w = --warnCount;
0N/A if (w >= 0) {
0N/A debug.println("Signature.init() not first method "
0N/A + "called, disabling delayed provider selection");
0N/A if (w == 0) {
0N/A debug.println("Further warnings of this type will "
0N/A + "be suppressed");
0N/A }
0N/A new Exception("Call trace").printStackTrace();
0N/A }
0N/A }
0N/A Exception lastException = null;
0N/A while ((firstService != null) || serviceIterator.hasNext()) {
0N/A Service s;
0N/A if (firstService != null) {
0N/A s = firstService;
0N/A firstService = null;
0N/A } else {
0N/A s = serviceIterator.next();
0N/A }
0N/A if (isSpi(s) == false) {
0N/A continue;
0N/A }
0N/A try {
0N/A sigSpi = newInstance(s);
0N/A provider = s.getProvider();
0N/A // not needed any more
0N/A firstService = null;
0N/A serviceIterator = null;
0N/A return;
0N/A } catch (NoSuchAlgorithmException e) {
0N/A lastException = e;
0N/A }
0N/A }
0N/A ProviderException e = new ProviderException
0N/A ("Could not construct SignatureSpi instance");
0N/A if (lastException != null) {
0N/A e.initCause(lastException);
0N/A }
0N/A throw e;
0N/A }
0N/A }
0N/A
0N/A private void chooseProvider(int type, Key key, SecureRandom random)
0N/A throws InvalidKeyException {
0N/A synchronized (lock) {
0N/A if (sigSpi != null) {
0N/A init(sigSpi, type, key, random);
0N/A return;
0N/A }
0N/A Exception lastException = null;
0N/A while ((firstService != null) || serviceIterator.hasNext()) {
0N/A Service s;
0N/A if (firstService != null) {
0N/A s = firstService;
0N/A firstService = null;
0N/A } else {
0N/A s = serviceIterator.next();
0N/A }
0N/A // if provider says it does not support this key, ignore it
0N/A if (s.supportsParameter(key) == false) {
0N/A continue;
0N/A }
0N/A // if instance is not a SignatureSpi, ignore it
0N/A if (isSpi(s) == false) {
0N/A continue;
0N/A }
0N/A try {
0N/A SignatureSpi spi = newInstance(s);
0N/A init(spi, type, key, random);
0N/A provider = s.getProvider();
0N/A sigSpi = spi;
0N/A firstService = null;
0N/A serviceIterator = null;
0N/A return;
0N/A } catch (Exception e) {
0N/A // NoSuchAlgorithmException from newInstance()
0N/A // InvalidKeyException from init()
0N/A // RuntimeException (ProviderException) from init()
0N/A if (lastException == null) {
0N/A lastException = e;
0N/A }
0N/A }
0N/A }
0N/A // no working provider found, fail
0N/A if (lastException instanceof InvalidKeyException) {
0N/A throw (InvalidKeyException)lastException;
0N/A }
0N/A if (lastException instanceof RuntimeException) {
0N/A throw (RuntimeException)lastException;
0N/A }
0N/A String k = (key != null) ? key.getClass().getName() : "(null)";
0N/A throw new InvalidKeyException
0N/A ("No installed provider supports this key: "
0N/A + k, lastException);
0N/A }
0N/A }
0N/A
0N/A private final static int I_PUB = 1;
0N/A private final static int I_PRIV = 2;
0N/A private final static int I_PRIV_SR = 3;
0N/A
0N/A private void init(SignatureSpi spi, int type, Key key,
0N/A SecureRandom random) throws InvalidKeyException {
0N/A switch (type) {
0N/A case I_PUB:
0N/A spi.engineInitVerify((PublicKey)key);
0N/A break;
0N/A case I_PRIV:
0N/A spi.engineInitSign((PrivateKey)key);
0N/A break;
0N/A case I_PRIV_SR:
0N/A spi.engineInitSign((PrivateKey)key, random);
0N/A break;
0N/A default:
0N/A throw new AssertionError("Internal error: " + type);
0N/A }
0N/A }
0N/A
0N/A protected void engineInitVerify(PublicKey publicKey)
0N/A throws InvalidKeyException {
0N/A if (sigSpi != null) {
0N/A sigSpi.engineInitVerify(publicKey);
0N/A } else {
0N/A chooseProvider(I_PUB, publicKey, null);
0N/A }
0N/A }
0N/A
0N/A protected void engineInitSign(PrivateKey privateKey)
0N/A throws InvalidKeyException {
0N/A if (sigSpi != null) {
0N/A sigSpi.engineInitSign(privateKey);
0N/A } else {
0N/A chooseProvider(I_PRIV, privateKey, null);
0N/A }
0N/A }
0N/A
0N/A protected void engineInitSign(PrivateKey privateKey, SecureRandom sr)
0N/A throws InvalidKeyException {
0N/A if (sigSpi != null) {
0N/A sigSpi.engineInitSign(privateKey, sr);
0N/A } else {
0N/A chooseProvider(I_PRIV_SR, privateKey, sr);
0N/A }
0N/A }
0N/A
0N/A protected void engineUpdate(byte b) throws SignatureException {
0N/A chooseFirstProvider();
0N/A sigSpi.engineUpdate(b);
0N/A }
0N/A
0N/A protected void engineUpdate(byte[] b, int off, int len)
0N/A throws SignatureException {
0N/A chooseFirstProvider();
0N/A sigSpi.engineUpdate(b, off, len);
0N/A }
0N/A
0N/A protected void engineUpdate(ByteBuffer data) {
0N/A chooseFirstProvider();
0N/A sigSpi.engineUpdate(data);
0N/A }
0N/A
0N/A protected byte[] engineSign() throws SignatureException {
0N/A chooseFirstProvider();
0N/A return sigSpi.engineSign();
0N/A }
0N/A
0N/A protected int engineSign(byte[] outbuf, int offset, int len)
0N/A throws SignatureException {
0N/A chooseFirstProvider();
0N/A return sigSpi.engineSign(outbuf, offset, len);
0N/A }
0N/A
0N/A protected boolean engineVerify(byte[] sigBytes)
0N/A throws SignatureException {
0N/A chooseFirstProvider();
0N/A return sigSpi.engineVerify(sigBytes);
0N/A }
0N/A
0N/A protected boolean engineVerify(byte[] sigBytes, int offset, int length)
0N/A throws SignatureException {
0N/A chooseFirstProvider();
0N/A return sigSpi.engineVerify(sigBytes, offset, length);
0N/A }
0N/A
0N/A protected void engineSetParameter(String param, Object value)
0N/A throws InvalidParameterException {
0N/A chooseFirstProvider();
0N/A sigSpi.engineSetParameter(param, value);
0N/A }
0N/A
0N/A protected void engineSetParameter(AlgorithmParameterSpec params)
0N/A throws InvalidAlgorithmParameterException {
0N/A chooseFirstProvider();
0N/A sigSpi.engineSetParameter(params);
0N/A }
0N/A
0N/A protected Object engineGetParameter(String param)
0N/A throws InvalidParameterException {
0N/A chooseFirstProvider();
0N/A return sigSpi.engineGetParameter(param);
0N/A }
0N/A
0N/A protected AlgorithmParameters engineGetParameters() {
0N/A chooseFirstProvider();
0N/A return sigSpi.engineGetParameters();
0N/A }
0N/A }
0N/A
0N/A // adapter for RSA/ECB/PKCS1Padding ciphers
0N/A private static class CipherAdapter extends SignatureSpi {
0N/A
0N/A private final Cipher cipher;
0N/A
0N/A private ByteArrayOutputStream data;
0N/A
0N/A CipherAdapter(Cipher cipher) {
0N/A this.cipher = cipher;
0N/A }
0N/A
0N/A protected void engineInitVerify(PublicKey publicKey)
0N/A throws InvalidKeyException {
0N/A cipher.init(Cipher.DECRYPT_MODE, publicKey);
0N/A if (data == null) {
0N/A data = new ByteArrayOutputStream(128);
0N/A } else {
0N/A data.reset();
0N/A }
0N/A }
0N/A
0N/A protected void engineInitSign(PrivateKey privateKey)
0N/A throws InvalidKeyException {
0N/A cipher.init(Cipher.ENCRYPT_MODE, privateKey);
0N/A data = null;
0N/A }
0N/A
0N/A protected void engineInitSign(PrivateKey privateKey,
0N/A SecureRandom random) throws InvalidKeyException {
0N/A cipher.init(Cipher.ENCRYPT_MODE, privateKey, random);
0N/A data = null;
0N/A }
0N/A
0N/A protected void engineUpdate(byte b) throws SignatureException {
0N/A engineUpdate(new byte[] {b}, 0, 1);
0N/A }
0N/A
0N/A protected void engineUpdate(byte[] b, int off, int len)
0N/A throws SignatureException {
0N/A if (data != null) {
0N/A data.write(b, off, len);
0N/A return;
0N/A }
0N/A byte[] out = cipher.update(b, off, len);
0N/A if ((out != null) && (out.length != 0)) {
0N/A throw new SignatureException
0N/A ("Cipher unexpectedly returned data");
0N/A }
0N/A }
0N/A
0N/A protected byte[] engineSign() throws SignatureException {
0N/A try {
0N/A return cipher.doFinal();
0N/A } catch (IllegalBlockSizeException e) {
0N/A throw new SignatureException("doFinal() failed", e);
0N/A } catch (BadPaddingException e) {
0N/A throw new SignatureException("doFinal() failed", e);
0N/A }
0N/A }
0N/A
0N/A protected boolean engineVerify(byte[] sigBytes)
0N/A throws SignatureException {
0N/A try {
0N/A byte[] out = cipher.doFinal(sigBytes);
0N/A byte[] dataBytes = data.toByteArray();
0N/A data.reset();
0N/A return Arrays.equals(out, dataBytes);
0N/A } catch (BadPaddingException e) {
0N/A // e.g. wrong public key used
0N/A // return false rather than throwing exception
0N/A return false;
0N/A } catch (IllegalBlockSizeException e) {
0N/A throw new SignatureException("doFinal() failed", e);
0N/A }
0N/A }
0N/A
0N/A protected void engineSetParameter(String param, Object value)
0N/A throws InvalidParameterException {
0N/A throw new InvalidParameterException("Parameters not supported");
0N/A }
0N/A
0N/A protected Object engineGetParameter(String param)
0N/A throws InvalidParameterException {
0N/A throw new InvalidParameterException("Parameters not supported");
0N/A }
0N/A
0N/A }
0N/A
0N/A}