aboutsummaryrefslogtreecommitdiff
path: root/src/share/classes/com/sun/org/apache/xml/internal/security/algorithms/implementations/IntegrityHmac.java
blob: d3495bb567f4ed2402a7876e0ee91b4a22e12f2d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
/*
 * reserved comment block
 * DO NOT REMOVE OR ALTER!
 */
/*
 * Copyright  1999-2004 The Apache Software Foundation.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package com.sun.org.apache.xml.internal.security.algorithms.implementations;



import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;

import javax.crypto.Mac;
import javax.crypto.SecretKey;

import com.sun.org.apache.xml.internal.security.algorithms.JCEMapper;
import com.sun.org.apache.xml.internal.security.algorithms.MessageDigestAlgorithm;
import com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithmSpi;
import com.sun.org.apache.xml.internal.security.signature.XMLSignature;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException;
import com.sun.org.apache.xml.internal.security.utils.Constants;
import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;


/**
 *
 * @author $Author: mullan $
 */
public abstract class IntegrityHmac extends SignatureAlgorithmSpi {

   /** {@link java.util.logging} logging facility */
    static java.util.logging.Logger log =
        java.util.logging.Logger.getLogger(IntegrityHmacSHA1.class.getName());

   /**
    * Method engineGetURI
    *
    *@inheritDoc
    */
   public abstract String engineGetURI();

   /** Field _macAlgorithm */
   private Mac _macAlgorithm = null;

   /** Field _HMACOutputLength */
   int _HMACOutputLength = 0;

   /**
    * Method IntegrityHmacSHA1das
    *
    * @throws XMLSignatureException
    */
   public IntegrityHmac() throws XMLSignatureException {

      String algorithmID = JCEMapper.translateURItoJCEID(this.engineGetURI());
      if (log.isLoggable(java.util.logging.Level.FINE))
        log.log(java.util.logging.Level.FINE, "Created IntegrityHmacSHA1 using " + algorithmID);

      try {
         this._macAlgorithm = Mac.getInstance(algorithmID);
      } catch (java.security.NoSuchAlgorithmException ex) {
         Object[] exArgs = { algorithmID,
                             ex.getLocalizedMessage() };

         throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs);
      }
   }

   /**
    * Proxy method for {@link java.security.Signature#setParameter(java.security.spec.AlgorithmParameterSpec)}
    * which is executed on the internal {@link java.security.Signature} object.
    *
    * @param params
    * @throws XMLSignatureException
    */
   protected void engineSetParameter(AlgorithmParameterSpec params)
           throws XMLSignatureException {
      throw new XMLSignatureException("empty");
   }

   public void reset() {
           _HMACOutputLength=0;
   }

   /**
    * Proxy method for {@link java.security.Signature#verify(byte[])}
    * which is executed on the internal {@link java.security.Signature} object.
    *
    * @param signature
    * @return true if the signature is correct
    * @throws XMLSignatureException
    */
   protected boolean engineVerify(byte[] signature)
           throws XMLSignatureException {

      try {
         byte[] completeResult = this._macAlgorithm.doFinal();

         if ((this._HMACOutputLength == 0) || (this._HMACOutputLength >= 160)) {
            return MessageDigestAlgorithm.isEqual(completeResult, signature);
         }
         byte[] stripped = IntegrityHmac.reduceBitLength(completeResult,
                                 this._HMACOutputLength);
         return MessageDigestAlgorithm.isEqual(stripped, signature);
      } catch (IllegalStateException ex) {
         throw new XMLSignatureException("empty", ex);
      }
   }

   /**
    * Proxy method for {@link java.security.Signature#initVerify(java.security.PublicKey)}
    * which is executed on the internal {@link java.security.Signature} object.
    *
    * @param secretKey
    * @throws XMLSignatureException
    */
   protected void engineInitVerify(Key secretKey) throws XMLSignatureException {

      if (!(secretKey instanceof SecretKey)) {
         String supplied = secretKey.getClass().getName();
         String needed = SecretKey.class.getName();
         Object exArgs[] = { supplied, needed };

         throw new XMLSignatureException("algorithms.WrongKeyForThisOperation",
                                         exArgs);
      }

      try {
         this._macAlgorithm.init(secretKey);
      } catch (InvalidKeyException ex) {
            // reinstantiate Mac object to work around bug in JDK
            // see: http://bugs.sun.com/view_bug.do?bug_id=4953555
            Mac mac = this._macAlgorithm;
            try {
                this._macAlgorithm = Mac.getInstance
                    (_macAlgorithm.getAlgorithm());
            } catch (Exception e) {
                // this shouldn't occur, but if it does, restore previous Mac
                if (log.isLoggable(java.util.logging.Level.FINE)) {
                    log.log(java.util.logging.Level.FINE, "Exception when reinstantiating Mac:" + e);
                }
                this._macAlgorithm = mac;
            }
            throw new XMLSignatureException("empty", ex);
      }
   }

   /**
    * Proxy method for {@link java.security.Signature#sign()}
    * which is executed on the internal {@link java.security.Signature} object.
    *
    * @return the result of the {@link java.security.Signature#sign()} method
    * @throws XMLSignatureException
    */
   protected byte[] engineSign() throws XMLSignatureException {

      try {
         byte[] completeResult = this._macAlgorithm.doFinal();

         if ((this._HMACOutputLength == 0) || (this._HMACOutputLength >= 160)) {
            return completeResult;
         }
          return IntegrityHmac.reduceBitLength(completeResult,
                                                 this._HMACOutputLength);

      } catch (IllegalStateException ex) {
         throw new XMLSignatureException("empty", ex);
      }
   }

   /**
    * Method reduceBitLength
    *
    * @param completeResult
    * @return the reduced bits.
    * @param length
    *
    */
   private static byte[] reduceBitLength(byte completeResult[], int length) {

      int bytes = length / 8;
      int abits = length % 8;
      byte[] strippedResult = new byte[bytes + ((abits == 0)
                                                ? 0
                                                : 1)];

      System.arraycopy(completeResult, 0, strippedResult, 0, bytes);

      if (abits > 0) {
         byte[] MASK = { (byte) 0x00, (byte) 0x80, (byte) 0xC0, (byte) 0xE0,
                         (byte) 0xF0, (byte) 0xF8, (byte) 0xFC, (byte) 0xFE };

         strippedResult[bytes] = (byte) (completeResult[bytes] & MASK[abits]);
      }

      return strippedResult;
   }

   /**
    * Method engineInitSign
    *
    * @param secretKey
    * @throws XMLSignatureException
    */
   protected void engineInitSign(Key secretKey) throws XMLSignatureException {

      if (!(secretKey instanceof SecretKey)) {
         String supplied = secretKey.getClass().getName();
         String needed = SecretKey.class.getName();
         Object exArgs[] = { supplied, needed };

         throw new XMLSignatureException("algorithms.WrongKeyForThisOperation",
                                         exArgs);
      }

      try {
         this._macAlgorithm.init(secretKey);
      } catch (InvalidKeyException ex) {
         throw new XMLSignatureException("empty", ex);
      }
   }

   /**
    * Method engineInitSign
    *
    * @param secretKey
    * @param algorithmParameterSpec
    * @throws XMLSignatureException
    */
   protected void engineInitSign(
           Key secretKey, AlgorithmParameterSpec algorithmParameterSpec)
              throws XMLSignatureException {

      if (!(secretKey instanceof SecretKey)) {
         String supplied = secretKey.getClass().getName();
         String needed = SecretKey.class.getName();
         Object exArgs[] = { supplied, needed };

         throw new XMLSignatureException("algorithms.WrongKeyForThisOperation",
                                         exArgs);
      }

      try {
         this._macAlgorithm.init(secretKey, algorithmParameterSpec);
      } catch (InvalidKeyException ex) {
         throw new XMLSignatureException("empty", ex);
      } catch (InvalidAlgorithmParameterException ex) {
         throw new XMLSignatureException("empty", ex);
      }
   }

   /**
    * Method engineInitSign
    *
    * @param secretKey
    * @param secureRandom
    * @throws XMLSignatureException
    */
   protected void engineInitSign(Key secretKey, SecureRandom secureRandom)
           throws XMLSignatureException {
      throw new XMLSignatureException("algorithms.CannotUseSecureRandomOnMAC");
   }

   /**
    * Proxy method for {@link java.security.Signature#update(byte[])}
    * which is executed on the internal {@link java.security.Signature} object.
    *
    * @param input
    * @throws XMLSignatureException
    */
   protected void engineUpdate(byte[] input) throws XMLSignatureException {

      try {
         this._macAlgorithm.update(input);
      } catch (IllegalStateException ex) {
         throw new XMLSignatureException("empty", ex);
      }
   }

   /**
    * Proxy method for {@link java.security.Signature#update(byte)}
    * which is executed on the internal {@link java.security.Signature} object.
    *
    * @param input
    * @throws XMLSignatureException
    */
   protected void engineUpdate(byte input) throws XMLSignatureException {

      try {
         this._macAlgorithm.update(input);
      } catch (IllegalStateException ex) {
         throw new XMLSignatureException("empty", ex);
      }
   }

   /**
    * Proxy method for {@link java.security.Signature#update(byte[], int, int)}
    * which is executed on the internal {@link java.security.Signature} object.
    *
    * @param buf
    * @param offset
    * @param len
    * @throws XMLSignatureException
    */
   protected void engineUpdate(byte buf[], int offset, int len)
           throws XMLSignatureException {

      try {
         this._macAlgorithm.update(buf, offset, len);
      } catch (IllegalStateException ex) {
         throw new XMLSignatureException("empty", ex);
      }
   }

   /**
    * Method engineGetJCEAlgorithmString
    * @inheritDoc
    *
    */
   protected String engineGetJCEAlgorithmString() {

      log.log(java.util.logging.Level.FINE, "engineGetJCEAlgorithmString()");

      return this._macAlgorithm.getAlgorithm();
   }

   /**
    * Method engineGetJCEAlgorithmString
    *
    * @inheritDoc
    */
   protected String engineGetJCEProviderName() {
      return this._macAlgorithm.getProvider().getName();
   }

   /**
    * Method engineSetHMACOutputLength
    *
    * @param HMACOutputLength
    */
   protected void engineSetHMACOutputLength(int HMACOutputLength) {
      this._HMACOutputLength = HMACOutputLength;
   }

   /**
    * Method engineGetContextFromElement
    *
    * @param element
    */
   protected void engineGetContextFromElement(Element element) {

      super.engineGetContextFromElement(element);

      if (element == null) {
         throw new IllegalArgumentException("element null");
      }

             Text hmaclength =XMLUtils.selectDsNodeText(element.getFirstChild(),
                    Constants._TAG_HMACOUTPUTLENGTH,0);

            if (hmaclength != null) {
               this._HMACOutputLength = Integer.parseInt(hmaclength.getData());
            }

   }

   /**
    * Method engineAddContextToElement
    *
    * @param element
    */
   public void engineAddContextToElement(Element element)
           {

      if (element == null) {
         throw new IllegalArgumentException("null element");
      }

      if (this._HMACOutputLength != 0) {
         Document doc = element.getOwnerDocument();
         Element HMElem = XMLUtils.createElementInSignatureSpace(doc,
                             Constants._TAG_HMACOUTPUTLENGTH);
         Text HMText =
            doc.createTextNode(new Integer(this._HMACOutputLength).toString());

         HMElem.appendChild(HMText);
         XMLUtils.addReturnToElement(element);
         element.appendChild(HMElem);
         XMLUtils.addReturnToElement(element);
      }
   }

   /**
    * Class IntegrityHmacSHA1
    *
    * @author $Author: mullan $
    * @version $Revision: 1.5 $
    */
   public static class IntegrityHmacSHA1 extends IntegrityHmac {

      /**
       * Constructor IntegrityHmacSHA1
       *
       * @throws XMLSignatureException
       */
      public IntegrityHmacSHA1() throws XMLSignatureException {
         super();
      }

      /**
       * Method engineGetURI
       * @inheritDoc
       *
       */
      public String engineGetURI() {
         return XMLSignature.ALGO_ID_MAC_HMAC_SHA1;
      }
   }

   /**
    * Class IntegrityHmacSHA256
    *
    * @author $Author: mullan $
    * @version $Revision: 1.5 $
    */
   public static class IntegrityHmacSHA256 extends IntegrityHmac {

      /**
       * Constructor IntegrityHmacSHA256
       *
       * @throws XMLSignatureException
       */
      public IntegrityHmacSHA256() throws XMLSignatureException {
         super();
      }

      /**
       * Method engineGetURI
       *
       * @inheritDoc
       */
      public String engineGetURI() {
         return XMLSignature.ALGO_ID_MAC_HMAC_SHA256;
      }
   }

   /**
    * Class IntegrityHmacSHA384
    *
    * @author $Author: mullan $
    * @version $Revision: 1.5 $
    */
   public static class IntegrityHmacSHA384 extends IntegrityHmac {

      /**
       * Constructor IntegrityHmacSHA384
       *
       * @throws XMLSignatureException
       */
      public IntegrityHmacSHA384() throws XMLSignatureException {
         super();
      }

      /**
       * Method engineGetURI
       * @inheritDoc
       *
       */
      public String engineGetURI() {
         return XMLSignature.ALGO_ID_MAC_HMAC_SHA384;
      }
   }

   /**
    * Class IntegrityHmacSHA512
    *
    * @author $Author: mullan $
    * @version $Revision: 1.5 $
    */
   public static class IntegrityHmacSHA512 extends IntegrityHmac {

      /**
       * Constructor IntegrityHmacSHA512
       *
       * @throws XMLSignatureException
       */
      public IntegrityHmacSHA512() throws XMLSignatureException {
         super();
      }

      /**
       * Method engineGetURI
       * @inheritDoc
       *
       */
      public String engineGetURI() {
         return XMLSignature.ALGO_ID_MAC_HMAC_SHA512;
      }
   }

   /**
    * Class IntegrityHmacRIPEMD160
    *
    * @author $Author: mullan $
    * @version $Revision: 1.5 $
    */
   public static class IntegrityHmacRIPEMD160 extends IntegrityHmac {

      /**
       * Constructor IntegrityHmacRIPEMD160
       *
       * @throws XMLSignatureException
       */
      public IntegrityHmacRIPEMD160() throws XMLSignatureException {
         super();
      }

      /**
       * Method engineGetURI
       *
       * @inheritDoc
       */
      public String engineGetURI() {
         return XMLSignature.ALGO_ID_MAC_HMAC_RIPEMD160;
      }
   }

   /**
    * Class IntegrityHmacMD5
    *
    * @author $Author: mullan $
    * @version $Revision: 1.5 $
    */
   public static class IntegrityHmacMD5 extends IntegrityHmac {

      /**
       * Constructor IntegrityHmacMD5
       *
       * @throws XMLSignatureException
       */
      public IntegrityHmacMD5() throws XMLSignatureException {
         super();
      }

      /**
       * Method engineGetURI
       *
       * @inheritDoc
       */
      public String engineGetURI() {
         return XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5;
      }
   }
}