001    /* SignatureSpi.java --- Signature Service Provider Interface
002       Copyright (C) 1999, 2003, Free Software Foundation, Inc.
003    
004    This file is part of GNU Classpath.
005    
006    GNU Classpath is free software; you can redistribute it and/or modify
007    it under the terms of the GNU General Public License as published by
008    the Free Software Foundation; either version 2, or (at your option)
009    any later version.
010    
011    GNU Classpath is distributed in the hope that it will be useful, but
012    WITHOUT ANY WARRANTY; without even the implied warranty of
013    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
014    General Public License for more details.
015    
016    You should have received a copy of the GNU General Public License
017    along with GNU Classpath; see the file COPYING.  If not, write to the
018    Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
019    02110-1301 USA.
020    
021    Linking this library statically or dynamically with other modules is
022    making a combined work based on this library.  Thus, the terms and
023    conditions of the GNU General Public License cover the whole
024    combination.
025    
026    As a special exception, the copyright holders of this library give you
027    permission to link this library with independent modules to produce an
028    executable, regardless of the license terms of these independent
029    modules, and to copy and distribute the resulting executable under
030    terms of your choice, provided that you also meet, for each linked
031    independent module, the terms and conditions of the license of that
032    module.  An independent module is a module which is not derived from
033    or based on this library.  If you modify this library, you may extend
034    this exception to your version of the library, but you are not
035    obligated to do so.  If you do not wish to do so, delete this
036    exception statement from your version. */
037    
038    package java.security;
039    
040    import java.nio.ByteBuffer;
041    import java.security.spec.AlgorithmParameterSpec;
042    
043    /**
044     * <code>SignatureSpi</code> defines the Service Provider Interface (SPI) for
045     * the {@link Signature} class. The signature class provides an interface to a
046     * digital signature algorithm. Digital signatures are used for authentication
047     * and integrity of data.
048     *
049     * @author Mark Benvenuto (ivymccough@worldnet.att.net)
050     * @since 1.2
051     * @see Signature
052     */
053    public abstract class SignatureSpi
054    {
055      /** Source of randomness. */
056      protected SecureRandom appRandom;
057    
058      /**
059       * Creates a new instance of <code>SignatureSpi</code>.
060       */
061      public SignatureSpi()
062      {
063        appRandom = null;
064      }
065    
066      /**
067       * Initializes this instance with the public key for verification purposes.
068       * 
069       * @param publicKey
070       *          the public key to verify with.
071       * @throws InvalidKeyException
072       *           if the key is invalid.
073       */
074      protected abstract void engineInitVerify(PublicKey publicKey)
075        throws InvalidKeyException;
076    
077      /**
078       * Initializes this instance with the private key for signing purposes.
079       * 
080       * @param privateKey
081       *          the private key to sign with.
082       * @throws InvalidKeyException
083       *           if the key is invalid.
084       */
085      protected abstract void engineInitSign(PrivateKey privateKey)
086        throws InvalidKeyException;
087    
088      /**
089       * Initializes this instance with the private key and source of randomness for
090       * signing purposes.
091       * 
092       * <p>This method cannot be abstract for backward compatibility reasons.</p>
093       * 
094       * @param privateKey
095       *          the private key to sign with.
096       * @param random
097       *          the {@link SecureRandom} to use.
098       * @throws InvalidKeyException
099       *           if the key is invalid.
100       * @since 1.2
101       */
102      protected void engineInitSign(PrivateKey privateKey, SecureRandom random)
103        throws InvalidKeyException
104      {
105        appRandom = random;
106        engineInitSign(privateKey);
107      }
108    
109      /**
110       * Updates the data to be signed or verified with the specified byte.
111       * 
112       * @param b
113       *          byte to update with.
114       * @throws SignatureException
115       *           if the engine is not properly initialized.
116       */
117      protected abstract void engineUpdate(byte b) throws SignatureException;
118    
119      /**
120       * Updates the data to be signed or verified with the specified bytes.
121       * 
122       * @param b
123       *          the array of bytes to use.
124       * @param off
125       *          the offset to start at in the array.
126       * @param len
127       *          the number of the bytes to use from the array.
128       * @throws SignatureException
129       *           if the engine is not properly initialized.
130       */
131      protected abstract void engineUpdate(byte[] b, int off, int len)
132        throws SignatureException;
133    
134      /**
135       * Update this signature with the {@link java.nio.Buffer#remaining()}
136       * bytes of the given buffer.
137       * 
138       * @param input The input buffer.
139       * @throws IllegalStateException if the engine is not properly initialized.
140       */
141      protected void engineUpdate(ByteBuffer input)
142      {
143        byte[] buf = new byte[4096];
144        while (input.hasRemaining())
145          {
146            int l = Math.min(input.remaining(), buf.length);
147            input.get(buf, 0, l);
148            try
149              {
150                engineUpdate(buf, 0, l);
151              }
152            catch (SignatureException se)
153              {
154                throw new IllegalStateException(se);
155              }
156          }
157      }
158      
159      /**
160       * Returns the signature bytes of all the data fed to this instance. The
161       * format of the output depends on the underlying signature algorithm.
162       * 
163       * @return the signature bytes.
164       * @throws SignatureException
165       *           if the engine is not properly initialized.
166       */
167      protected abstract byte[] engineSign() throws SignatureException;
168    
169      /**
170       * Generates signature bytes of all the data fed to this instance and stores
171       * the result in the designated array. The format of the output depends on
172       * the underlying signature algorithm.
173       * 
174       * <p>This method cannot be abstract for backward compatibility reasons.
175       * After calling this method, the signature is reset to its initial state and
176       * can be used to generate additional signatures.</p>
177       * 
178       * <p><b>IMPLEMENTATION NOTE:</b>: Neither this method nor the GNU provider
179       * will return partial digests. If <code>len</code> is less than the
180       * signature length, this method will throw a {@link SignatureException}. If
181       * it is greater than or equal then it is ignored.</p>
182       * 
183       * @param outbuf
184       *          the array of bytes to store the result in.
185       * @param offset
186       *          the offset to start at in the array.
187       * @param len
188       *          the number of the bytes to use in the array.
189       * @return the real number of bytes used.
190       * @throws SignatureException
191       *           if the engine is not properly initialized.
192       * @since 1.2
193       */
194      protected int engineSign(byte[] outbuf, int offset, int len)
195        throws SignatureException
196      {
197        byte[] tmp = engineSign();
198        if (tmp.length > len)
199          throw new SignatureException("Invalid Length");
200    
201        System.arraycopy(outbuf, offset, tmp, 0, tmp.length);
202        return tmp.length;
203      }
204    
205      /**
206       * Verifies a designated signature.
207       * 
208       * @param sigBytes
209       *          the signature bytes to verify.
210       * @return <code>true</code> if verified, <code>false</code> otherwise.
211       * @throws SignatureException
212       *           if the engine is not properly initialized or if it is the wrong
213       *           signature.
214       */
215      protected abstract boolean engineVerify(byte[] sigBytes)
216        throws SignatureException;
217    
218      /**
219       * Convenience method which calls the method with the same name and one
220       * argument after copying the designated bytes into a temporary byte array.
221       * Subclasses may override this method for performance reasons.
222       * 
223       * @param sigBytes
224       *          the array of bytes to use.
225       * @param offset
226       *          the offset to start from in the array of bytes.
227       * @param length
228       *          the number of bytes to use, starting at offset.
229       * @return <code>true</code> if verified, <code>false</code> otherwise.
230       * @throws SignatureException
231       *           if the engine is not properly initialized.
232       */
233      protected boolean engineVerify(byte[] sigBytes, int offset, int length)
234        throws SignatureException
235      {
236        byte[] tmp = new byte[length];
237        System.arraycopy(sigBytes, offset, tmp, 0, length);
238        return engineVerify(tmp);
239      }
240    
241      /**
242       * Sets the specified algorithm parameter to the specified value.
243       * 
244       * @param param
245       *          the parameter name.
246       * @param value
247       *          the parameter value.
248       * @throws InvalidParameterException
249       *           if the parameter invalid, the parameter is already set and
250       *           cannot be changed, a security exception occured, etc.
251       * @deprecated use the other setParameter.
252       */
253      protected abstract void engineSetParameter(String param, Object value)
254        throws InvalidParameterException;
255    
256      /**
257       * Sets the signature engine with the specified {@link AlgorithmParameterSpec}.
258       * 
259       * <p>This method cannot be abstract for backward compatibility reasons. By
260       * default it always throws {@link UnsupportedOperationException} unless
261       * overridden.</p>
262       * 
263       * @param params
264       *          the parameters.
265       * @throws InvalidParameterException
266       *           if the parameter is invalid, the parameter is already set and
267       *           cannot be changed, a security exception occured, etc.
268       */
269      protected void engineSetParameter(AlgorithmParameterSpec params)
270        throws InvalidAlgorithmParameterException
271      {
272        throw new UnsupportedOperationException();
273      }
274    
275      /**
276       * The default implementaion of this method always throws a
277       * {@link UnsupportedOperationException}. It MUST be overridden by concrete
278       * implementations to return the appropriate {@link AlgorithmParameters} for
279       * this signature engine (or <code>null</code> when that engine does not use
280       * any parameters.
281       * 
282       * @return the parameters used with this signature engine, or
283       *         <code>null</code> if it does not use any parameters.
284       * @throws UnsupportedOperationException
285       *           always.
286       */
287      protected AlgorithmParameters engineGetParameters()
288      {
289        throw new UnsupportedOperationException();
290      }
291    
292      /**
293       * Returns the value for the specified algorithm parameter.
294       * 
295       * @param param
296       *          the parameter name.
297       * @return the parameter value.
298       * @throws InvalidParameterException
299       *           if the parameter is invalid.
300       * @deprecated use the other getParameter
301       */
302      protected abstract Object engineGetParameter(String param)
303        throws InvalidParameterException;
304    
305      /**
306       * Returns a clone of this instance.
307       * 
308       * @return a clone of this instance.
309       * @throws CloneNotSupportedException
310       *           if the implementation does not support cloning.
311       */
312      public Object clone() throws CloneNotSupportedException
313      {
314        return super.clone();
315      }
316    }