KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > org > apache > xml > internal > security > algorithms > implementations > IntegrityHmac


1 /*
2  * Copyright 1999-2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */

17 package com.sun.org.apache.xml.internal.security.algorithms.implementations;
18
19
20
21 import java.security.InvalidAlgorithmParameterException JavaDoc;
22 import java.security.InvalidKeyException JavaDoc;
23 import java.security.Key JavaDoc;
24 import java.security.SecureRandom JavaDoc;
25 import java.security.spec.AlgorithmParameterSpec JavaDoc;
26
27 import javax.crypto.Mac;
28 import javax.crypto.SecretKey;
29
30 import com.sun.org.apache.xml.internal.security.algorithms.JCEMapper;
31 import com.sun.org.apache.xml.internal.security.algorithms.MessageDigestAlgorithm;
32 import com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithmSpi;
33 import com.sun.org.apache.xml.internal.security.signature.XMLSignature;
34 import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException;
35 import com.sun.org.apache.xml.internal.security.utils.Constants;
36 import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
37 import org.w3c.dom.Document JavaDoc;
38 import org.w3c.dom.Element JavaDoc;
39 import org.w3c.dom.Text JavaDoc;
40
41
42 /**
43  *
44  * @author $Author: raul $
45  */

46 public abstract class IntegrityHmac extends SignatureAlgorithmSpi {
47     
48    /** {@link java.util.logging} logging facility */
49     static java.util.logging.Logger JavaDoc log =
50         java.util.logging.Logger.getLogger(IntegrityHmacSHA1.class.getName());
51
52    /**
53     * Method engineGetURI
54     *
55     *@inheritDoc
56     */

57    public abstract String JavaDoc engineGetURI();
58
59    /** Field _macAlgorithm */
60    private Mac _macAlgorithm = null;
61
62    /** Field _HMACOutputLength */
63    int _HMACOutputLength = 0;
64
65    /**
66     * Method IntegrityHmacSHA1das
67     *
68     * @throws XMLSignatureException
69     */

70    public IntegrityHmac() throws XMLSignatureException {
71
72       String JavaDoc algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI());
73       if (true)
74         if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "Created IntegrityHmacSHA1 using " + algorithmID);
75
76       try {
77          this._macAlgorithm = Mac.getInstance(algorithmID);
78       } catch (java.security.NoSuchAlgorithmException JavaDoc ex) {
79          Object JavaDoc[] exArgs = { algorithmID,
80                              ex.getLocalizedMessage() };
81
82          throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
83       }
84    }
85
86    /**
87     * Proxy method for {@link java.security.Signature#setParameter(java.security.spec.AlgorithmParameterSpec)}
88     * which is executed on the internal {@link java.security.Signature} object.
89     *
90     * @param params
91     * @throws XMLSignatureException
92     */

93    protected void engineSetParameter(AlgorithmParameterSpec JavaDoc params)
94            throws XMLSignatureException {
95       throw new XMLSignatureException("empty");
96    }
97
98    /**
99     * Proxy method for {@link java.security.Signature#verify(byte[])}
100     * which is executed on the internal {@link java.security.Signature} object.
101     *
102     * @param signature
103     * @return true if the signature is correct
104     * @throws XMLSignatureException
105     */

106    protected boolean engineVerify(byte[] signature)
107            throws XMLSignatureException {
108
109       try {
110          byte[] completeResult = this._macAlgorithm.doFinal();
111
112          if ((this._HMACOutputLength == 0) || (this._HMACOutputLength >= 160)) {
113             return MessageDigestAlgorithm.isEqual(completeResult, signature);
114          }
115          byte[] stripped = IntegrityHmac.reduceBitLength(completeResult,
116                                  this._HMACOutputLength);
117          return MessageDigestAlgorithm.isEqual(stripped, signature);
118       } catch (IllegalStateException JavaDoc ex) {
119          throw new XMLSignatureException("empty", ex);
120       }
121    }
122
123    /**
124     * Proxy method for {@link java.security.Signature#initVerify(java.security.PublicKey)}
125     * which is executed on the internal {@link java.security.Signature} object.
126     *
127     * @param secretKey
128     * @throws XMLSignatureException
129     */

130    protected void engineInitVerify(Key JavaDoc secretKey) throws XMLSignatureException {
131
132       if (!(secretKey instanceof SecretKey)) {
133          String JavaDoc supplied = secretKey.getClass().getName();
134          String JavaDoc needed = SecretKey.class.getName();
135          Object JavaDoc exArgs[] = { supplied, needed };
136
137          throw new XMLSignatureException("algorithms.WrongKeyForThisOperation",
138                                          exArgs);
139       }
140
141       try {
142          this._macAlgorithm.init(secretKey);
143       } catch (InvalidKeyException JavaDoc ex) {
144          throw new XMLSignatureException("empty", ex);
145       }
146    }
147
148    /**
149     * Proxy method for {@link java.security.Signature#sign()}
150     * which is executed on the internal {@link java.security.Signature} object.
151     *
152     * @return the result of the {@link java.security.Signature#sign()} method
153     * @throws XMLSignatureException
154     */

155    protected byte[] engineSign() throws XMLSignatureException {
156
157       try {
158          byte[] completeResult = this._macAlgorithm.doFinal();
159
160          if ((this._HMACOutputLength == 0) || (this._HMACOutputLength >= 160)) {
161             return completeResult;
162          }
163           return IntegrityHmac.reduceBitLength(completeResult,
164                                                  this._HMACOutputLength);
165          
166       } catch (IllegalStateException JavaDoc ex) {
167          throw new XMLSignatureException("empty", ex);
168       }
169    }
170
171    /**
172     * Method reduceBitLength
173     *
174     * @param completeResult
175     * @return the reduced bits.
176     * @param length
177     *
178     */

179    private static byte[] reduceBitLength(byte completeResult[], int length) {
180
181       int bytes = length / 8;
182       int abits = length % 8;
183       byte[] strippedResult = new byte[bytes + ((abits == 0)
184                                                 ? 0
185                                                 : 1)];
186
187       System.arraycopy(completeResult, 0, strippedResult, 0, bytes);
188
189       if (abits > 0) {
190          byte[] MASK = { (byte) 0x00, (byte) 0x80, (byte) 0xC0, (byte) 0xE0,
191                          (byte) 0xF0, (byte) 0xF8, (byte) 0xFC, (byte) 0xFE };
192
193          strippedResult[bytes] = (byte) (completeResult[bytes] & MASK[abits]);
194       }
195
196       return strippedResult;
197    }
198
199    /**
200     * Method engineInitSign
201     *
202     * @param secretKey
203     * @throws XMLSignatureException
204     */

205    protected void engineInitSign(Key JavaDoc secretKey) throws XMLSignatureException {
206
207       if (!(secretKey instanceof SecretKey)) {
208          String JavaDoc supplied = secretKey.getClass().getName();
209          String JavaDoc needed = SecretKey.class.getName();
210          Object JavaDoc exArgs[] = { supplied, needed };
211
212          throw new XMLSignatureException("algorithms.WrongKeyForThisOperation",
213                                          exArgs);
214       }
215
216       try {
217          this._macAlgorithm.init(secretKey);
218       } catch (InvalidKeyException JavaDoc ex) {
219          throw new XMLSignatureException("empty", ex);
220       }
221    }
222
223    /**
224     * Method engineInitSign
225     *
226     * @param secretKey
227     * @param algorithmParameterSpec
228     * @throws XMLSignatureException
229     */

230    protected void engineInitSign(
231            Key JavaDoc secretKey, AlgorithmParameterSpec JavaDoc algorithmParameterSpec)
232               throws XMLSignatureException {
233
234       if (!(secretKey instanceof SecretKey)) {
235          String JavaDoc supplied = secretKey.getClass().getName();
236          String JavaDoc needed = SecretKey.class.getName();
237          Object JavaDoc exArgs[] = { supplied, needed };
238
239          throw new XMLSignatureException("algorithms.WrongKeyForThisOperation",
240                                          exArgs);
241       }
242
243       try {
244          this._macAlgorithm.init(secretKey, algorithmParameterSpec);
245       } catch (InvalidKeyException JavaDoc ex) {
246          throw new XMLSignatureException("empty", ex);
247       } catch (InvalidAlgorithmParameterException JavaDoc ex) {
248          throw new XMLSignatureException("empty", ex);
249       }
250    }
251
252    /**
253     * Method engineInitSign
254     *
255     * @param secretKey
256     * @param secureRandom
257     * @throws XMLSignatureException
258     */

259    protected void engineInitSign(Key JavaDoc secretKey, SecureRandom JavaDoc secureRandom)
260            throws XMLSignatureException {
261       throw new XMLSignatureException("algorithms.CannotUseSecureRandomOnMAC");
262    }
263
264    /**
265     * Proxy method for {@link java.security.Signature#update(byte[])}
266     * which is executed on the internal {@link java.security.Signature} object.
267     *
268     * @param input
269     * @throws XMLSignatureException
270     */

271    protected void engineUpdate(byte[] input) throws XMLSignatureException {
272
273       try {
274          this._macAlgorithm.update(input);
275       } catch (IllegalStateException JavaDoc ex) {
276          throw new XMLSignatureException("empty", ex);
277       }
278    }
279
280    /**
281     * Proxy method for {@link java.security.Signature#update(byte)}
282     * which is executed on the internal {@link java.security.Signature} object.
283     *
284     * @param input
285     * @throws XMLSignatureException
286     */

287    protected void engineUpdate(byte input) throws XMLSignatureException {
288
289       try {
290          this._macAlgorithm.update(input);
291       } catch (IllegalStateException JavaDoc ex) {
292          throw new XMLSignatureException("empty", ex);
293       }
294    }
295
296    /**
297     * Proxy method for {@link java.security.Signature#update(byte[], int, int)}
298     * which is executed on the internal {@link java.security.Signature} object.
299     *
300     * @param buf
301     * @param offset
302     * @param len
303     * @throws XMLSignatureException
304     */

305    protected void engineUpdate(byte buf[], int offset, int len)
306            throws XMLSignatureException {
307
308       try {
309          this._macAlgorithm.update(buf, offset, len);
310       } catch (IllegalStateException JavaDoc ex) {
311          throw new XMLSignatureException("empty", ex);
312       }
313    }
314
315    /**
316     * Method engineGetJCEAlgorithmString
317     * @inheritDoc
318     *
319     */

320    protected String JavaDoc engineGetJCEAlgorithmString() {
321
322       if (log.isLoggable(java.util.logging.Level.FINE)) log.log(java.util.logging.Level.FINE, "engineGetJCEAlgorithmString()");
323
324       return this._macAlgorithm.getAlgorithm();
325    }
326
327    /**
328     * Method engineGetJCEAlgorithmString
329     *
330     * @inheritDoc
331     */

332    protected String JavaDoc engineGetJCEProviderName() {
333       return this._macAlgorithm.getProvider().getName();
334    }
335
336    /**
337     * Method engineSetHMACOutputLength
338     *
339     * @param HMACOutputLength
340     */

341    protected void engineSetHMACOutputLength(int HMACOutputLength) {
342       this._HMACOutputLength = HMACOutputLength;
343    }
344
345    /**
346     * Method engineGetContextFromElement
347     *
348     * @param element
349     */

350    protected void engineGetContextFromElement(Element JavaDoc element) {
351
352       super.engineGetContextFromElement(element);
353
354       if (element == null) {
355          throw new IllegalArgumentException JavaDoc("element null");
356       }
357
358              Text JavaDoc hmaclength =XMLUtils.selectDsNodeText(element.getFirstChild(),
359                     Constants._TAG_HMACOUTPUTLENGTH,0);
360
361             if (hmaclength != null) {
362                this._HMACOutputLength = Integer.parseInt(hmaclength.getData());
363             }
364       
365    }
366
367    /**
368     * Method engineAddContextToElement
369     *
370     * @param element
371     */

372    public void engineAddContextToElement(Element JavaDoc element)
373            {
374
375       if (element == null) {
376          throw new IllegalArgumentException JavaDoc("null element");
377       }
378
379       if (this._HMACOutputLength != 0) {
380          Document JavaDoc doc = element.getOwnerDocument();
381          Element JavaDoc HMElem = XMLUtils.createElementInSignatureSpace(doc,
382                              Constants._TAG_HMACOUTPUTLENGTH);
383          Text JavaDoc HMText =
384             doc.createTextNode(new Integer JavaDoc(this._HMACOutputLength).toString());
385
386          HMElem.appendChild(HMText);
387          XMLUtils.addReturnToElement(element);
388          element.appendChild(HMElem);
389          XMLUtils.addReturnToElement(element);
390       }
391    }
392
393    /**
394     * Class IntegrityHmacSHA1
395     *
396     * @author $Author: raul $
397     * @version $Revision: 1.13 $
398     */

399    public static class IntegrityHmacSHA1 extends IntegrityHmac {
400
401       /**
402        * Constructor IntegrityHmacSHA1
403        *
404        * @throws XMLSignatureException
405        */

406       public IntegrityHmacSHA1() throws XMLSignatureException {
407          super();
408       }
409
410       /**
411        * Method engineGetURI
412        * @inheritDoc
413        *
414        */

415       public String JavaDoc engineGetURI() {
416          return XMLSignature.ALGO_ID_MAC_HMAC_SHA1;
417       }
418    }
419
420    /**
421     * Class IntegrityHmacSHA256
422     *
423     * @author $Author: raul $
424     * @version $Revision: 1.13 $
425     */

426    public static class IntegrityHmacSHA256 extends IntegrityHmac {
427
428       /**
429        * Constructor IntegrityHmacSHA256
430        *
431        * @throws XMLSignatureException
432        */

433       public IntegrityHmacSHA256() throws XMLSignatureException {
434          super();
435       }
436
437       /**
438        * Method engineGetURI
439        *
440        * @inheritDoc
441        */

442       public String JavaDoc engineGetURI() {
443          return XMLSignature.ALGO_ID_MAC_HMAC_SHA256;
444       }
445    }
446
447    /**
448     * Class IntegrityHmacSHA384
449     *
450     * @author $Author: raul $
451     * @version $Revision: 1.13 $
452     */

453    public static class IntegrityHmacSHA384 extends IntegrityHmac {
454
455       /**
456        * Constructor IntegrityHmacSHA384
457        *
458        * @throws XMLSignatureException
459        */

460       public IntegrityHmacSHA384() throws XMLSignatureException {
461          super();
462       }
463
464       /**
465        * Method engineGetURI
466        * @inheritDoc
467        *
468        */

469       public String JavaDoc engineGetURI() {
470          return XMLSignature.ALGO_ID_MAC_HMAC_SHA384;
471       }
472    }
473
474    /**
475     * Class IntegrityHmacSHA512
476     *
477     * @author $Author: raul $
478     * @version $Revision: 1.13 $
479     */

480    public static class IntegrityHmacSHA512 extends IntegrityHmac {
481
482       /**
483        * Constructor IntegrityHmacSHA512
484        *
485        * @throws XMLSignatureException
486        */

487       public IntegrityHmacSHA512() throws XMLSignatureException {
488          super();
489       }
490
491       /**
492        * Method engineGetURI
493        * @inheritDoc
494        *
495        */

496       public String JavaDoc engineGetURI() {
497          return XMLSignature.ALGO_ID_MAC_HMAC_SHA512;
498       }
499    }
500
501    /**
502     * Class IntegrityHmacRIPEMD160
503     *
504     * @author $Author: raul $
505     * @version $Revision: 1.13 $
506     */

507    public static class IntegrityHmacRIPEMD160 extends IntegrityHmac {
508
509       /**
510        * Constructor IntegrityHmacRIPEMD160
511        *
512        * @throws XMLSignatureException
513        */

514       public IntegrityHmacRIPEMD160() throws XMLSignatureException {
515          super();
516       }
517
518       /**
519        * Method engineGetURI
520        *
521        * @inheritDoc
522        */

523       public String JavaDoc engineGetURI() {
524          return XMLSignature.ALGO_ID_MAC_HMAC_RIPEMD160;
525       }
526    }
527
528    /**
529     * Class IntegrityHmacMD5
530     *
531     * @author $Author: raul $
532     * @version $Revision: 1.13 $
533     */

534    public static class IntegrityHmacMD5 extends IntegrityHmac {
535
536       /**
537        * Constructor IntegrityHmacMD5
538        *
539        * @throws XMLSignatureException
540        */

541       public IntegrityHmacMD5() throws XMLSignatureException {
542          super();
543       }
544
545       /**
546        * Method engineGetURI
547        *
548        * @inheritDoc
549        */

550       public String JavaDoc engineGetURI() {
551          return XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5;
552       }
553    }
554 }
555
Popular Tags