summaryrefslogtreecommitdiffstats
path: root/base/server/cms/src/com/netscape/cms/servlet/common/CMCOutputTemplate.java
blob: 067dce76b25622ac91d020031ae6180076f8f7e3 (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
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
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; version 2 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
// (C) 2007 Red Hat, Inc.
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.common;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.cert.CertificateExpiredException;
import java.util.Date;
import java.util.Hashtable;

import javax.servlet.http.HttpServletResponse;

import org.mozilla.jss.CryptoManager;
import org.mozilla.jss.asn1.ANY;
import org.mozilla.jss.asn1.ASN1Util;
import org.mozilla.jss.asn1.ENUMERATED;
import org.mozilla.jss.asn1.GeneralizedTime;
import org.mozilla.jss.asn1.INTEGER;
import org.mozilla.jss.asn1.InvalidBERException;
import org.mozilla.jss.asn1.OBJECT_IDENTIFIER;
import org.mozilla.jss.asn1.OCTET_STRING;
import org.mozilla.jss.asn1.SEQUENCE;
import org.mozilla.jss.asn1.SET;
import org.mozilla.jss.asn1.UTF8String;
import org.mozilla.jss.crypto.DigestAlgorithm;
import org.mozilla.jss.crypto.EncryptionAlgorithm;
import org.mozilla.jss.crypto.SignatureAlgorithm;
import org.mozilla.jss.pkcs11.PK11PubKey;
import org.mozilla.jss.pkix.cert.Certificate;
import org.mozilla.jss.pkix.cmc.CMCCertId;
import org.mozilla.jss.pkix.cmc.CMCStatusInfo;
import org.mozilla.jss.pkix.cmc.EncryptedPOP;
import org.mozilla.jss.pkix.cmc.GetCert;
import org.mozilla.jss.pkix.cmc.OtherInfo;
import org.mozilla.jss.pkix.cmc.OtherMsg;
import org.mozilla.jss.pkix.cmc.PendInfo;
import org.mozilla.jss.pkix.cmc.ResponseBody;
import org.mozilla.jss.pkix.cmc.RevokeRequest;
import org.mozilla.jss.pkix.cmc.TaggedAttribute;
import org.mozilla.jss.pkix.cmc.TaggedRequest;
import org.mozilla.jss.pkix.cms.ContentInfo;
import org.mozilla.jss.pkix.cms.EncapsulatedContentInfo;
import org.mozilla.jss.pkix.cms.EnvelopedData;
import org.mozilla.jss.pkix.cms.IssuerAndSerialNumber;
import org.mozilla.jss.pkix.cms.SignedData;
import org.mozilla.jss.pkix.cms.SignerIdentifier;
import org.mozilla.jss.pkix.cms.SignerInfo;
import org.mozilla.jss.pkix.primitive.AlgorithmIdentifier;
import org.mozilla.jss.pkix.primitive.Name;

import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.authentication.ISharedToken;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.EPropertyNotFound;
import com.netscape.certsrv.base.SessionContext;
import com.netscape.certsrv.ca.ICertificateAuthority;
import com.netscape.certsrv.dbs.certdb.ICertRecord;
import com.netscape.certsrv.dbs.certdb.ICertificateRepository;
import com.netscape.certsrv.logging.AuditEvent;
import com.netscape.certsrv.logging.AuditFormat;
import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.logging.event.CertStatusChangeRequestProcessedEvent;
import com.netscape.certsrv.profile.IEnrollProfile;
import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.IRequestQueue;
import com.netscape.certsrv.request.RequestId;
import com.netscape.certsrv.request.RequestStatus;
import com.netscape.cmsutil.crypto.CryptoUtil;

import netscape.security.x509.CRLExtensions;
import netscape.security.x509.CRLReasonExtension;
import netscape.security.x509.CertificateChain;
import netscape.security.x509.InvalidityDateExtension;
import netscape.security.x509.RevocationReason;
import netscape.security.x509.RevokedCertImpl;
import netscape.security.x509.X500Name;
import netscape.security.x509.X509CertImpl;
import netscape.security.x509.X509Key;

/**
 * Utility CMCOutputTemplate
 *
 * @version $ $, $Date$
 */
public class CMCOutputTemplate {
    protected ILogger mSignedAuditLogger = CMS.getSignedAuditLogger();

    public CMCOutputTemplate() {
    }

    public void createFullResponseWithFailedStatus(HttpServletResponse resp,
            SEQUENCE bpids, int code, UTF8String s) {
        SEQUENCE controlSeq = new SEQUENCE();
        SEQUENCE cmsSeq = new SEQUENCE();
        SEQUENCE otherMsgSeq = new SEQUENCE();

        int bpid = 1;
        OtherInfo otherInfo = new OtherInfo(OtherInfo.FAIL,
                new INTEGER(code), null);
        CMCStatusInfo cmcStatusInfo = new CMCStatusInfo(
                new INTEGER(CMCStatusInfo.FAILED),
                bpids, s, otherInfo);
        TaggedAttribute tagattr = new TaggedAttribute(
                new INTEGER(bpid++),
                OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
        controlSeq.addElement(tagattr);

        try {
            ResponseBody respBody = new ResponseBody(controlSeq,
                    cmsSeq, otherMsgSeq);

            SET certs = new SET();
            ContentInfo contentInfo = getContentInfo(respBody, certs);
            if (contentInfo == null)
                return;
            ByteArrayOutputStream fos = new ByteArrayOutputStream();
            contentInfo.encode(fos);
            fos.close();
            byte[] contentBytes = fos.toByteArray();

            resp.setContentType("application/pkcs7-mime");
            resp.setContentLength(contentBytes.length);
            OutputStream os = resp.getOutputStream();
            os.write(contentBytes);
            os.flush();
        } catch (Exception e) {
            CMS.debug("CMCOutputTemplate createFullResponseWithFailedStatus Exception: " + e.toString());
            return;
        }
    }

    public void createFullResponse(HttpServletResponse resp, IRequest[] reqs,
            String cert_request_type, int[] error_codes) {
        String method = "CMCOutputTemplate: createFullResponse: ";
        CMS.debug(method +
                "begins with cert_request_type=" +
                cert_request_type);

        SEQUENCE controlSeq = new SEQUENCE();
        SEQUENCE cmsSeq = new SEQUENCE();
        SEQUENCE otherMsgSeq = new SEQUENCE();
        SessionContext context = SessionContext.getContext();

        // set status info control for simple enrollment request
        // in rfc 2797: body list value is 1
        int bpid = 1;
        SEQUENCE pending_bpids = null;
        SEQUENCE success_bpids = null;
        SEQUENCE failed_bpids = null;
        if (cert_request_type.equals("crmf") ||
                cert_request_type.equals("pkcs10")) {
            String reqId = reqs[0].getRequestId().toString();
            OtherInfo otherInfo = null;
            if (error_codes[0] == 2) {
                PendInfo pendInfo = new PendInfo(reqId, new Date());
                otherInfo = new OtherInfo(OtherInfo.PEND, null,
                        pendInfo);
            } else {
                otherInfo = new OtherInfo(OtherInfo.FAIL,
                        new INTEGER(OtherInfo.BAD_REQUEST), null);
            }

            SEQUENCE bpids = new SEQUENCE();
            bpids.addElement(new INTEGER(1));
            CMCStatusInfo cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.PENDING,
                    bpids, (String) null, otherInfo);
            TaggedAttribute tagattr = new TaggedAttribute(
                    new INTEGER(bpid++),
                    OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
            controlSeq.addElement(tagattr);
        } else if (cert_request_type.equals("cmc")) {
            CMS.debug(method + " processing cmc");
            pending_bpids = new SEQUENCE();
            success_bpids = new SEQUENCE();
            failed_bpids = new SEQUENCE();
            EncryptedPOP encPop = null;
            if (reqs != null) {
                for (int i = 0; i < reqs.length; i++) {
                    CMS.debug(method + " error_codes[" +i+"]="
                            + error_codes[i]);
                    if (error_codes[i] == 0) {
                        success_bpids.addElement(new INTEGER(
                                reqs[i].getExtDataInBigInteger("bodyPartId")));
                    } else if (error_codes[i] == 2) {
                        pending_bpids.addElement(new INTEGER(
                                reqs[i].getExtDataInBigInteger("bodyPartId")));
                        try {
                            encPop = constructEncryptedPop(reqs[i]);
                        } catch (Exception e) {
                            CMS.debug(method + e);
                            return;
                        }
                    } else {
                        failed_bpids.addElement(new INTEGER(
                                reqs[i].getExtDataInBigInteger("bodyPartId")));
                    }
                }
            } else {
                CMS.debug(method + " reqs null. could be revocation");
            }

            TaggedAttribute tagattr = null;
            CMCStatusInfo cmcStatusInfo = null;

            SEQUENCE decryptedPOPBpids = (SEQUENCE) context.get("decryptedPOP");
            if (decryptedPOPBpids != null && decryptedPOPBpids.size() > 0) {
                OtherInfo otherInfo = new OtherInfo(OtherInfo.FAIL,
                        new INTEGER(OtherInfo.POP_FAILED), null);
                cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.FAILED,
                        decryptedPOPBpids, (String) null, otherInfo);
                tagattr = new TaggedAttribute(
                        new INTEGER(bpid++),
                        OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
                controlSeq.addElement(tagattr);
            }

            SEQUENCE identificationBpids = (SEQUENCE) context.get("identification");
            if (identificationBpids != null && identificationBpids.size() > 0) {
                OtherInfo otherInfo = new OtherInfo(OtherInfo.FAIL,
                        new INTEGER(OtherInfo.BAD_IDENTITY), null);
                cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.FAILED,
                        identificationBpids, (String) null, otherInfo);
                tagattr = new TaggedAttribute(
                        new INTEGER(bpid++),
                        OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
                controlSeq.addElement(tagattr);
            }

            SEQUENCE identityV2Bpids = (SEQUENCE) context.get("identityProofV2");
            if (identityV2Bpids != null && identityV2Bpids.size() > 0) {
                OtherInfo otherInfo = new OtherInfo(OtherInfo.FAIL,
                        new INTEGER(OtherInfo.BAD_IDENTITY), null);
                cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.FAILED,
                        identityV2Bpids, (String) null, otherInfo);
                tagattr = new TaggedAttribute(
                        new INTEGER(bpid++),
                        OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
                controlSeq.addElement(tagattr);
            }


            SEQUENCE identityBpids = (SEQUENCE) context.get("identityProof");
            if (identityBpids != null && identityBpids.size() > 0) {
                OtherInfo otherInfo = new OtherInfo(OtherInfo.FAIL,
                        new INTEGER(OtherInfo.BAD_IDENTITY), null);
                cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.FAILED,
                        identityBpids, (String) null, otherInfo);
                tagattr = new TaggedAttribute(
                        new INTEGER(bpid++),
                        OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
                controlSeq.addElement(tagattr);
            }

            SEQUENCE POPLinkWitnessV2Bpids = (SEQUENCE) context.get("POPLinkWitnessV2");
            if (POPLinkWitnessV2Bpids != null && POPLinkWitnessV2Bpids.size() > 0) {
                OtherInfo otherInfo = new OtherInfo(OtherInfo.FAIL,
                        new INTEGER(OtherInfo.BAD_REQUEST), null);
                cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.FAILED,
                        POPLinkWitnessV2Bpids, (String) null, otherInfo);
                tagattr = new TaggedAttribute(
                        new INTEGER(bpid++),
                        OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
                controlSeq.addElement(tagattr);
            }

            SEQUENCE POPLinkWitnessBpids = (SEQUENCE) context.get("POPLinkWitness");
            if (POPLinkWitnessBpids != null && POPLinkWitnessBpids.size() > 0) {
                OtherInfo otherInfo = new OtherInfo(OtherInfo.FAIL,
                        new INTEGER(OtherInfo.BAD_REQUEST), null);
                cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.FAILED,
                        POPLinkWitnessBpids, (String) null, otherInfo);
                tagattr = new TaggedAttribute(
                        new INTEGER(bpid++),
                        OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
                controlSeq.addElement(tagattr);
            }

            if (pending_bpids.size() > 0) {
                // handle encryptedPOP control first

                if (encPop != null) {
                    CMS.debug(method + "adding encPop");
                    tagattr = new TaggedAttribute(
                            new INTEGER(bpid++),
                            OBJECT_IDENTIFIER.id_cmc_encryptedPOP,
                            encPop);
                    controlSeq.addElement(tagattr);
                    CMS.debug(method + "encPop added");
                }

                String reqId = reqs[0].getRequestId().toString();
                OtherInfo otherInfo = null;
                PendInfo pendInfo = new PendInfo(reqId, new Date());
                otherInfo = new OtherInfo(OtherInfo.PEND, null,
                        pendInfo);
                // cfu: inject POP_REQUIRED when working on V2 status
                cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.PENDING,
                        pending_bpids, (String) null, otherInfo);
                tagattr = new TaggedAttribute(
                        new INTEGER(bpid++),
                        OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
                controlSeq.addElement(tagattr);
            }

            if (success_bpids.size() > 0) {
                boolean confirmRequired = false;
                try {
                    confirmRequired =
                            CMS.getConfigStore().getBoolean("cmc.cert.confirmRequired",
                                    false);
                } catch (Exception e) {
                }
                if (confirmRequired) {
                    CMS.debug(method + " confirmRequired in the request");
                    cmcStatusInfo =
                            new CMCStatusInfo(CMCStatusInfo.CONFIRM_REQUIRED,
                                    success_bpids, (String) null, null);
                } else {
                    cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.SUCCESS,
                            success_bpids, (String) null, null);
                }
                tagattr = new TaggedAttribute(
                        new INTEGER(bpid++),
                        OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
                controlSeq.addElement(tagattr);
            }

            if (failed_bpids.size() > 0) {
                OtherInfo otherInfo = new OtherInfo(OtherInfo.FAIL,
                        new INTEGER(OtherInfo.BAD_REQUEST), null);
                cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.FAILED,
                        failed_bpids, (String) null, otherInfo);
                tagattr = new TaggedAttribute(
                        new INTEGER(bpid++),
                        OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
                controlSeq.addElement(tagattr);
            }
        }

        SET certs = new SET();

        try {
            // deal with controls
            Integer nums = (Integer) (context.get("numOfControls"));
            if (nums != null && nums.intValue() > 0) {
                CMS.debug(method + " processing controls");
                TaggedAttribute attr =
                        (TaggedAttribute) (context.get(OBJECT_IDENTIFIER.id_cmc_getCert));
                if (attr != null) {
                    try {
                        processGetCertControl(attr, certs);
                    } catch (EBaseException ee) {
                        CMS.debug(method + ee.toString());
                        OtherInfo otherInfo1 = new OtherInfo(OtherInfo.FAIL,
                                new INTEGER(OtherInfo.BAD_CERT_ID), null);
                        SEQUENCE bpids1 = new SEQUENCE();
                        bpids1.addElement(attr.getBodyPartID());
                        CMCStatusInfo cmcStatusInfo1 = new CMCStatusInfo(
                                new INTEGER(CMCStatusInfo.FAILED),
                                bpids1, null, otherInfo1);
                        TaggedAttribute tagattr1 = new TaggedAttribute(
                                new INTEGER(bpid++),
                                OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo1);
                        controlSeq.addElement(tagattr1);
                    }
                }

                attr =
                        (TaggedAttribute) (context.get(OBJECT_IDENTIFIER.id_cmc_dataReturn));
                if (attr != null)
                    bpid = processDataReturnControl(attr, controlSeq, bpid);

                attr =
                        (TaggedAttribute) context.get(OBJECT_IDENTIFIER.id_cmc_transactionId);
                if (attr != null)
                    bpid = processTransactionControl(attr, controlSeq, bpid);

                attr =
                        (TaggedAttribute) context.get(OBJECT_IDENTIFIER.id_cmc_senderNonce);
                if (attr != null)
                    bpid = processSenderNonceControl(attr, controlSeq, bpid);

                attr =
                        (TaggedAttribute) context.get(OBJECT_IDENTIFIER.id_cmc_QueryPending);
                if (attr != null)
                    bpid = processQueryPendingControl(attr, controlSeq, bpid);

                attr =
                        (TaggedAttribute) context.get(OBJECT_IDENTIFIER.id_cmc_idConfirmCertAcceptance);

                if (attr != null)
                    bpid = processConfirmCertAcceptanceControl(attr, controlSeq,
                            bpid);

                attr =
                        (TaggedAttribute) context.get(OBJECT_IDENTIFIER.id_cmc_revokeRequest);

                if (attr != null)
                    bpid = processRevokeRequestControl(attr, controlSeq,
                            bpid);
            }

            if (success_bpids != null && success_bpids.size() > 0) {
                for (int i = 0; i < reqs.length; i++) {
                    if (error_codes[i] == 0) {
                        X509CertImpl impl =
                                (reqs[i].getExtDataInCert(IEnrollProfile.REQUEST_ISSUED_CERT));
                        byte[] bin = impl.getEncoded();
                        Certificate.Template certTemplate = new Certificate.Template();
                        Certificate cert = (Certificate) certTemplate.decode(
                                new ByteArrayInputStream(bin));
                        certs.addElement(cert);
                    }
                }
            }

            ResponseBody respBody = new ResponseBody(controlSeq,
                    cmsSeq, otherMsgSeq);
            CMS.debug(method + " after new ResponseBody, respBody not null");

            ContentInfo contentInfo = getContentInfo(respBody, certs);
            ByteArrayOutputStream fos = new ByteArrayOutputStream();
            contentInfo.encode(fos);
            fos.close();
            byte[] contentBytes = fos.toByteArray();

            resp.setContentType("application/pkcs7-mime");
            resp.setContentLength(contentBytes.length);
            OutputStream os = resp.getOutputStream();
            os.write(contentBytes);
            os.flush();
            CMS.debug(method + "ends");
        } catch (java.security.cert.CertificateEncodingException e) {
            CMS.debug(method + e.toString());
        } catch (InvalidBERException e) {
            CMS.debug(method + e.toString());
        } catch (IOException e) {
            CMS.debug(method + e.toString());
        } catch (Exception e) {
            CMS.debug(method + e.toString());
        }
    }

    /**
     * constructEncryptedPop pulls cmc pop challenge fields out of the request
     * and constructs an EncryptedPOP
     * to be included in the response later
     *
     * @author cfu
     */
    public EncryptedPOP constructEncryptedPop(IRequest req)
            throws EBaseException {
        String method = "CMCOutputTemplate: constructEncryptedPop: ";
        String msg = "";
        CMS.debug(method + "begins");
        EncryptedPOP encPop = null;

        if (req == null) {
            msg = method + "method parameters cannot be null";
            CMS.debug(msg);
            throw new EBaseException(msg);
        }

        boolean popChallengeRequired = req.getExtDataInBoolean("cmc_POPchallengeRequired", false);
        if (!popChallengeRequired) {
            CMS.debug(method + "popChallengeRequired false");
            return null;
        }
        CMS.debug(method + "popChallengeRequired true");

        byte[] cmc_msg = req.getExtDataInByteArray(IEnrollProfile.CTX_CERT_REQUEST);
        byte[] pop_encryptedData = req.getExtDataInByteArray("pop_encryptedData");
        //don't need this for encryptedPOP, but need to check for existence anyway
        byte[] pop_sysPubEncryptedSession = req.getExtDataInByteArray("pop_sysPubEncryptedSession");
        byte[] pop_userPubEncryptedSession = req.getExtDataInByteArray("pop_userPubEncryptedSession");
        byte[] iv = req.getExtDataInByteArray("pop_encryptedDataIV");
        if ((pop_encryptedData != null) &&
                (pop_sysPubEncryptedSession != null) &&
                (pop_userPubEncryptedSession != null)) {
            // generate encryptedPOP here
            // algs are hard-coded for now

            try {
                EnvelopedData envData = CryptoUtil.createEnvelopedData(
                        pop_encryptedData,
                        pop_userPubEncryptedSession);
                if (envData == null) {
                    msg = "envData null returned by createEnvelopedData";
                    throw new EBaseException(method + msg);
                }
                ContentInfo ci = new ContentInfo(envData);
                CMS.debug(method + "now we can compose encryptedPOP");

                TaggedRequest.Template tReqTemplate = new TaggedRequest.Template();
                TaggedRequest tReq = (TaggedRequest) tReqTemplate.decode(
                        new ByteArrayInputStream(cmc_msg));
                if (tReq == null) {
                    msg = "tReq null from tReqTemplate.decode";
                    CMS.debug(msg);
                    throw new EBaseException(method + msg);
                }

                OBJECT_IDENTIFIER oid = EncryptionAlgorithm.AES_128_CBC.toOID();
                AlgorithmIdentifier aid = new AlgorithmIdentifier(oid, new OCTET_STRING(iv));

                encPop = new EncryptedPOP(
                        tReq,
                        ci,
                        aid,
                        CryptoUtil.getDefaultHashAlg(),
                        new OCTET_STRING(req.getExtDataInByteArray("pop_witness")));

            } catch (Exception e) {
                CMS.debug(method + " excepton:" + e);
                throw new EBaseException(method + " exception:" + e);
            }

        } else {
            msg = "popChallengeRequired required, but one more more of the pop_ data not found in request";
            CMS.debug(method + msg);
            throw new EBaseException(method + msg);
        }

        return encPop;
    }

    private ContentInfo getContentInfo(ResponseBody respBody, SET certs) {
        String method = "CMCOutputTemplate: getContentInfo: ";
        CMS.debug(method + "begins");
        try {
            ICertificateAuthority ca = null;
            // add CA cert chain
            ca = (ICertificateAuthority) CMS.getSubsystem("ca");
            CertificateChain certchains = ca.getCACertChain();
            java.security.cert.X509Certificate[] chains = certchains.getChain();

            for (int i = 0; i < chains.length; i++) {
                Certificate.Template certTemplate = new Certificate.Template();
                Certificate cert = (Certificate) certTemplate.decode(
                        new ByteArrayInputStream(chains[i].getEncoded()));
                certs.addElement(cert);
            }

            EncapsulatedContentInfo enContentInfo = new EncapsulatedContentInfo(
                    OBJECT_IDENTIFIER.id_cct_PKIResponse, respBody);
            org.mozilla.jss.crypto.X509Certificate x509CAcert = null;
            x509CAcert = ca.getCaX509Cert();
            X509CertImpl caimpl = new X509CertImpl(x509CAcert.getEncoded());
            X500Name issuerName = (X500Name) caimpl.getIssuerDN();
            byte[] issuerByte = issuerName.getEncoded();
            ByteArrayInputStream istream = new ByteArrayInputStream(issuerByte);
            Name issuer = (Name) Name.getTemplate().decode(istream);
            IssuerAndSerialNumber ias = new IssuerAndSerialNumber(
                    issuer, new INTEGER(x509CAcert.getSerialNumber().toString()));
            SignerIdentifier si = new SignerIdentifier(
                    SignerIdentifier.ISSUER_AND_SERIALNUMBER, ias, null);
            // use CA instance's default signature and digest algorithm
            SignatureAlgorithm signAlg = ca.getDefaultSignatureAlgorithm();
            org.mozilla.jss.crypto.PrivateKey privKey =
                    CryptoManager.getInstance().findPrivKeyByCert(x509CAcert);
            /*
                        org.mozilla.jss.crypto.PrivateKey.Type keyType = privKey.getType();
                        if( keyType.equals( org.mozilla.jss.crypto.PrivateKey.RSA ) ) {
                            signAlg = SignatureAlgorithm.RSASignatureWithSHA1Digest;
                        } else if( keyType.equals( org.mozilla.jss.crypto.PrivateKey.DSA ) ) {
                            signAlg = SignatureAlgorithm.DSASignatureWithSHA1Digest;
                        } else if( keyType.equals( org.mozilla.jss.crypto.PrivateKey.EC ) ) {
                             signAlg = SignatureAlgorithm.ECSignatureWithSHA1Digest;
                        } else {
                            CMS.debug( "CMCOutputTemplate::getContentInfo() - "
                                     + "signAlg is unsupported!" );
                            return null;
                        }
            */
            DigestAlgorithm digestAlg = signAlg.getDigestAlg();
            MessageDigest msgDigest = null;
            byte[] digest = null;

            msgDigest = MessageDigest.getInstance(digestAlg.toString());

            ByteArrayOutputStream ostream = new ByteArrayOutputStream();

            respBody.encode(ostream);
            digest = msgDigest.digest(ostream.toByteArray());

            SignerInfo signInfo = new
                    SignerInfo(si, null, null,
                            OBJECT_IDENTIFIER.id_cct_PKIResponse,
                            digest, signAlg, privKey);
            SET signInfos = new SET();

            signInfos.addElement(signInfo);

            SET digestAlgs = new SET();

            if (digestAlg != null) {
                AlgorithmIdentifier ai = new
                        AlgorithmIdentifier(digestAlg.toOID(), null);

                digestAlgs.addElement(ai);
            }
            SignedData signedData = new SignedData(digestAlgs,
                    enContentInfo, certs, null, signInfos);

            ContentInfo contentInfo = new ContentInfo(signedData);
            CMS.debug(method + " - done");
            return contentInfo;
        } catch (Exception e) {
            CMS.debug(method + " Failed to create CMCContentInfo. Exception: " + e.toString());
        }
        return null;
    }

    public void createSimpleResponse(HttpServletResponse resp, IRequest[] reqs) {
        SET certs = new SET();
        SessionContext context = SessionContext.getContext();
        try {
            TaggedAttribute attr =
                    (TaggedAttribute) (context.get(OBJECT_IDENTIFIER.id_cmc_getCert));
            processGetCertControl(attr, certs);
        } catch (Exception e) {
            CMS.debug("CMCOutputTemplate: No certificate is found.");
        }

        SET digestAlgorithms = new SET();
        SET signedInfos = new SET();

        // oid for id-data
        OBJECT_IDENTIFIER oid = new OBJECT_IDENTIFIER("1.2.840.113549.1.7.1");
        EncapsulatedContentInfo enContentInfo = new EncapsulatedContentInfo(oid, null);

        try {
            if (reqs != null) {
                for (int i = 0; i < reqs.length; i++) {
                    X509CertImpl impl =
                            (reqs[i].getExtDataInCert(IEnrollProfile.REQUEST_ISSUED_CERT));
                    byte[] bin = impl.getEncoded();
                    Certificate.Template certTemplate = new Certificate.Template();
                    Certificate cert =
                            (Certificate) certTemplate.decode(new ByteArrayInputStream(bin));

                    certs.addElement(cert);
                }

                // Get CA certs
                ICertificateAuthority ca = (ICertificateAuthority) CMS.getSubsystem("ca");
                CertificateChain certchains = ca.getCACertChain();
                java.security.cert.X509Certificate[] chains = certchains.getChain();

                for (int i = 0; i < chains.length; i++) {
                    Certificate.Template certTemplate = new Certificate.Template();
                    Certificate cert = (Certificate) certTemplate.decode(
                            new ByteArrayInputStream(chains[i].getEncoded()));
                    certs.addElement(cert);
                }
            }

            if (certs.size() == 0)
                return;
            SignedData signedData = new SignedData(digestAlgorithms,
                    enContentInfo, certs, null, signedInfos);

            ContentInfo contentInfo = new ContentInfo(signedData);
            ByteArrayOutputStream fos = new ByteArrayOutputStream();
            contentInfo.encode(fos);
            fos.close();
            byte[] contentBytes = fos.toByteArray();

            resp.setContentType("application/pkcs7-mime");
            resp.setContentLength(contentBytes.length);
            OutputStream os = resp.getOutputStream();
            os.write(contentBytes);
            os.flush();
        } catch (java.security.cert.CertificateEncodingException e) {
            CMS.debug("CMCOutputTemplate exception: " + e.toString());
        } catch (InvalidBERException e) {
            CMS.debug("CMCOutputTemplate exception: " + e.toString());
        } catch (IOException e) {
            CMS.debug("CMCOutputTemplate exception: " + e.toString());
        }
    }

    private int processConfirmCertAcceptanceControl(
            TaggedAttribute attr, SEQUENCE controlSeq, int bpid) {
        if (attr != null) {
            INTEGER bodyId = attr.getBodyPartID();
            SEQUENCE seq = new SEQUENCE();
            seq.addElement(bodyId);
            SET values = attr.getValues();
            if (values != null && values.size() > 0) {
                try {
                    CMCCertId cmcCertId =
                            (CMCCertId) (ASN1Util.decode(CMCCertId.getTemplate(),
                                    ASN1Util.encode(values.elementAt(0))));
                    BigInteger serialno = cmcCertId.getSerial();
                    SEQUENCE issuers = cmcCertId.getIssuer();
                    //ANY issuer = (ANY)issuers.elementAt(0);
                    ANY issuer =
                            (ANY) (ASN1Util.decode(ANY.getTemplate(),
                                    ASN1Util.encode(issuers.elementAt(0))));
                    byte[] b = issuer.getEncoded();
                    X500Name n = new X500Name(b);
                    ICertificateAuthority ca = null;
                    ca = (ICertificateAuthority) CMS.getSubsystem("ca");
                    X500Name caName = ca.getX500Name();
                    boolean confirmAccepted = false;
                    if (n.toString().equalsIgnoreCase(caName.toString())) {
                        CMS.debug("CMCOutputTemplate: Issuer names are equal");
                        ICertificateRepository repository = ca.getCertificateRepository();
                        try {
                            repository.getX509Certificate(serialno);
                        } catch (EBaseException ee) {
                            CMS.debug("CMCOutputTemplate: Certificate in the confirm acceptance control was not found");
                        }
                    }
                    CMCStatusInfo cmcStatusInfo = null;
                    if (confirmAccepted) {
                        CMS.debug("CMCOutputTemplate: Confirm Acceptance received. The certificate exists in the certificate repository.");
                        cmcStatusInfo =
                                new CMCStatusInfo(CMCStatusInfo.SUCCESS, seq,
                                        (String) null, null);
                    } else {
                        CMS.debug("CMCOutputTemplate: Confirm Acceptance received. The certificate does not exist in the certificate repository.");
                        OtherInfo otherInfo = new OtherInfo(OtherInfo.FAIL,
                                new INTEGER(OtherInfo.BAD_CERT_ID), null);
                        cmcStatusInfo =
                                new CMCStatusInfo(CMCStatusInfo.FAILED, seq,
                                        (String) null, otherInfo);
                    }
                    TaggedAttribute statustagattr = new TaggedAttribute(
                            new INTEGER(bpid++),
                            OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
                    controlSeq.addElement(statustagattr);
                } catch (Exception e) {
                    CMS.debug("CMCOutputTemplate exception: " + e.toString());
                }
            }
        }
        return bpid;
    }

    private void processGetCertControl(TaggedAttribute attr, SET certs)
            throws InvalidBERException, java.security.cert.CertificateEncodingException,
            IOException, EBaseException {
        if (attr != null) {
            SET vals = attr.getValues();

            if (vals.size() == 1) {
                GetCert getCert =
                        (GetCert) (ASN1Util.decode(GetCert.getTemplate(),
                                ASN1Util.encode(vals.elementAt(0))));
                BigInteger serialno = getCert.getSerialNumber();
                ANY issuer = getCert.getIssuer();
                byte b[] = issuer.getEncoded();
                X500Name n = new X500Name(b);
                ICertificateAuthority ca = (ICertificateAuthority) CMS.getSubsystem("ca");
                X500Name caName = ca.getX500Name();
                if (!n.toString().equalsIgnoreCase(caName.toString())) {
                    CMS.debug("CMCOutputTemplate: Issuer names are equal in the GetCert Control");
                    throw new EBaseException("Certificate is not found");
                }
                ICertificateRepository repository =
                        ca.getCertificateRepository();
                X509CertImpl impl = repository.getX509Certificate(serialno);
                byte[] bin = impl.getEncoded();
                Certificate.Template certTemplate = new Certificate.Template();
                Certificate cert =
                        (Certificate) certTemplate.decode(new ByteArrayInputStream(bin));
                certs.addElement(cert);
            }
        }
    }

    private int processQueryPendingControl(TaggedAttribute attr,
            SEQUENCE controlSeq, int bpid) {
        if (attr != null) {
            SET values = attr.getValues();
            if (values != null && values.size() > 0) {
                SEQUENCE pending_bpids = new SEQUENCE();
                SEQUENCE success_bpids = new SEQUENCE();
                SEQUENCE failed_bpids = new SEQUENCE();
                for (int i = 0; i < values.size(); i++) {
                    try {
                        INTEGER reqId = (INTEGER)
                                ASN1Util.decode(INTEGER.getTemplate(),
                                        ASN1Util.encode(values.elementAt(i)));
                        String requestId = new String(reqId.toByteArray());

                        ICertificateAuthority ca = (ICertificateAuthority) CMS.getSubsystem("ca");
                        IRequestQueue queue = ca.getRequestQueue();
                        IRequest r = queue.findRequest(new RequestId(requestId));
                        if (r != null) {
                            RequestStatus status = r.getRequestStatus();
                            if (status.equals(RequestStatus.PENDING)) {
                                pending_bpids.addElement(reqId);
                            } else if (status.equals(RequestStatus.APPROVED)) {
                                success_bpids.addElement(reqId);
                            } else if (status.equals(RequestStatus.REJECTED)) {
                                failed_bpids.addElement(reqId);
                            }
                        }
                    } catch (Exception e) {
                    }
                }

                if (pending_bpids.size() > 0) {
                    CMCStatusInfo cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.PENDING,
                            pending_bpids, (String) null, null);
                    TaggedAttribute tagattr = new TaggedAttribute(
                            new INTEGER(bpid++),
                            OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
                    controlSeq.addElement(tagattr);
                }
                if (success_bpids.size() > 0) {
                    CMCStatusInfo cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.SUCCESS,
                            pending_bpids, (String) null, null);
                    TaggedAttribute tagattr = new TaggedAttribute(
                            new INTEGER(bpid++),
                            OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
                    controlSeq.addElement(tagattr);
                }

                if (failed_bpids.size() > 0) {
                    CMCStatusInfo cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.FAILED,
                            pending_bpids, (String) null, null);
                    TaggedAttribute tagattr = new TaggedAttribute(
                            new INTEGER(bpid++),
                            OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
                    controlSeq.addElement(tagattr);
                }

            }
        }
        return bpid;
    }

    private int processTransactionControl(TaggedAttribute attr,
            SEQUENCE controlSeq, int bpid) {
        if (attr != null) {
            SET transIds = attr.getValues();
            if (transIds != null) {
                TaggedAttribute tagattr = new TaggedAttribute(
                        new INTEGER(bpid++), OBJECT_IDENTIFIER.id_cmc_transactionId,
                        transIds);
                controlSeq.addElement(tagattr);
            }
        }

        return bpid;
    }

    private int processSenderNonceControl(TaggedAttribute attr,
            SEQUENCE controlSeq, int bpid) {
        if (attr != null) {
            SET sNonce = attr.getValues();
            if (sNonce != null) {
                TaggedAttribute tagattr = new TaggedAttribute(
                        new INTEGER(bpid++), OBJECT_IDENTIFIER.id_cmc_recipientNonce,
                        sNonce);
                controlSeq.addElement(tagattr);
                Date date = new Date();
                String salt = "lala123" + date.toString();
                byte[] dig;
                try {
                    MessageDigest SHA2Digest = MessageDigest.getInstance("SHA256");
                    dig = SHA2Digest.digest(salt.getBytes());
                } catch (NoSuchAlgorithmException ex) {
                    dig = salt.getBytes();
                }

                String b64E = CMS.BtoA(dig);
                tagattr = new TaggedAttribute(
                        new INTEGER(bpid++), OBJECT_IDENTIFIER.id_cmc_senderNonce,
                        new OCTET_STRING(b64E.getBytes()));
                controlSeq.addElement(tagattr);
            }
        }

        return bpid;
    }

    private int processDataReturnControl(TaggedAttribute attr,
            SEQUENCE controlSeq, int bpid) throws InvalidBERException {

        if (attr != null) {
            SET vals = attr.getValues();

            if (vals.size() > 0) {
                OCTET_STRING str =
                        (OCTET_STRING) (ASN1Util.decode(OCTET_STRING.getTemplate(),
                                ASN1Util.encode(vals.elementAt(0))));
                TaggedAttribute tagattr = new TaggedAttribute(
                        new INTEGER(bpid++),
                        OBJECT_IDENTIFIER.id_cmc_dataReturn, str);
                controlSeq.addElement(tagattr);
            }
        }

        return bpid;
    }

    private int processRevokeRequestControl(TaggedAttribute attr,
            SEQUENCE controlSeq, int bpid) throws InvalidBERException, EBaseException,
            IOException {
        String method = "CMCOutputTemplate: processRevokeRequestControl: ";
        String msg = "";
        CMS.debug(method + "begins");
        boolean revoke = false;
        SessionContext context = SessionContext.getContext();
        String authManagerId = (String) context.get(SessionContext.AUTH_MANAGER_ID);
        if (authManagerId == null) {
            CMS.debug(method + "authManagerId null.????");
            //unlikely, but...
            authManagerId = "none";
        } else {
            CMS.debug(method + "authManagerId =" + authManagerId);
        }

        // in case of CMCUserSignedAuth,
        // for matching signer and revoked cert principal
        X500Name signerPrincipal = null;

        // for auditing
        String auditRequesterID = null;
        auditRequesterID = (String) context.get(SessionContext.USER_ID);

        if (auditRequesterID != null) {
            auditRequesterID = auditRequesterID.trim();
        } else {
            auditRequesterID = ILogger.NONROLEUSER;
        }
        signerPrincipal = (X500Name) context.get(SessionContext.CMC_SIGNER_PRINCIPAL);
        String auditSubjectID = null;
        String auditRequestType = "revoke";
        String auditSerialNumber = null;
        String auditReasonNum = null;
        RequestStatus auditApprovalStatus = RequestStatus.REJECTED;

        if (attr != null) {
            INTEGER attrbpid = attr.getBodyPartID();
            CMCStatusInfo cmcStatusInfo = null;
            SET vals = attr.getValues();
            if (vals.size() > 0) {
                RevokeRequest revRequest = (RevokeRequest) (ASN1Util.decode(new RevokeRequest.Template(),
                        ASN1Util.encode(vals.elementAt(0))));
                OCTET_STRING reqSecret = revRequest.getSharedSecret();
                INTEGER pid = attr.getBodyPartID();
                TaggedAttribute tagattr = null;
                INTEGER revokeCertSerial = revRequest.getSerialNumber();
                ENUMERATED n = revRequest.getReason();
                RevocationReason reason = toRevocationReason(n);
                auditReasonNum = reason.toString();
                BigInteger revokeSerial = new BigInteger(revokeCertSerial.toByteArray());
                auditSerialNumber = revokeSerial.toString();

                if (reqSecret == null) {
                    CMS.debug(method + "no shared secret in request; Checking signature;");
                    boolean needVerify = true;
                    try {
                        needVerify = CMS.getConfigStore().getBoolean("cmc.revokeCert.verify", true);
                    } catch (Exception e) {
                    }

                    if (needVerify) {
                        if (authManagerId.equals("CMCUserSignedAuth")) {
                            if (signerPrincipal == null) {
                                CMS.debug(method + "missing CMC signer principal");
                                OtherInfo otherInfo = new OtherInfo(OtherInfo.FAIL,
                                        new INTEGER(OtherInfo.BAD_MESSAGE_CHECK),
                                        null);
                                SEQUENCE failed_bpids = new SEQUENCE();
                                failed_bpids.addElement(attrbpid);
                                cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.FAILED, failed_bpids, (String) null,
                                        otherInfo);
                                tagattr = new TaggedAttribute(
                                        new INTEGER(bpid++),
                                        OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
                                controlSeq.addElement(tagattr);
                                return bpid;
                            }
                        } else { // !CMCUserSignedAuth

                            // this code is making the assumption that OtherMsg
                            // is used for signer info in signed cmc revocation,
                            // when in fact the signer info is
                            // in the outer layer and should have already been
                            // verified in the auth manager;
                            // Left here for possible legacy client(s)

                            Integer num1 = (Integer) context.get("numOfOtherMsgs");
                            CMS.debug(method + "found numOfOtherMsgs =" + num1.toString());
                            int num = num1.intValue();
                            for (int i = 0; i < num; i++) {
                                OtherMsg data = (OtherMsg) context.get("otherMsg" + i);
                                INTEGER dpid = data.getBodyPartID();
                                if (pid.longValue() == dpid.longValue()) {
                                    CMS.debug(method + "body part id match;");
                                    ANY msgValue = data.getOtherMsgValue();
                                    SignedData msgData = (SignedData) msgValue.decodeWith(SignedData.getTemplate());
                                    if (!verifyRevRequestSignature(msgData)) {
                                        OtherInfo otherInfo = new OtherInfo(OtherInfo.FAIL,
                                                new INTEGER(OtherInfo.BAD_MESSAGE_CHECK),
                                                null);
                                        SEQUENCE failed_bpids = new SEQUENCE();
                                        failed_bpids.addElement(attrbpid);
                                        cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.FAILED, failed_bpids,
                                                (String) null,
                                                otherInfo);
                                        tagattr = new TaggedAttribute(
                                                new INTEGER(bpid++),
                                                OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
                                        controlSeq.addElement(tagattr);
                                        return bpid;
                                    }
                                } else {
                                    CMS.debug(method + "body part id do not match;");
                                }
                            }
                        }
                    }

                    revoke = true;
                } else { //use shared secret; request unsigned
                    CMS.debug(method + "checking shared secret");
                    // check shared secret
                    //TODO: remember to provide one-time-use when working
                    //      on shared token
                    ISharedToken tokenClass =
                            CMS.getSharedTokenClass("cmc.revokeCert.sharedSecret.class");
                    if (tokenClass == null) {
                        CMS.debug(method + " Failed to retrieve shared secret plugin class");
                        OtherInfo otherInfo = new OtherInfo(OtherInfo.FAIL, new INTEGER(OtherInfo.INTERNAL_CA_ERROR),
                                null);
                        SEQUENCE failed_bpids = new SEQUENCE();
                        failed_bpids.addElement(attrbpid);
                        cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.FAILED, failed_bpids, (String) null, otherInfo);
                        tagattr = new TaggedAttribute(
                                new INTEGER(bpid++),
                                OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
                        controlSeq.addElement(tagattr);
                        return bpid;
                    }

                    String sharedSecret = 
                            sharedSecret = tokenClass.getSharedToken(revokeSerial);

                    if (sharedSecret == null) {
                        CMS.debug("CMCOutputTemplate: shared secret not found.");
                        OtherInfo otherInfo = new OtherInfo(OtherInfo.FAIL, new INTEGER(OtherInfo.INTERNAL_CA_ERROR),
                                null);
                        SEQUENCE failed_bpids = new SEQUENCE();
                        failed_bpids.addElement(attrbpid);
                        cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.FAILED, failed_bpids, (String) null, otherInfo);
                        tagattr = new TaggedAttribute(
                                new INTEGER(bpid++),
                                OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
                        controlSeq.addElement(tagattr);
                        return bpid;
                    }

                    byte[] reqSecretb = reqSecret.toByteArray();
                    String clientSC = new String(reqSecretb);
                    if (clientSC.equals(sharedSecret)) {
                        CMS.debug(method
                                + " Client and server shared secret are the same, can go ahead and revoke certificate.");
                        revoke = true;
                    } else {
                        CMS.debug(method
                                + " Client and server shared secret are not the same, cannot revoke certificate.");
                        OtherInfo otherInfo = new OtherInfo(OtherInfo.FAIL, new INTEGER(OtherInfo.BAD_MESSAGE_CHECK),
                                null);
                        SEQUENCE failed_bpids = new SEQUENCE();
                        failed_bpids.addElement(attrbpid);
                        cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.FAILED, failed_bpids, (String) null, otherInfo);
                        tagattr = new TaggedAttribute(
                                new INTEGER(bpid++),
                                OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
                        controlSeq.addElement(tagattr);

                        audit(new CertStatusChangeRequestProcessedEvent(
                                auditSubjectID,
                                ILogger.FAILURE,
                                auditRequesterID,
                                auditSerialNumber,
                                auditRequestType,
                                auditReasonNum,
                                auditApprovalStatus));

                        return bpid;
                    }
                }

                if (revoke) {
                    ICertificateAuthority ca = (ICertificateAuthority) CMS.getSubsystem("ca");
                    ICertificateRepository repository = ca.getCertificateRepository();
                    ICertRecord record = null;
                    try {
                        record = repository.readCertificateRecord(revokeSerial);
                    } catch (EBaseException ee) {
                        CMS.debug(method + "Exception: " + ee.toString());
                    }

                    if (record == null) {
                        CMS.debug(method + " The certificate is not found");
                        OtherInfo otherInfo = new OtherInfo(OtherInfo.FAIL, new INTEGER(OtherInfo.BAD_CERT_ID), null);
                        SEQUENCE failed_bpids = new SEQUENCE();
                        failed_bpids.addElement(attrbpid);
                        cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.FAILED, failed_bpids, (String) null, otherInfo);
                        tagattr = new TaggedAttribute(
                                new INTEGER(bpid++),
                                OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
                        controlSeq.addElement(tagattr);
                        return bpid;
                    }

                    if (record.getStatus().equals(ICertRecord.STATUS_REVOKED)) {
                        CMS.debug("CMCOutputTemplate: The certificate is already revoked.");
                        SEQUENCE success_bpids = new SEQUENCE();
                        success_bpids.addElement(attrbpid);
                        cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.SUCCESS,
                                success_bpids, (String) null, null);
                        tagattr = new TaggedAttribute(
                                new INTEGER(bpid++),
                                OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
                        controlSeq.addElement(tagattr);
                        return bpid;
                    }

                    X509CertImpl impl = record.getCertificate();

                    X500Name certPrincipal = (X500Name) impl.getSubjectDN();
                    auditSubjectID = certPrincipal.getCommonName();

                    // in case of user-signed request, check if signer
                    // principal matches that of the revoking cert
                    if ((reqSecret == null) && authManagerId.equals("CMCUserSignedAuth")) {
                        if (!certPrincipal.equals(signerPrincipal)) {
                            msg = "certificate principal and signer do not match";
                            CMS.debug(method + msg);
                            OtherInfo otherInfo = new OtherInfo(OtherInfo.FAIL, new INTEGER(OtherInfo.BAD_IDENTITY),
                                    null);
                            SEQUENCE failed_bpids = new SEQUENCE();
                            failed_bpids.addElement(attrbpid);
                            cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.FAILED, failed_bpids, msg,
                                    otherInfo);
                            tagattr = new TaggedAttribute(
                                    new INTEGER(bpid++),
                                    OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
                            controlSeq.addElement(tagattr);

                            audit(new CertStatusChangeRequestProcessedEvent(
                                    auditSubjectID,
                                    ILogger.FAILURE,
                                    auditRequesterID,
                                    auditSerialNumber,
                                    auditRequestType,
                                    auditReasonNum,
                                    auditApprovalStatus));

                            return bpid;
                        } else {
                            CMS.debug(method + "certificate principal and signer match");
                        }
                    }

                    X509CertImpl[] impls = new X509CertImpl[1];
                    impls[0] = impl;
                    CRLReasonExtension crlReasonExtn = new CRLReasonExtension(reason);
                    CRLExtensions entryExtn = new CRLExtensions();
                    GeneralizedTime t = revRequest.getInvalidityDate();
                    InvalidityDateExtension invalidityDateExtn = null;
                    if (t != null) {
                        invalidityDateExtn = new InvalidityDateExtension(t.toDate());
                        entryExtn.set(invalidityDateExtn.getName(), invalidityDateExtn);
                    }
                    if (crlReasonExtn != null) {
                        entryExtn.set(crlReasonExtn.getName(), crlReasonExtn);
                    }

                    RevokedCertImpl revCertImpl = new RevokedCertImpl(impl.getSerialNumber(), CMS.getCurrentDate(),
                            entryExtn);
                    RevokedCertImpl[] revCertImpls = new RevokedCertImpl[1];
                    revCertImpls[0] = revCertImpl;
                    IRequestQueue queue = ca.getRequestQueue();
                    IRequest revReq = queue.newRequest(IRequest.REVOCATION_REQUEST);
                    revReq.setExtData(IRequest.CERT_INFO, revCertImpls);
                    revReq.setExtData(IRequest.REVOKED_REASON,
                            Integer.valueOf(reason.toInt()));
                    UTF8String utfstr = revRequest.getComment();
                    if (utfstr != null)
                        revReq.setExtData(IRequest.REQUESTOR_COMMENTS, utfstr.toString());
                    revReq.setExtData(IRequest.REQUESTOR_TYPE, IRequest.REQUESTOR_AGENT);
                    queue.processRequest(revReq);
                    RequestStatus stat = revReq.getRequestStatus();
                    if (stat == RequestStatus.COMPLETE) {
                        Integer result = revReq.getExtDataInInteger(IRequest.RESULT);
                        CMS.debug(method + " revReq result = " + result);
                        if (result.equals(IRequest.RES_ERROR)) {
                            CMS.debug("CMCOutputTemplate: revReq exception: " +
                                    revReq.getExtDataInString(IRequest.ERROR));
                            OtherInfo otherInfo = new OtherInfo(OtherInfo.FAIL, new INTEGER(OtherInfo.BAD_REQUEST),
                                    null);
                            SEQUENCE failed_bpids = new SEQUENCE();
                            failed_bpids.addElement(attrbpid);
                            cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.FAILED, failed_bpids, (String) null,
                                    otherInfo);
                            tagattr = new TaggedAttribute(
                                    new INTEGER(bpid++),
                                    OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
                            controlSeq.addElement(tagattr);

                            audit(new CertStatusChangeRequestProcessedEvent(
                                    auditSubjectID,
                                    ILogger.FAILURE,
                                    auditRequesterID,
                                    auditSerialNumber,
                                    auditRequestType,
                                    auditReasonNum,
                                    auditApprovalStatus));

                            return bpid;
                        }
                    }

                    ILogger logger = CMS.getLogger();
                    String initiative = AuditFormat.FROMUSER;
                    logger.log(ILogger.EV_AUDIT, ILogger.S_OTHER, AuditFormat.LEVEL,
                            AuditFormat.DOREVOKEFORMAT, new Object[] {
                                    revReq.getRequestId(), initiative, "completed",
                                    impl.getSubjectDN(),
                                    impl.getSerialNumber().toString(16),
                                    reason.toString() });
                    CMS.debug(method + " Certificate revoked.");
                    SEQUENCE success_bpids = new SEQUENCE();
                    success_bpids.addElement(attrbpid);
                    cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.SUCCESS,
                            success_bpids, (String) null, null);
                    tagattr = new TaggedAttribute(
                            new INTEGER(bpid++),
                            OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
                    controlSeq.addElement(tagattr);

                    auditApprovalStatus = RequestStatus.COMPLETE;
                    audit(new CertStatusChangeRequestProcessedEvent(
                            auditSubjectID,
                            ILogger.SUCCESS,
                            auditRequesterID,
                            auditSerialNumber,
                            auditRequestType,
                            auditReasonNum,
                            auditApprovalStatus));
                    return bpid;
                } else {
                    OtherInfo otherInfo = new OtherInfo(OtherInfo.FAIL, new INTEGER(OtherInfo.BAD_MESSAGE_CHECK), null);
                    SEQUENCE failed_bpids = new SEQUENCE();
                    failed_bpids.addElement(attrbpid);
                    cmcStatusInfo = new CMCStatusInfo(CMCStatusInfo.FAILED, failed_bpids, (String) null, otherInfo);
                    tagattr = new TaggedAttribute(
                            new INTEGER(bpid++),
                            OBJECT_IDENTIFIER.id_cmc_cMCStatusInfo, cmcStatusInfo);
                    controlSeq.addElement(tagattr);

                    audit(new CertStatusChangeRequestProcessedEvent(
                            auditSubjectID,
                            ILogger.FAILURE,
                            auditRequesterID,
                            auditSerialNumber,
                            auditRequestType,
                            auditReasonNum,
                            auditApprovalStatus));

                    return bpid;
                }
            }
        }

        return bpid;
    }

    protected void audit(AuditEvent event) {

        String template = event.getMessage();
        Object[] params = event.getParameters();

        String message = CMS.getLogMessage(template, params);

        audit(message);
    }

    protected void audit(String msg) {
        // in this case, do NOT strip preceding/trailing whitespace
        // from passed-in String parameters

        if (mSignedAuditLogger == null) {
            return;
        }

        mSignedAuditLogger.log(ILogger.EV_SIGNED_AUDIT,
                null,
                ILogger.S_SIGNED_AUDIT,
                ILogger.LL_SECURITY,
                msg);
    }

    private RevocationReason toRevocationReason(ENUMERATED n) {
        long code = n.getValue();
        if (code == RevokeRequest.aACompromise.getValue())
            return RevocationReason.UNSPECIFIED;
        else if (code == RevokeRequest.affiliationChanged.getValue())
            return RevocationReason.AFFILIATION_CHANGED;
        else if (code == RevokeRequest.cACompromise.getValue())
            return RevocationReason.CA_COMPROMISE;
        else if (code == RevokeRequest.certificateHold.getValue())
            return RevocationReason.CERTIFICATE_HOLD;
        else if (code == RevokeRequest.cessationOfOperation.getValue())
            return RevocationReason.CESSATION_OF_OPERATION;
        else if (code == RevokeRequest.keyCompromise.getValue())
            return RevocationReason.KEY_COMPROMISE;
        else if (code == RevokeRequest.privilegeWithdrawn.getValue())
            return RevocationReason.UNSPECIFIED;
        else if (code == RevokeRequest.removeFromCRL.getValue())
            return RevocationReason.REMOVE_FROM_CRL;
        else if (code == RevokeRequest.superseded.getValue())
            return RevocationReason.SUPERSEDED;
        else if (code == RevokeRequest.unspecified.getValue())
            return RevocationReason.UNSPECIFIED;
        return RevocationReason.UNSPECIFIED;
    }

    private boolean verifyRevRequestSignature(SignedData msgData) {
        String method = "CMCOutputTemplate: verifyRevRequestSignature: ";
        CMS.debug(method + "begins");
        try {
            EncapsulatedContentInfo ci = msgData.getContentInfo();
            OCTET_STRING content = ci.getContent();
            ByteArrayInputStream s = new ByteArrayInputStream(content.toByteArray());
            TaggedAttribute tattr = (TaggedAttribute) (new TaggedAttribute.Template()).decode(s);
            SET values = tattr.getValues();
            RevokeRequest revRequest = null;
            if (values != null && values.size() > 0) {
                revRequest = (RevokeRequest) (ASN1Util.decode(new RevokeRequest.Template(),
                        ASN1Util.encode(values.elementAt(0))));
            } else {
                CMS.debug(method + "attribute null");
                return false;
            }

            SET dias = msgData.getDigestAlgorithmIdentifiers();
            int numDig = dias.size();
            Hashtable<String, byte[]> digs = new Hashtable<String, byte[]>();
            for (int i = 0; i < numDig; i++) {
                AlgorithmIdentifier dai = (AlgorithmIdentifier) dias.elementAt(i);
                String name = DigestAlgorithm.fromOID(dai.getOID()).toString();
                MessageDigest md = MessageDigest.getInstance(name);
                byte[] digest = md.digest(content.toByteArray());
                digs.put(name, digest);
            }

            SET sis = msgData.getSignerInfos();
            int numSis = sis.size();
            for (int i = 0; i < numSis; i++) {
                org.mozilla.jss.pkix.cms.SignerInfo si = (org.mozilla.jss.pkix.cms.SignerInfo) sis.elementAt(i);
                String name = si.getDigestAlgorithm().toString();
                byte[] digest = digs.get(name);
                if (digest == null) {
                    MessageDigest md = MessageDigest.getInstance(name);
                    ByteArrayOutputStream ostream = new ByteArrayOutputStream();
                    revRequest.encode(ostream);
                    digest = md.digest(ostream.toByteArray());
                }
                SignerIdentifier sid = si.getSignerIdentifier();
                if (sid.getType().equals(SignerIdentifier.ISSUER_AND_SERIALNUMBER)) {
                    org.mozilla.jss.pkix.cms.IssuerAndSerialNumber issuerAndSerialNumber = sid
                            .getIssuerAndSerialNumber();
                    java.security.cert.X509Certificate cert = null;
                    if (msgData.hasCertificates()) {
                        SET certs = msgData.getCertificates();
                        int numCerts = certs.size();
                        for (int j = 0; j < numCerts; j++) {
                            org.mozilla.jss.pkix.cert.Certificate certJss = (Certificate) certs.elementAt(j);
                            org.mozilla.jss.pkix.cert.CertificateInfo certI = certJss.getInfo();
                            Name issuer = certI.getIssuer();
                            byte[] issuerB = ASN1Util.encode(issuer);
                            INTEGER sn = certI.getSerialNumber();
                            if (new String(issuerB).equalsIgnoreCase(new String(ASN1Util.encode(issuerAndSerialNumber
                                    .getIssuer()))) &&
                                    sn.toString().equals(issuerAndSerialNumber.getSerialNumber().toString())) {
                                ByteArrayOutputStream os = new ByteArrayOutputStream();
                                certJss.encode(os);
                                cert = new X509CertImpl(os.toByteArray());
                                break;
                            }
                        }
                    }

                    if (cert != null) {
                        CMS.debug(method + "found cert");
                        PublicKey pbKey = cert.getPublicKey();
                        PK11PubKey pubK = PK11PubKey.fromSPKI(((X509Key) pbKey).getKey());
                        si.verify(digest, ci.getContentType(), pubK);

                        // now check validity of the cert
                        java.security.cert.X509Certificate[] x509Certs = new java.security.cert.X509Certificate[1];
                        x509Certs[0] = cert;
                        if (CMS.isRevoked(x509Certs)) {
                            CMS.debug(method + "CMC signing cert is a revoked certificate");
                            return false;
                        }
                        try {
                            cert.checkValidity();
                        } catch (CertificateExpiredException e) {
                            CMS.debug(method + "CMC signing cert is an expired certificate");
                            return false;
                        } catch (Exception e) {
                            return false;
                        }

                        return true;
                    } else {
                        CMS.debug(method + "cert not found");
                    }
                } else {
                    CMS.debug(method + "unsupported SignerIdentifier for CMC revocation");
                }
            }

            return false;
        } catch (Exception e) {
            CMS.debug("CMCOutputTemplate: verifyRevRequestSignature. Exception: " + e.toString());
            return false;
        }
    }
}