mirror of https://github.com/OpenIdentityPlatform/OpenDJ.git

kenneth_suter
15.34.2007 80c58327faaa4873369f6bb949e62792c2f708e0
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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at
 * trunk/opends/resource/legal-notices/OpenDS.LICENSE
 * or https://OpenDS.dev.java.net/OpenDS.LICENSE.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at
 * trunk/opends/resource/legal-notices/OpenDS.LICENSE.  If applicable,
 * add the following below this CDDL HEADER, with the fields enclosed
 * by brackets "[]" replaced with your own identifying information:
 *      Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 *
 *
 *      Portions Copyright 2006-2007 Sun Microsystems, Inc.
 */
package org.opends.server.protocols.asn1;
import org.opends.messages.Message;
 
 
 
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
 
import org.opends.server.api.ProtocolElement;
import org.opends.server.types.ByteString;
 
import static org.opends.messages.ProtocolMessages.*;
import static org.opends.server.protocols.asn1.ASN1Constants.*;
import static org.opends.server.util.ServerConstants.*;
import static org.opends.server.util.StaticUtils.*;
 
 
 
/**
 * This class defines the data structures and methods to use when interacting
 * with generic ASN.1 elements.  Subclasses may provide more specific
 * functionality for individual element types.
 */
public class ASN1Element
       implements ProtocolElement, Serializable
{
 
 
 
  /**
   * The serial version identifier required to satisfy the compiler because this
   * class implements the <CODE>java.io.Serializable</CODE> interface.  This
   * value was generated using the <CODE>serialver</CODE> command-line utility
   * included with the Java SDK.
   */
  private static final long serialVersionUID = -6085322427222358963L;
 
 
 
  // The BER type for this element.
  private byte type;
 
  // The encoded value for this element.
  private byte[] value;
 
 
 
  /**
   * Creates a new ASN.1 element with the specified type and no value.
   *
   * @param  type  The BER type for this ASN.1 element.
   */
  public ASN1Element(byte type)
  {
    this.type  = type;
    this.value = NO_VALUE;
  }
 
 
 
  /**
   * Creates a new ASN.1 element with the specified type and value.
   *
   * @param  type   The BER type for this ASN.1 element.
   * @param  value  The encoded value for this ASN.1 element.
   */
  public ASN1Element(byte type, byte[] value)
  {
    this.type  = type;
 
    if (value == null)
    {
      this.value = NO_VALUE;
    }
    else
    {
      this.value = value;
    }
  }
 
 
 
  /**
   * Retrieves the BER type for this ASN.1 element.
   *
   * @return  The BER type for this ASN.1 element.
   */
  public byte getType()
  {
    return type;
  }
 
 
 
  /**
   * Specifies the BER type for this ASN.1 element.
   *
   * @param  type  The BER type for this ASN.1 element.
   */
  public void setType(byte type)
  {
    this.type = type;
  }
 
 
 
  /**
   * Indicates whether this ASN.1 element is in the universal class.
   *
   * @return  <CODE>true</CODE> if this ASN.1 element is in the universal class,
   *          or <CODE>false</CODE> if not.
   */
  public boolean isUniversal()
  {
    return ((type & TYPE_MASK_ALL_BUT_CLASS) == TYPE_MASK_UNIVERSAL);
  }
 
 
 
  /**
   * Indicates whether this ASN.1 element is in the application-specific class.
   *
   * @return  <CODE>true</CODE> if this ASN.1 element is in the
   *          application-specific class, or <CODE>false</CODE> if not.
   */
  public boolean isApplicationSpecific()
  {
    return ((type & TYPE_MASK_ALL_BUT_CLASS) == TYPE_MASK_APPLICATION);
  }
 
 
 
  /**
   * Indicates whether this ASN.1 element is in the context-specific class.
   *
   * @return  <CODE>true</CODE> if this ASN.1 element is in the context-specific
   *          class, or <CODE>false</CODE> if not.
   */
  public boolean isContextSpecific()
  {
    return ((type & TYPE_MASK_ALL_BUT_CLASS) == TYPE_MASK_CONTEXT);
  }
 
 
 
  /**
   * Indicates whether this ASN.1 element is in the private class.
   *
   * @return  <CODE>true</CODE> if this ASN.1 element is in the private class,
   *          or <CODE>false</CODE> if not.
   */
  public boolean isPrivate()
  {
    return ((type & TYPE_MASK_ALL_BUT_CLASS) == TYPE_MASK_PRIVATE);
  }
 
 
 
  /**
   * Indicates whether this ASN.1 element has a primitive value.
   *
   * @return  <CODE>true</CODE> if this ASN.1 element has a primitive value, or
   *          <CODE>false</CODE> if it is constructed.
   */
  public boolean isPrimitive()
  {
    return ((type & TYPE_MASK_ALL_BUT_PC) == TYPE_MASK_PRIMITIVE);
  }
 
 
 
  /**
   * Indicates whether this ASN.1 element has a constructed value.
   *
   * @return  <CODE>true</CODE> if this ASN.1 element has a constructed value,
   *          or <CODE>false</CODE> if it is primitive.
   */
  public boolean isConstructed()
  {
    return ((type & TYPE_MASK_ALL_BUT_PC) == TYPE_MASK_CONSTRUCTED);
  }
 
 
 
  /**
   * Retrieves the encoded value for this ASN.1 element.
   *
   * @return  The encoded value for this ASN.1 element.
   */
  public byte[] value()
  {
    return value;
  }
 
 
 
  /**
   * Specifies the encoded value for this ASN.1 element.
   *
   * @param  value  The encoded value for this ASN.1 element.
   *
   * @throws  ASN1Exception  If the provided value is not appropriate for this
   *                         type of ASN.1 element.
   */
  public void setValue(byte[] value)
         throws ASN1Exception
  {
    if (value == null)
    {
      this.value = NO_VALUE;
    }
    else
    {
      this.value = value;
    }
  }
 
 
 
  /**
   * Specifies the value to use for this ASN.1 element, but without performing
   * any validity checks.  This should only be used by subclasses and they must
   * ensure that it is non-null and conforms to the appropriate requirements of
   * the underlying type.
   *
   * @param  value  The encoded value for this ASN.1 element.
   */
  protected final void setValueInternal(byte[] value)
  {
    this.value = value;
  }
 
 
 
  /**
   * Encodes the provided value for use as the length of an ASN.1 element.
   *
   * @param  length  The length to encode for use in an ASN.1 element.
   *
   * @return  The byte array containing the encoded length.
   */
  public static byte[] encodeLength(int length)
  {
    if (length < 128)
    {
      return new byte[] { (byte) length };
    }
 
    if ((length & 0x000000FF) == length)
    {
      return new byte[]
      {
        (byte) 0x81,
        (byte) (length & 0xFF)
      };
    }
    else if ((length & 0x0000FFFF) == length)
    {
      return new byte[]
      {
        (byte) 0x82,
        (byte) ((length >> 8) & 0xFF),
        (byte) (length & 0xFF)
      };
    }
    else if ((length & 0x00FFFFFF) == length)
    {
      return new byte[]
      {
        (byte) 0x83,
        (byte) ((length >> 16) & 0xFF),
        (byte) ((length >>  8) & 0xFF),
        (byte) (length & 0xFF)
      };
    }
    else
    {
      return new byte[]
      {
        (byte) 0x84,
        (byte) ((length >> 24) & 0xFF),
        (byte) ((length >> 16) & 0xFF),
        (byte) ((length >>  8) & 0xFF),
        (byte) (length & 0xFF)
      };
    }
  }
 
 
 
  /**
   * Encodes this ASN.1 element to a byte array.
   *
   * @return  The byte array containing the encoded ASN.1 element.
   */
  public byte[] encode()
  {
    if (value.length == 0)
    {
      return new byte[] { type, 0x00 };
    }
    else if (value.length < 128)
    {
      byte[] encodedElement = new byte[value.length + 2];
 
      encodedElement[0] = type;
      encodedElement[1] = (byte) value.length;
      System.arraycopy(value, 0, encodedElement, 2, value.length);
 
      return encodedElement;
    }
    else
    {
      byte[] encodedLength  = encodeLength(value.length);
      byte[] encodedElement = new byte[1 + value.length + encodedLength.length];
 
      encodedElement[0] = type;
      System.arraycopy(encodedLength, 0, encodedElement, 1,
                       encodedLength.length);
      System.arraycopy(value, 0, encodedElement, 1+encodedLength.length,
                       value.length);
 
      return encodedElement;
    }
  }
 
 
 
  /**
   * Retrieves a byte array containing the encoded representation of the
   * provided boolean value.
   *
   * @param  booleanValue  The boolean value to encode.
   *
   * @return  A byte array containing the encoded representation of the provided
   *          boolean value.
   */
  public static byte[] encodeValue(boolean booleanValue)
  {
    return (booleanValue ? BOOLEAN_VALUE_TRUE : BOOLEAN_VALUE_FALSE);
  }
 
 
 
  /**
   * Retrieves a byte array containing the encoded representation of the
   * provided integer value.
   *
   * @param  intValue  The integer value to encode.
   *
   * @return  A byte array containing the encoded representation of the provided
   *          integer value.
   */
  public static byte[] encodeValue(int intValue)
  {
    if ((intValue & 0x0000007F) == intValue)
    {
      return new byte[]
      {
        (byte) (intValue & 0xFF)
      };
    }
    else if ((intValue & 0x00007FFF) == intValue)
    {
      return new byte[]
      {
        (byte) ((intValue >> 8) & 0xFF),
        (byte) (intValue & 0xFF)
      };
    }
    else if ((intValue & 0x007FFFFF) == intValue)
    {
      return new byte[]
      {
        (byte) ((intValue >> 16) & 0xFF),
        (byte) ((intValue >>  8) & 0xFF),
        (byte) (intValue & 0xFF)
      };
    }
    else
    {
      return new byte[]
      {
        (byte) ((intValue >> 24) & 0xFF),
        (byte) ((intValue >> 16) & 0xFF),
        (byte) ((intValue >>  8) & 0xFF),
        (byte) (intValue & 0xFF)
      };
    }
  }
 
 
 
  /**
   * Retrieves a byte array containing the encoded representation of the
   * provided long value.
   *
   * @param  longValue  The long value to encode.
   *
   * @return  A byte array containing the encoded representation of the provided
   *          long value.
   */
  public static byte[] encodeLongValue(long longValue)
  {
    if ((longValue & 0x000000000000007FL) == longValue)
    {
      return new byte[]
      {
        (byte) (longValue & 0xFF)
      };
    }
    else if ((longValue & 0x0000000000007FFFL) == longValue)
    {
      return new byte[]
      {
        (byte) ((longValue >> 8) & 0xFF),
        (byte) (longValue & 0xFF)
      };
    }
    else if ((longValue & 0x00000000007FFFFFL) == longValue)
    {
      return new byte[]
      {
        (byte) ((longValue >> 16) & 0xFF),
        (byte) ((longValue >>  8) & 0xFF),
        (byte) (longValue & 0xFF)
      };
    }
    else if ((longValue & 0x000000007FFFFFFFL) == longValue)
    {
      return new byte[]
      {
        (byte) ((longValue >> 24) & 0xFF),
        (byte) ((longValue >> 16) & 0xFF),
        (byte) ((longValue >>  8) & 0xFF),
        (byte) (longValue & 0xFF)
      };
    }
    else if ((longValue & 0x0000007FFFFFFFFFL) == longValue)
    {
      return new byte[]
      {
        (byte) ((longValue >> 32) & 0xFF),
        (byte) ((longValue >> 24) & 0xFF),
        (byte) ((longValue >> 16) & 0xFF),
        (byte) ((longValue >>  8) & 0xFF),
        (byte) (longValue & 0xFF)
      };
    }
    else if ((longValue & 0x00007FFFFFFFFFFFL) == longValue)
    {
      return new byte[]
      {
        (byte) ((longValue >> 40) & 0xFF),
        (byte) ((longValue >> 32) & 0xFF),
        (byte) ((longValue >> 24) & 0xFF),
        (byte) ((longValue >> 16) & 0xFF),
        (byte) ((longValue >>  8) & 0xFF),
        (byte) (longValue & 0xFF)
      };
    }
    else if ((longValue & 0x007FFFFFFFFFFFFFL) == longValue)
    {
      return new byte[]
      {
        (byte) ((longValue >> 48) & 0xFF),
        (byte) ((longValue >> 40) & 0xFF),
        (byte) ((longValue >> 32) & 0xFF),
        (byte) ((longValue >> 24) & 0xFF),
        (byte) ((longValue >> 16) & 0xFF),
        (byte) ((longValue >>  8) & 0xFF),
        (byte) (longValue & 0xFF)
      };
    }
    else
    {
      return new byte[]
      {
        (byte) ((longValue >> 56) & 0xFF),
        (byte) ((longValue >> 48) & 0xFF),
        (byte) ((longValue >> 40) & 0xFF),
        (byte) ((longValue >> 32) & 0xFF),
        (byte) ((longValue >> 24) & 0xFF),
        (byte) ((longValue >> 16) & 0xFF),
        (byte) ((longValue >>  8) & 0xFF),
        (byte) (longValue & 0xFF)
      };
    }
  }
 
 
 
  /**
   * Retrieves a byte array containing the encoded representation of the
   * provided set of ASN.1 elements.
   *
   * @param  elements  The set of ASN.1 elements to encode into the value.
   *
   * @return  A byte array containing the encoded representation of the
   *          provided set of ASN.1 elements.
   */
  public static byte[] encodeValue(ArrayList<ASN1Element> elements)
  {
    if (elements == null)
    {
      return NO_VALUE;
    }
 
 
    int totalLength = 0;
    byte[][] encodedElements = new byte[elements.size()][];
    for (int i=0; i < encodedElements.length; i++)
    {
      encodedElements[i] = elements.get(i).encode();
      totalLength += encodedElements[i].length;
    }
 
    byte[] encodedValue = new byte[totalLength];
    int startPos = 0;
    for (byte[] b : encodedElements)
    {
      System.arraycopy(b, 0, encodedValue, startPos, b.length);
      startPos += b.length;
    }
 
    return encodedValue;
  }
 
 
 
  /**
   * Decodes the contents of the provided byte array as an ASN.1 element.
   *
   * @param  encodedElement  The byte array containing the ASN.1 element to
   *                         decode.
   *
   * @return  The decoded ASN.1 element.
   *
   * @throws  ASN1Exception  If a problem occurs while attempting to decode the
   *                         byte array as an ASN.1 element.
   */
  public static ASN1Element decode(byte[] encodedElement)
         throws ASN1Exception
  {
    // First make sure that the array is not null and long enough to contain
    // a valid ASN.1 element.
    if (encodedElement == null)
    {
      Message message = ERR_ASN1_NULL_ELEMENT.get();
      throw new ASN1Exception(message);
    }
    else if (encodedElement.length < 2)
    {
      Message message = ERR_ASN1_SHORT_ELEMENT.get(encodedElement.length);
      throw new ASN1Exception(message);
    }
 
 
    // Next, decode the length.  This allows multi-byte lengths with up to four
    // bytes used to indicate how many bytes are in the length.
    byte type = encodedElement[0];
    int length = (encodedElement[1] & 0x7F);
    int valueStartPos = 2;
    if (length != encodedElement[1])
    {
      int numLengthBytes = length;
      if (numLengthBytes > 4)
      {
        Message message = ERR_ASN1_INVALID_NUM_LENGTH_BYTES.get(numLengthBytes);
        throw new ASN1Exception(message);
      }
      else if (encodedElement.length < (2 + numLengthBytes))
      {
        Message message = ERR_ASN1_TRUNCATED_LENGTH.get(numLengthBytes);
        throw new ASN1Exception(message);
      }
 
      length = 0x00;
      valueStartPos = 2 + numLengthBytes;
      for (int i=0; i < numLengthBytes; i++)
      {
        length = (length << 8) | (encodedElement[i+2] & 0xFF);
      }
    }
 
 
    // Make sure that the number of bytes left is equal to the number of bytes
    // in the value.
    if ((encodedElement.length - valueStartPos) != length)
    {
      Message message = ERR_ASN1_LENGTH_MISMATCH.get(
          length, (encodedElement.length - valueStartPos));
      throw new ASN1Exception(message);
    }
 
 
    // Copy the value and construct the element to return.
    byte[] value = new byte[length];
    System.arraycopy(encodedElement, valueStartPos, value, 0, length);
    return new ASN1Element(type, value);
  }
 
 
 
  /**
   * Decodes the specified portion of the provided byte array as an ASN.1
   * element.
   *
   * @param  encodedElement  The byte array containing the ASN.1 element to
   *                         decode.
   * @param  startPos        The position in the provided array at which to
   *                         start decoding.
   * @param  length          The number of bytes in the set of data to decode as
   *                         an ASN.1 element.
   *
   * @return  The decoded ASN.1 element.
   *
   * @throws  ASN1Exception  If a problem occurs while attempting to decode the
   *                         byte array as an ASN.1 element.
   */
  public static ASN1Element decode(byte[] encodedElement, int startPos,
                                   int length)
         throws ASN1Exception
  {
    // First make sure that the array is not null and long enough to contain
    // a valid ASN.1 element.
    if (encodedElement == null)
    {
      Message message = ERR_ASN1_NULL_ELEMENT.get();
      throw new ASN1Exception(message);
    }
    else if ((startPos < 0) || (startPos+length > encodedElement.length) ||
             (length < 2))
    {
      Message message = ERR_ASN1_SHORT_ELEMENT.get(encodedElement.length);
      throw new ASN1Exception(message);
    }
 
 
    // Next, decode the length.  This allows multi-byte lengths with up to four
    // bytes used to indicate how many bytes are in the length.
    byte type = encodedElement[startPos];
    int elementLength = (encodedElement[startPos+1] & 0x7F);
    int valueStartPos = startPos + 2;
    if (elementLength != encodedElement[startPos+1])
    {
      int numLengthBytes = elementLength;
      if (numLengthBytes > 4)
      {
        Message message = ERR_ASN1_INVALID_NUM_LENGTH_BYTES.get(numLengthBytes);
        throw new ASN1Exception(message);
      }
      else if (startPos+length < (2 + numLengthBytes))
      {
        Message message = ERR_ASN1_TRUNCATED_LENGTH.get(numLengthBytes);
        throw new ASN1Exception(message);
      }
 
      elementLength = 0x00;
      valueStartPos = startPos + 2 + numLengthBytes;
      for (int i=0; i < numLengthBytes; i++)
      {
        elementLength = (elementLength << 8) | (encodedElement[i+2] & 0xFF);
      }
    }
 
 
    // Make sure that the number of bytes left is equal to the number of bytes
    // in the value.
    if ((startPos+length - valueStartPos) != elementLength)
    {
      Message message = ERR_ASN1_LENGTH_MISMATCH.get(
          elementLength, (startPos+length - valueStartPos));
      throw new ASN1Exception(message);
    }
 
 
    // Copy the value and construct the element to return.
    byte[] value = new byte[elementLength];
    System.arraycopy(encodedElement, valueStartPos, value, 0, elementLength);
    return new ASN1Element(type, value);
  }
 
 
 
  /**
   * Decodes this ASN.1 element as an ASN.1 Boolean element.
   *
   * @return  The ASN.1 Boolean element decoded from this element.
   *
   * @throws  ASN1Exception  If a problem occurs while attempting to decode this
   *                         element as an ASN.1 Boolean element.
   */
  public ASN1Boolean decodeAsBoolean()
         throws ASN1Exception
  {
    return ASN1Boolean.decodeAsBoolean(this);
  }
 
 
 
  /**
   * Decodes this ASN.1 element as an ASN.1 enumerated element.
   *
   * @return  The ASN.1 enumerated element decoded from this element.
   *
   * @throws  ASN1Exception  If a problem occurs while attempting to decode this
   *                         element as an ASN.1 enumerated element.
   */
  public ASN1Enumerated decodeAsEnumerated()
         throws ASN1Exception
  {
    return ASN1Enumerated.decodeAsEnumerated(this);
  }
 
 
 
  /**
   * Decodes this ASN.1 element as an ASN.1 integer element.
   *
   * @return  The ASN.1 integer element decoded from this element.
   *
   * @throws  ASN1Exception  If a problem occurs while attempting to decode this
   *                         element as an ASN.1 integer element.
   */
  public ASN1Integer decodeAsInteger()
         throws ASN1Exception
  {
    return ASN1Integer.decodeAsInteger(this);
  }
 
 
 
  /**
   * Decodes this ASN.1 element as an ASN.1 long element.
   *
   * @return  The ASN.1 long element decoded from this element.
   *
   * @throws  ASN1Exception  If a problem occurs while attempting to decode this
   *                         element as an ASN.1 long element.
   */
  public ASN1Long decodeAsLong()
         throws ASN1Exception
  {
    return ASN1Long.decodeAsLong(this);
  }
 
 
 
  /**
   * Decodes this ASN.1 element as an ASN.1 null element.
   *
   * @return  The ASN.1 null element decoded from this element.
   *
   * @throws  ASN1Exception  If a problem occurs while attempting to decode this
   *                         element as an ASN.1 null element.
   */
  public ASN1Null decodeAsNull()
         throws ASN1Exception
  {
    return ASN1Null.decodeAsNull(this);
  }
 
 
 
  /**
   * Decodes this ASN.1 element as an ASN.1 octet string element.
   *
   * @return  The ASN.1 octet string element decoded from this element.
   *
   * @throws  ASN1Exception  If a problem occurs while attempting to decode this
   *                         element as an ASN.1 octet string element.
   */
  public ASN1OctetString decodeAsOctetString()
         throws ASN1Exception
  {
    return ASN1OctetString.decodeAsOctetString(this);
  }
 
 
 
  /**
   * Decodes this ASN.1 element as an ASN.1 sequence element.
   *
   * @return  The ASN.1 sequence element decoded from this element.
   *
   * @throws  ASN1Exception  If a problem occurs while attempting to decode this
   *                         element as an ASN.1 sequence element.
   */
  public ASN1Sequence decodeAsSequence()
         throws ASN1Exception
  {
    return ASN1Sequence.decodeAsSequence(this);
  }
 
 
 
  /**
   * Decodes this ASN.1 element as an ASN.1 set element.
   *
   * @return  The ASN.1 set element decoded from this element.
   *
   * @throws  ASN1Exception  If a problem occurs while attempting to decode this
   *                         element as an ASN.1 set element.
   */
  public ASN1Set decodeAsSet()
         throws ASN1Exception
  {
    return ASN1Set.decodeAsSet(this);
  }
 
 
 
  /**
   * Decodes the provided byte array as a collection of ASN.1 elements as would
   * be found in the value of a sequence or set.
   *
   * @param  encodedElements  The byte array containing the data to decode.
   *
   * @return  The set of decoded ASN.1 elements.
   *
   * @throws  ASN1Exception  If a problem occurs while attempting to decode the
   *                         set of ASN.1 elements from the provided byte array.
   */
  public static ArrayList<ASN1Element> decodeElements(byte[] encodedElements)
         throws ASN1Exception
  {
    // Make sure that the element array is not null.
    if (encodedElements == null)
    {
      Message message = ERR_ASN1_ELEMENT_SET_NULL.get();
      throw new ASN1Exception(message);
    }
 
 
    // Iterate through the array and keep reading elements until the end is
    // reached.
    ArrayList<ASN1Element> elements = new ArrayList<ASN1Element>();
    int startPos = 0;
    while (startPos < encodedElements.length)
    {
      byte type = encodedElements[startPos++];
      if (startPos >= encodedElements.length)
      {
        Message message = ERR_ASN1_ELEMENT_SET_NO_LENGTH.get();
        throw new ASN1Exception(message);
      }
 
 
      byte firstLengthByte = encodedElements[startPos++];
      int length = (byte) (firstLengthByte & 0x7F);
      if (length != firstLengthByte)
      {
        int numLengthBytes = length;
        if (numLengthBytes > 4)
        {
          Message message =
              ERR_ASN1_ELEMENT_SET_INVALID_NUM_LENGTH_BYTES.get(numLengthBytes);
          throw new ASN1Exception(message);
        }
 
        if (numLengthBytes > encodedElements.length - startPos)
        {
          Message message =
              ERR_ASN1_ELEMENT_SET_TRUNCATED_LENGTH.get(numLengthBytes);
          throw new ASN1Exception(message);
        }
 
        length = 0x00;
        for (int i=0; i < numLengthBytes; i++)
        {
          length = (length << 8) | (encodedElements[startPos++] & 0xFF);
        }
      }
 
 
      // Make sure that there are at least enough bytes to hold the value.
      if (length > encodedElements.length - startPos)
      {
        Message message = ERR_ASN1_ELEMENT_SET_TRUNCATED_VALUE.get(
            length, (encodedElements.length-startPos));
        throw new ASN1Exception(message);
      }
 
 
      // Create the element and add it to the list.
      byte[] value = new byte[length];
      System.arraycopy(encodedElements, startPos, value, 0, length);
      elements.add(new ASN1Element(type, value));
      startPos += length;
    }
 
 
    return elements;
  }
 
 
 
  /**
   * Retrieves the name of the protocol associated with this protocol element.
   *
   * @return  The name of the protocol associated with this protocol element.
   */
  public String getProtocolElementName()
  {
    return "ASN.1";
  }
 
 
 
  /**
   * Indicates whether the provided object is equal to this ASN.1 element.
   *
   * @param  o  The object for which to make the determination.
   *
   * @return  <CODE>true</CODE> if the provided object is an ASN.1 element that
   *          is equal to this element, or <CODE>false</CODE> if not.  The
   *          object will be considered equal if it is an ASN.1 element (or a
   *          subclass) with the same type and encoded value.
   */
  public boolean equals(Object o)
  {
    if (this == o)
    {
      return true;
    }
 
    if ((o == null) || (! (o instanceof ASN1Element)))
    {
      return false;
    }
 
    ASN1Element e = (ASN1Element) o;
    return ((type == e.type) && Arrays.equals(value, e.value));
  }
 
 
 
  /**
   * Indicates whether the provided ASN.1 element has a value that is equal to
   * the value of this ASN.1 element.
   *
   * @param  element  The ASN.1 element whose value should be compared against
   *                  the value of this element.
   *
   * @return  <CODE>true</CODE> if the values of the elements are equal, or
   *          <CODE>false</CODE> if not.
   */
  public boolean equalsIgnoreType(ASN1Element element)
  {
    return Arrays.equals(value, element.value);
  }
 
 
 
  /**
   * Indicates whether the provided byte string has a value that is equal to
   * the value of this ASN.1 element.
   *
   * @param  byteString  The byte string whose value should be compared against
   *                     the value of this element.
   *
   * @return  <CODE>true</CODE> if the values are equal, or <CODE>false</CODE>
   *          if not.
   */
  public boolean equalsIgnoreType(ByteString byteString)
  {
    return Arrays.equals(value, byteString.value());
  }
 
 
 
  /**
   * Indicates whether the provided ASN.1 element is equal to this element.
   *
   * @param  e  The ASN.1 element for which to make the determination.
   *
   * @return  <CODE>true</CODE> ASN.1 element is equal to this element,
   *          or <CODE>false</CODE> if not.  The elements will be considered
   *          equal if they have the same type and encoded value.
   */
  public boolean equalsElement(ASN1Element e)
  {
    if (this == e)
    {
      return true;
    }
 
    if (e == null)
    {
      return false;
    }
 
    return ((type == e.type) && Arrays.equals(value, e.value));
  }
 
 
 
  /**
   * Retrieves the hash code for this ASN.1 element.  It will be constructed
   * from the sum of the type and up to the first twenty bytes of the value.
   *
   * @return  The hash code for this ASN.1 element.
   */
  public int hashCode()
  {
    int hashCode = type;
    int length = Math.min(20, value.length);
    for (int i=0; i < length; i++)
    {
      hashCode += value[i];
    }
 
    return hashCode;
  }
 
 
 
  /**
   * Retrieves a string representation of this ASN.1 element.
   *
   * @return  A string representation of this ASN.1 element.
   */
  public String toString()
  {
    StringBuilder buffer = new StringBuilder();
    toString(buffer);
    return buffer.toString();
  }
 
 
 
  /**
   * Appends a string representation of this ASN.1 element to the provided
   * buffer.
   *
   * @param  buffer  The buffer to which the information should be appended.
   */
  public void toString(StringBuilder buffer)
  {
    buffer.append("ASN1Element(type=");
    buffer.append(byteToHex(type));
    buffer.append(", length=");
    buffer.append(value.length);
    buffer.append(")");
  }
 
 
 
  /**
   * Appends a string representation of this protocol element to the provided
   * buffer.
   *
   * @param  buffer  The buffer into which the string representation should be
   *                 written.
   * @param  indent  The number of spaces that should be used to indent the
   *                 resulting string representation.
   */
  public void toString(StringBuilder buffer, int indent)
  {
    StringBuilder indentBuf = new StringBuilder(indent);
    for (int i=0 ; i < indent; i++)
    {
      indentBuf.append(' ');
    }
 
    buffer.append(indentBuf);
    buffer.append("ASN.1 Element");
    buffer.append(EOL);
 
    buffer.append(indentBuf);
    buffer.append("  BER Type:  ");
    buffer.append(byteToHex(type));
    buffer.append(EOL);
 
    buffer.append(indentBuf);
    buffer.append("  Value (");
    buffer.append(value.length);
    buffer.append(" bytes)");
    buffer.append(EOL);
 
    byteArrayToHexPlusAscii(buffer, value, indent+2);
  }
}