summaryrefslogtreecommitdiffstats
path: root/base/server/cms/src/com/netscape/cms/profile/common/EnrollProfile.java
blob: 7dfaddac43b0033f950843b27b8ba72c33909434 (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
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
// --- 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.profile.common;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.cert.CertificateException;
import java.util.Arrays;
import java.util.Date;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Random;
import java.util.StringTokenizer;

import org.mozilla.jss.CryptoManager;
import org.mozilla.jss.asn1.ASN1Util;
import org.mozilla.jss.asn1.ASN1Value;
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.CryptoToken;
import org.mozilla.jss.crypto.DigestAlgorithm;
import org.mozilla.jss.crypto.EncryptionAlgorithm;
import org.mozilla.jss.crypto.HMACAlgorithm;
import org.mozilla.jss.crypto.IVParameterSpec;
import org.mozilla.jss.crypto.KeyGenAlgorithm;
import org.mozilla.jss.crypto.KeyWrapAlgorithm;
import org.mozilla.jss.crypto.PrivateKey;
import org.mozilla.jss.crypto.SymmetricKey;
import org.mozilla.jss.pkcs10.CertificationRequest;
import org.mozilla.jss.pkcs10.CertificationRequestInfo;
import org.mozilla.jss.pkix.cmc.DecryptedPOP;
import org.mozilla.jss.pkix.cmc.IdentityProofV2;
import org.mozilla.jss.pkix.cmc.LraPopWitness;
import org.mozilla.jss.pkix.cmc.OtherMsg;
import org.mozilla.jss.pkix.cmc.PKIData;
import org.mozilla.jss.pkix.cmc.PopLinkWitnessV2;
import org.mozilla.jss.pkix.cmc.TaggedAttribute;
import org.mozilla.jss.pkix.cmc.TaggedCertificationRequest;
import org.mozilla.jss.pkix.cmc.TaggedRequest;
import org.mozilla.jss.pkix.crmf.CertReqMsg;
import org.mozilla.jss.pkix.crmf.CertRequest;
import org.mozilla.jss.pkix.crmf.CertTemplate;
import org.mozilla.jss.pkix.crmf.PKIArchiveOptions;
import org.mozilla.jss.pkix.crmf.ProofOfPossession;
import org.mozilla.jss.pkix.primitive.AVA;
import org.mozilla.jss.pkix.primitive.AlgorithmIdentifier;
import org.mozilla.jss.pkix.primitive.Attribute;
import org.mozilla.jss.pkix.primitive.Name;
import org.mozilla.jss.pkix.primitive.SubjectPublicKeyInfo;

import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.authentication.IAuthManager;
import com.netscape.certsrv.authentication.IAuthToken;
import com.netscape.certsrv.authentication.ISharedToken;
import com.netscape.certsrv.authority.IAuthority;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.SessionContext;
import com.netscape.certsrv.ca.ICertificateAuthority;
import com.netscape.certsrv.logging.AuditEvent;
import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.profile.ECMCBadIdentityException;
import com.netscape.certsrv.profile.ECMCBadMessageCheckException;
import com.netscape.certsrv.profile.ECMCBadRequestException;
import com.netscape.certsrv.profile.ECMCPopFailedException;
import com.netscape.certsrv.profile.ECMCPopRequiredException;
import com.netscape.certsrv.profile.ECMCUnsupportedExtException;
import com.netscape.certsrv.profile.EDeferException;
import com.netscape.certsrv.profile.EProfileException;
import com.netscape.certsrv.profile.ERejectException;
import com.netscape.certsrv.profile.IEnrollProfile;
import com.netscape.certsrv.profile.IProfileContext;
import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.IRequestQueue;
import com.netscape.certsrv.request.RequestId;
import com.netscape.cmsutil.crypto.CryptoUtil;
import com.netscape.cmsutil.util.HMACDigest;

import netscape.security.pkcs.PKCS10;
import netscape.security.pkcs.PKCS10Attribute;
import netscape.security.pkcs.PKCS10Attributes;
import netscape.security.pkcs.PKCS9Attribute;
import netscape.security.util.DerInputStream;
import netscape.security.util.DerOutputStream;
import netscape.security.util.DerValue;
import netscape.security.util.ObjectIdentifier;
import netscape.security.x509.AlgorithmId;
import netscape.security.x509.CertificateAlgorithmId;
import netscape.security.x509.CertificateExtensions;
import netscape.security.x509.CertificateIssuerName;
import netscape.security.x509.CertificateSerialNumber;
import netscape.security.x509.CertificateSubjectName;
import netscape.security.x509.CertificateValidity;
import netscape.security.x509.CertificateVersion;
import netscape.security.x509.CertificateX509Key;
import netscape.security.x509.Extension;
import netscape.security.x509.Extensions;
import netscape.security.x509.PKIXExtensions;
import netscape.security.x509.SubjectKeyIdentifierExtension;
import netscape.security.x509.X500Name;
import netscape.security.x509.X509CertImpl;
import netscape.security.x509.X509CertInfo;
import netscape.security.x509.X509Key;

/**
 * This class implements a generic enrollment profile.
 *
 * @version $Revision$, $Date$
 */
public abstract class EnrollProfile extends BasicProfile
        implements IEnrollProfile {

    private PKIData mCMCData;

    public EnrollProfile() {
        super();
    }

    public abstract IAuthority getAuthority();

    public IRequestQueue getRequestQueue() {
        IAuthority authority = getAuthority();

        return authority.getRequestQueue();
    }

    public IProfileContext createContext() {
        return new ProfileContext();
    }

    /**
     * Creates request.
     */
    public IRequest[] createRequests(IProfileContext ctx, Locale locale)
            throws EProfileException {

        String method = "EnrollProfile: createRequests: ";
        CMS.debug(method + "begins");

        // determine how many requests should be created
        String cert_request_type = ctx.get(CTX_CERT_REQUEST_TYPE);
        String cert_request = ctx.get(CTX_CERT_REQUEST);
        String is_renewal = ctx.get(CTX_RENEWAL);
        Integer renewal_seq_num = 0;

        /* cert_request_type can be null for the case of CMC */
        if (cert_request_type == null) {
            CMS.debug(method + " request type is null");
        }

        int num_requests = 1; // default to 1 request

        if (cert_request_type != null && cert_request_type.startsWith("pkcs10")) {
            // catch for invalid request
            parsePKCS10(locale, cert_request);
        }
        if (cert_request_type != null && cert_request_type.startsWith("crmf")) {
            CertReqMsg msgs[] = parseCRMF(locale, cert_request);

            num_requests = msgs.length;
        }
        TaggedRequest[] cmc_msgs = null;
        if (cert_request_type != null && cert_request_type.startsWith("cmc")) {

            // donePOI true means Proof-Of-Identity is already done.
            // if the auth manager is the CMCUserSignedAuth, then
            // the new cert will eventually have the same subject as the
            // user signing cert
            // if the auth manager is the CMCAuth (agent pre-approved),
            // then no changes
            boolean donePOI = false;
            String signingUserSerial = ctx.get(IAuthManager.CRED_CMC_SIGNING_CERT);
            if (signingUserSerial != null) {
                donePOI = true;
            }
            // catch for invalid request
            cmc_msgs = parseCMC(locale, cert_request, donePOI);
            if (cmc_msgs == null) {
                CMS.debug(method + "parseCMC returns cmc_msgs null");
                return null;
            } else {
                num_requests = cmc_msgs.length;
                CMS.debug(method + "parseCMC returns cmc_msgs num_requests=" +
                        num_requests);
            }
        }

        // only 1 request for renewal
        if ((is_renewal != null) && (is_renewal.equals("true"))) {
            num_requests = 1;
            String renewal_seq_num_str = ctx.get(CTX_RENEWAL_SEQ_NUM);
            if (renewal_seq_num_str != null) {
                renewal_seq_num = Integer.parseInt(renewal_seq_num_str);
            } else {
                renewal_seq_num = 0;
            }
        }

        // populate requests with appropriate content
        IRequest result[] = new IRequest[num_requests];

        for (int i = 0; i < num_requests; i++) {
            result[i] = createEnrollmentRequest();
            if ((is_renewal != null) && (is_renewal.equals("true"))) {
                result[i].setExtData(REQUEST_SEQ_NUM, renewal_seq_num);
            } else {
                result[i].setExtData(REQUEST_SEQ_NUM, Integer.valueOf(i));
                if ((cmc_msgs != null) && (cmc_msgs[i] != null)) {
                    CMS.debug(method + "setting cmc TaggedRequest in request");
                    result[i].setExtData(
                            CTX_CERT_REQUEST,
                            ASN1Util.encode(cmc_msgs[i]));
                }
            }
            if (locale != null) {
                result[i].setExtData(REQUEST_LOCALE, locale.getLanguage());
            }

            // set requested CA
            result[i].setExtData(IRequest.AUTHORITY_ID, ctx.get(REQUEST_AUTHORITY_ID));
        }
        return result;
    }

    public abstract X500Name getIssuerName();

    public void setDefaultCertInfo(IRequest req) throws EProfileException {
        // create an empty certificate template so that
        // default plugins that store stuff
        X509CertInfo info = new X509CertInfo();

        // retrieve issuer name
        X500Name issuerName = getIssuerName();

        byte[] dummykey = new byte[] {
                48, 92, 48, 13, 6, 9, 42, -122, 72, -122, -9, 13, 1, 1, 1, 5,
                0, 3, 75, 0, 48, 72, 2, 65, 0, -65, 121, -119, -59, 105, 66,
                -122, -78, -30, -64, 63, -47, 44, -48, -104, 103, -47, -108,
                42, -38, 46, -8, 32, 49, -29, -26, -112, -29, -86, 71, 24,
                -104, 78, -31, -75, -128, 90, -92, -34, -51, -125, -13, 80, 101,
                -78, 39, -119, -38, 117, 28, 67, -19, -71, -124, -85, 105, -53,
                -103, -59, -67, -38, -83, 118, 65, 2, 3, 1, 0, 1 };
        // default values into x509 certinfo. This thing is
        // not serializable by default
        try {
            info.set(X509CertInfo.VERSION,
                    new CertificateVersion(CertificateVersion.V3));
            info.set(X509CertInfo.SERIAL_NUMBER,
                    new CertificateSerialNumber(new BigInteger("0")));
            ICertificateAuthority authority =
                    (ICertificateAuthority) getAuthority();
            if (authority.getIssuerObj() != null) {
                // this ensures the isserDN has the same encoding as the
                // subjectDN of the CA signing cert
                CMS.debug("EnrollProfile: setDefaultCertInfo: setting issuerDN using exact CA signing cert subjectDN encoding");
                info.set(X509CertInfo.ISSUER,
                        authority.getIssuerObj());
            } else {
                CMS.debug("EnrollProfile: setDefaultCertInfo: authority.getIssuerObj() is null, creating new CertificateIssuerName");
                info.set(X509CertInfo.ISSUER,
                        new CertificateIssuerName(issuerName));
            }
            info.set(X509CertInfo.KEY,
                    new CertificateX509Key(X509Key.parse(new DerValue(dummykey))));
            info.set(X509CertInfo.SUBJECT,
                    new CertificateSubjectName(new X500Name("CN=Dummy Subject Name")));
            info.set(X509CertInfo.VALIDITY,
                    new CertificateValidity(new Date(), new Date()));
            info.set(X509CertInfo.ALGORITHM_ID,
                    new CertificateAlgorithmId(AlgorithmId.get("MD5withRSA")));

            // add default extension container
            info.set(X509CertInfo.EXTENSIONS,
                    new CertificateExtensions());
        } catch (Exception e) {
            // throw exception - add key to template
            CMS.debug("EnrollProfile: Unable to create X509CertInfo: " + e);
            CMS.debug(e);
            throw new EProfileException(e);
        }
        req.setExtData(REQUEST_CERTINFO, info);
    }

    public IRequest createEnrollmentRequest()
            throws EProfileException {
        IRequest req = null;

        try {
            req = getRequestQueue().newRequest("enrollment");

            setDefaultCertInfo(req);

            // put the certificate info into request
            req.setExtData(REQUEST_EXTENSIONS,
                    new CertificateExtensions());

            CMS.debug("EnrollProfile: createEnrollmentRequest " +
                    req.getRequestId());
        } catch (EBaseException e) {
            // raise exception?
            CMS.debug("EnrollProfile: Unable to create enrollment request: " + e);
            CMS.debug(e);
        }

        return req;
    }

    public abstract void execute(IRequest request)
            throws EProfileException;

    /**
     * Perform simple policy set assignment.
     */
    public String getPolicySetId(IRequest req) {
        Integer seq = req.getExtDataInInteger(REQUEST_SEQ_NUM);
        int seq_no = seq.intValue(); // start from 0

        int count = 0;
        Enumeration<String> setIds = getProfilePolicySetIds();

        while (setIds.hasMoreElements()) {
            String setId = setIds.nextElement();

            if (count == seq_no) {
                return setId;
            }
            count++;
        }
        return null;
    }

    public String getRequestorDN(IRequest request) {
        X509CertInfo info = request.getExtDataInCertInfo(REQUEST_CERTINFO);

        try {
            CertificateSubjectName sn = (CertificateSubjectName)
                    info.get(X509CertInfo.SUBJECT);

            return sn.toString();
        } catch (Exception e) {
            CMS.debug("EnrollProfile: Unable to get requestor DN: " + e);
            CMS.debug(e);
        }
        return null;
    }

    /**
     * setPOPchallenge generates a POP challenge and sets necessary info in request
     * for composing encryptedPOP later
     *
     * @param IRequest the request
     * @author cfu
     */
    public void setPOPchallenge(IRequest req) throws EBaseException {
        String method = "EnrollProfile: setPOPchallenge: ";
        String msg = "";

        CMS.debug(method + " getting user public key in request");
        if (req == null) {
            CMS.debug(method + "method parameters cannot be null");
            throw new EBaseException(method + msg);
        }
        byte[] req_key_data = req.getExtDataInByteArray(IEnrollProfile.REQUEST_KEY);
        if (req_key_data != null) {
            CMS.debug(method + "found user public key in request");

            // generate a challenge of 64 bytes;
            Random random = new Random();
            byte[] challenge = new byte[64];
            random.nextBytes(challenge);

            ICertificateAuthority authority = (ICertificateAuthority) getAuthority();
            PublicKey issuanceProtPubKey = authority.getIssuanceProtPubKey();
            if (issuanceProtPubKey != null)
                CMS.debug(method + "issuanceProtPubKey not null");
            else {
                msg = method + "issuanceProtPubKey null";
                CMS.debug(msg);
                throw new EBaseException(method + msg);
            }

            try {
                CryptoToken token = null;
                String tokenName = CMS.getConfigStore().getString("cmc.token", CryptoUtil.INTERNAL_TOKEN_NAME);
                token = CryptoUtil.getCryptoToken(tokenName);

                byte[] iv = CryptoUtil.getNonceData(EncryptionAlgorithm.AES_128_CBC.getIVLength());
                IVParameterSpec ivps = new IVParameterSpec(iv);

                PublicKey userPubKey = X509Key.parsePublicKey(new DerValue(req_key_data));
                if (userPubKey == null) {
                    msg = method + "userPubKey null after X509Key.parsePublicKey";
                    CMS.debug(msg);
                    throw new EBaseException(msg);
                }

                SymmetricKey symKey = CryptoUtil.generateKey(
                        token,
                        KeyGenAlgorithm.AES,
                        128,
                        null,
                        true);

                byte[] pop_encryptedData = CryptoUtil.encryptUsingSymmetricKey(
                        token,
                        symKey,
                        challenge,
                        EncryptionAlgorithm.AES_128_CBC,
                        ivps);

                if (pop_encryptedData == null) {
                    msg = method + "pop_encryptedData null";
                    CMS.debug(msg);
                    throw new EBaseException(msg);
                }

                byte[] pop_sysPubEncryptedSession =  CryptoUtil.wrapUsingPublicKey(
                        token,
                        issuanceProtPubKey,
                        symKey,
                        KeyWrapAlgorithm.RSA);

                if (pop_sysPubEncryptedSession == null) {
                    msg = method + "pop_sysPubEncryptedSession null";
                    CMS.debug(msg);
                    throw new EBaseException(msg);
                }


                byte[] pop_userPubEncryptedSession = CryptoUtil.wrapUsingPublicKey(
                        token,
                        userPubKey,
                        symKey,
                        KeyWrapAlgorithm.RSA);

                if (pop_userPubEncryptedSession == null) {
                    msg = method + "pop_userPubEncryptedSession null";
                    CMS.debug(msg);
                    throw new EBaseException(msg);
                }
                CMS.debug(method + "POP challenge fields generated successfully...setting request extData");

                req.setExtData("pop_encryptedData", pop_encryptedData);

                req.setExtData("pop_sysPubEncryptedSession", pop_sysPubEncryptedSession);

                req.setExtData("pop_userPubEncryptedSession", pop_userPubEncryptedSession);

                req.setExtData("pop_encryptedDataIV", iv);

                // now compute and set witness
                CMS.debug(method + "now compute and set witness");
                String hashName = CryptoUtil.getDefaultHashAlgName();
                CMS.debug(method + "hashName is " + hashName);
                MessageDigest hash = MessageDigest.getInstance(hashName);
                byte[] witness = hash.digest(challenge);
                req.setExtData("pop_witness", witness);

            } catch (Exception e) {
                CMS.debug(method + e);
                throw new EBaseException(e.toString());
            }

        } else {
            CMS.debug(method + " public key not found in request");
            throw new EBaseException(method + " public key not found in request");
        }
    }

    /**
     * This method is called after the user submits the
     * request from the end-entity page.
     */
    public void submit(IAuthToken token, IRequest request)
            throws EDeferException, EProfileException {
        // Request Submission Logic:
        //
        // if (Authentication Failed) {
        //   return Error
        // } else {
        //   if (No Auth Token) {
        //     queue request
        //   } else {
        //     process request
        //   }
        // }
        String method = "EnrollProfile: submit: ";

        IRequestQueue queue = getRequestQueue();
        String msg = "";
        CMS.debug(method + "begins");

        boolean popChallengeRequired =
                request.getExtDataInBoolean("cmc_POPchallengeRequired", false);
        CMS.debug(method + "popChallengeRequired =" + popChallengeRequired);

        // this profile queues request that is authenticated
        // by NoAuth
        try {
            queue.updateRequest(request);
        } catch (EBaseException e) {
            // save request to disk
            CMS.debug(method + " Unable to update request: " + e);
            CMS.debug(e);
        }

        if (token == null){
            CMS.debug(method + " auth token is null; agent manual approval required;");
            CMS.debug(method + " validating request");
            validate(request);
            try {
                queue.updateRequest(request);
            } catch (EBaseException e) {
                msg = method + " Unable to update request after validation: " + e;
                CMS.debug(msg);
                throw new EProfileException(msg);
            }
            throw new EDeferException("defer request");
        } else if (popChallengeRequired) {
            // this is encryptedPOP case; defer to require decryptedPOP
            CMS.debug(method + " popChallengeRequired, defer to enforce decryptedPOP");
            validate(request);

            CMS.debug(method + " about to call setPOPchallenge");
            try {
                setPOPchallenge(request);
                queue.updateRequest(request);
            } catch (EBaseException e) {
                msg = method + e;
                CMS.debug(msg);
                throw new EProfileException(msg);
            }

            throw new ECMCPopRequiredException(" Return  with DecryptedPOP to complete");

        } else {
            // this profile executes request that is authenticated
            // by non NoAuth
            CMS.debug(method + " auth token is not null");
            validate(request);
            execute(request);
        }
    }

    /**
     * getPKIDataFromCMCblob
     *
     * @param certReqBlob cmc b64 encoded blob
     * @return PKIData
     */
    public PKIData getPKIDataFromCMCblob(Locale locale, String certReqBlob)
            throws EProfileException {

        String method = "EnrollProfile: getPKIDataFromCMCblob: ";
        String msg = ""; // for capturing debug and throw info

        /* cert request must not be null */
        if (certReqBlob == null) {
            msg = method + "certReqBlob null";
            CMS.debug(msg);
            throw new EProfileException(
                    CMS.getUserMessage(locale, "CMS_PROFILE_INVALID_REQUEST") +
                            msg);
        }
        //CMS.debug(method + " Start: " + certReqBlob);
        CMS.debug(method + "starts");

        String creq = normalizeCertReq(certReqBlob);
        try {
            byte data[] = CMS.AtoB(creq);
            ByteArrayInputStream cmcBlobIn = new ByteArrayInputStream(data);
            PKIData pkiData = null;

            org.mozilla.jss.pkix.cms.ContentInfo cmcReq = (org.mozilla.jss.pkix.cms.ContentInfo) org.mozilla.jss.pkix.cms.ContentInfo
                    .getTemplate().decode(cmcBlobIn);
            OCTET_STRING content = null;
            if (cmcReq.getContentType().equals(
                    org.mozilla.jss.pkix.cms.ContentInfo.SIGNED_DATA)) {
                CMS.debug(method + "cmc request content is signed data");
                org.mozilla.jss.pkix.cms.SignedData cmcFullReq = (org.mozilla.jss.pkix.cms.SignedData) cmcReq
                        .getInterpretedContent();
                org.mozilla.jss.pkix.cms.EncapsulatedContentInfo ci = cmcFullReq.getContentInfo();
                content = ci.getContent();

            } else { // for unsigned revocation requests (using shared secret)
                CMS.debug(method + "cmc request content is unsigned data");
                content = (OCTET_STRING) cmcReq.getInterpretedContent();
            }
            ByteArrayInputStream s = new ByteArrayInputStream(content.toByteArray());
            pkiData = (PKIData) (new PKIData.Template()).decode(s);

            mCMCData = pkiData;
            //PKIData pkiData = (PKIData)
            //    (new PKIData.Template()).decode(cmcBlobIn);

            return pkiData;
        } catch (Exception e) {
            CMS.debug(method + e);
            throw new EProfileException(
                    CMS.getUserMessage(locale, "CMS_PROFILE_INVALID_REQUEST"), e);
        }
    }

    public static CertificateSubjectName getCMCSigningCertSNfromCertSerial(
            String certSerial) throws Exception {
        X509CertImpl userCert = getCMCSigningCertFromCertSerial(certSerial);

        if (userCert != null) {
            return userCert.getSubjectObj();
        } else {
            return null;
        }
    }

    /**
     * getCMCSigningCertFromCertSerial is to be used when authentication
     * was done with CMCUserSignedAuth where the resulting
     * authToken contains
     * IAuthManager.CRED_CMC_SIGNING_CERT, serial number
     * This method takes the serial number
     * and finds the cert from the CA's certdb
     */
    public static X509CertImpl getCMCSigningCertFromCertSerial(
            String certSerial) throws Exception {
        String method = "EnrollProfile: getCMCSigningCertFromCertSerial: ";
        String msg = "";

        X509CertImpl userCert = null;

        if (certSerial == null || certSerial.equals("")) {
            msg = method + "certSerial empty";
            CMS.debug(msg);
            throw new Exception(msg);
        }

        // for CMCUserSignedAuth, the signing user is the subject of
        // the new cert
        ICertificateAuthority authority = (ICertificateAuthority) CMS.getSubsystem(CMS.SUBSYSTEM_CA);
        try {
            BigInteger serialNo = new BigInteger(certSerial);
            userCert = authority.getCertificateRepository().getX509Certificate(serialNo);
        } catch (NumberFormatException e) {
            msg = method + e;
            CMS.debug(msg);
            throw new Exception(msg);
        } catch (EBaseException e) {
            msg = method + e + "; signing user cert not found: serial=" + certSerial;
            CMS.debug(msg);
            throw new Exception(msg);
        }

        if (userCert != null) {
            msg = method + "signing user cert found; serial=" + certSerial;
            CMS.debug(msg);
        } else {
            msg = method + "signing user cert not found: serial=" + certSerial;
            CMS.debug(msg);
            throw new Exception(msg);
        }

        return userCert;
    }

    /*
     * parseCMC
     * @throws EProfileException in case of error
     *   note: returing "null" doesn't mean failure
     */
    public TaggedRequest[] parseCMC(Locale locale, String certreq)
            throws EProfileException {
        return parseCMC(locale, certreq, false);
    }
    public TaggedRequest[] parseCMC(Locale locale, String certreq, boolean donePOI)
            throws EProfileException {

        String method = "EnrollProfile: parseCMC: ";
        String msg = ""; // for capturing debug and throw info
        //CMS.debug(method + " Start parseCMC(): " + certreq);
        CMS.debug(method + "starts");
        String auditMessage = "";
        String auditSubjectID = auditSubjectID();

        /* cert request must not be null */
        if (certreq == null) {
            msg = method + "certreq null";
            CMS.debug(msg);
            throw new EProfileException(
                    CMS.getUserMessage(locale, "CMS_PROFILE_INVALID_REQUEST") +
                            msg);
        }

        TaggedRequest msgs[] = null;
        try {
            PKIData pkiData = getPKIDataFromCMCblob(locale, certreq);
            SEQUENCE controlSeq = pkiData.getControlSequence();
            int numcontrols = controlSeq.size();
            SEQUENCE reqSeq = pkiData.getReqSequence();
            byte randomSeed[] = null;
            UTF8String ident_s = null;
            SessionContext context = SessionContext.getContext();

            boolean id_cmc_revokeRequest = false;
            if (!context.containsKey("numOfControls")) {
                CMS.debug(method + "numcontrols="+ numcontrols);
                if (numcontrols > 0) {
                    context.put("numOfControls", Integer.valueOf(numcontrols));
                    TaggedAttribute[] attributes = new TaggedAttribute[numcontrols];
                    boolean id_cmc_decryptedPOP = false;
                    SET decPopVals = null;
                    boolean id_cmc_regInfo = false;
                    SET reqIdVals = null;

                    boolean id_cmc_identification = false;
                    SET ident = null;

                    boolean id_cmc_identityProofV2 = false;
                    boolean id_cmc_identityProof = false;
                    TaggedAttribute attr = null;

                    boolean id_cmc_idPOPLinkRandom = false;
                    SET vals = null;

                    /**
                     * pre-process all controls --
                     * the postponed processing is so that we can capture
                     * the identification, if included
                     */
                    CMS.debug(method + "about to pre-process controls");
                    for (int i = 0; i < numcontrols; i++) {
                        attributes[i] = (TaggedAttribute) controlSeq.elementAt(i);
                        OBJECT_IDENTIFIER oid = attributes[i].getType();
                        if (oid.equals(OBJECT_IDENTIFIER.id_cmc_revokeRequest)) {
                            id_cmc_revokeRequest = true;
                            // put in context for processing in
                            // CMCOutputTemplate.java later
                            context.put(OBJECT_IDENTIFIER.id_cmc_revokeRequest,
                                    attributes[i]);
                        } else if (oid.equals(OBJECT_IDENTIFIER.id_cmc_decryptedPOP)) {
                            CMS.debug(method + " id_cmc_decryptedPOP found");
                            id_cmc_decryptedPOP = true;
                            decPopVals = attributes[i].getValues();
                        } else if (oid.equals(OBJECT_IDENTIFIER.id_cmc_regInfo)) {
                            CMS.debug(method + "id_cmc_regInfo found");
                            id_cmc_regInfo = true;
                            reqIdVals = attributes[i].getValues();
                        } else if (oid.equals(OBJECT_IDENTIFIER.id_cmc_identification)) {
                            CMS.debug(method + " id_cmc_identification found");
                            id_cmc_identification = true;
                            ident = attributes[i].getValues();
                        } else if (oid.equals(OBJECT_IDENTIFIER.id_cmc_identityProofV2)) {
                            CMS.debug(method + " id_cmc_identityProofV2 found");
                            id_cmc_identityProofV2 = true;
                            attr = attributes[i];
                        } else if (oid.equals(OBJECT_IDENTIFIER.id_cmc_identityProof)) {
                            CMS.debug(method + " id_cmc_identityProof found");
                            id_cmc_identityProof = true;
                            attr = attributes[i];
                        } else if (oid.equals(OBJECT_IDENTIFIER.id_cmc_idPOPLinkRandom)) {
                            CMS.debug(method + "id_cmc_idPOPLinkRandom found");
                            id_cmc_idPOPLinkRandom = true;
                            vals = attributes[i].getValues();
                        } else {
                            CMS.debug(method + "unknown control found");
                            context.put(attributes[i].getType(), attributes[i]);
                        }
                    } //for

                    /**
                     * now do the actual control processing
                     */
                    CMS.debug(method + "processing controls...");

                    if (id_cmc_revokeRequest) {
                        CMS.debug(method + "revocation control");
                    }

                    if (id_cmc_identification) {
                        if (ident == null) {
                            msg = "id_cmc_identification contains null attribute value";
                            CMS.debug(method + msg);
                            SEQUENCE bpids = getRequestBpids(reqSeq);
                            context.put("identification", bpids);

                            msg = " id_cmc_identification attribute value not found in";
                            CMS.debug(method + msg);

                            throw new ECMCBadRequestException(
                                    CMS.getUserMessage(locale, "CMS_PROFILE_INVALID_REQUEST") + ":" +
                                            msg);
                        } else {
                            ident_s = (UTF8String) (ASN1Util.decode(UTF8String.getTemplate(),
                                    ASN1Util.encode(ident.elementAt(0))));
                        }
                        if (ident == null && ident_s == null) {
                            msg = " id_cmc_identification contains invalid content";
                            CMS.debug(method + msg);
                            SEQUENCE bpids = getRequestBpids(reqSeq);
                            context.put("identification", bpids);

                            CMS.debug(method + msg);

                            throw new ECMCBadRequestException(
                                    CMS.getUserMessage(locale, "CMS_PROFILE_INVALID_REQUEST") + ":" +
                                            msg);

                        }
                    }

                    // checking Proof Of Identity, if not pre-signed

                    if (donePOI || id_cmc_revokeRequest) {
                        // for logging purposes
                        if (id_cmc_identityProofV2) {
                            CMS.debug(method
                                    + "pre-signed CMC request, but id_cmc_identityProofV2 found...ignore; no further proof of identification check");
                        } else if (id_cmc_identityProof) {
                            CMS.debug(method
                                    + "pre-signed CMC request, but id_cmc_identityProof found...ignore; no further proof of identification check");
                        } else {
                            CMS.debug(method + "pre-signed CMC request; no further proof of identification check");
                        }
                    } else if (id_cmc_identityProofV2 && (attr != null)) {
                        // either V2 or not V2; can't be both
                        CMS.debug(method +
                                "not pre-signed CMC request; calling verifyIdentityProofV2;");
                        if (!id_cmc_identification || ident_s == null) {
                            SEQUENCE bpids = getRequestBpids(reqSeq);
                            context.put("identification", bpids);
                            context.put("identityProofV2", bpids);
                            msg = "id_cmc_identityProofV2 missing id_cmc_identification";
                            CMS.debug(method + msg);
                            auditMessage = CMS.getLogMessage(
                                    AuditEvent.CMC_PROOF_OF_IDENTIFICATION,
                                    auditSubjectID,
                                    ILogger.FAILURE,
                                    method + msg);
                            audit(auditMessage);

                            throw new ECMCBadIdentityException(
                                    CMS.getUserMessage(locale, "CMS_PROFILE_INVALID_REQUEST") + ":" +
                                            msg);
                        }

                        boolean valid = verifyIdentityProofV2(context, attr, ident_s,
                                reqSeq);
                        if (!valid) {
                            SEQUENCE bpids = getRequestBpids(reqSeq);
                            context.put("identityProofV2", bpids);

                            msg = " after verifyIdentityProofV2";
                            CMS.debug(method + msg);
                            throw new ECMCBadIdentityException(CMS.getUserMessage(locale,
                                    "CMS_POI_VERIFICATION_ERROR") + msg);
                        } else {
                            CMS.debug(method + "passed verifyIdentityProofV2; Proof of Identity successful;");
                        }
                    } else if (id_cmc_identityProof && (attr != null)) {
                        CMS.debug(method + "not pre-signed CMC request; calling verifyIdentityProof;");
                        boolean valid = verifyIdentityProof(attr,
                                reqSeq);
                        if (!valid) {
                            SEQUENCE bpids = getRequestBpids(reqSeq);
                            context.put("identityProof", bpids);

                            msg = " after verifyIdentityProof";
                            CMS.debug(method + msg);
                            throw new ECMCBadIdentityException(CMS.getUserMessage(locale,
                                    "CMS_POI_VERIFICATION_ERROR") + msg);
                        } else {
                            CMS.debug(method + "passed verifyIdentityProof; Proof of Identity successful;");
                            // in case it was set
                            auditSubjectID = auditSubjectID();
                        }
                    } else {
                        msg = "not pre-signed CMC request; missing Proof of Identification control";
                        CMS.debug(method + msg);
                        auditMessage = CMS.getLogMessage(
                                AuditEvent.CMC_PROOF_OF_IDENTIFICATION,
                                auditSubjectID,
                                ILogger.FAILURE,
                                method + msg);
                        audit(auditMessage);
                        throw new ECMCBadRequestException(CMS.getUserMessage(locale,
                                "CMS_POI_VERIFICATION_ERROR") + ":" + msg);
                    }

                    if (id_cmc_decryptedPOP) {
                        if (decPopVals != null) {
                            if (!id_cmc_regInfo) {
                                msg = "id_cmc_decryptedPOP must be accompanied by id_cmc_regInfo for request id per server/client agreement";
                                CMS.debug(method + msg);
                                auditMessage = CMS.getLogMessage(
                                        AuditEvent.PROOF_OF_POSSESSION,
                                        auditSubjectID,
                                        ILogger.FAILURE,
                                        method + msg);
                                audit(auditMessage);

                                SEQUENCE bpids = getRequestBpids(reqSeq);
                                context.put("decryptedPOP", bpids);
                                throw new ECMCPopFailedException(CMS.getUserMessage(locale,
                                        "CMS_POP_VERIFICATION_ERROR") + ":" + msg);
                            }

                            OCTET_STRING reqIdOS =
                                    (OCTET_STRING) (ASN1Util.decode(OCTET_STRING.getTemplate(),
                                    ASN1Util.encode(reqIdVals.elementAt(0))));

                            DecryptedPOP decPop = (DecryptedPOP) (ASN1Util.decode(DecryptedPOP.getTemplate(),
                                    ASN1Util.encode(decPopVals.elementAt(0))));
                            CMS.debug(method + "DecryptedPOP encoded");

                            BigInteger reqId = verifyDecryptedPOP(locale, decPop, reqIdOS);
                            if (reqId != null) {
                                context.put("cmcDecryptedPopReqId", reqId);
                            } else {
                                msg = "DecryptedPOP failed to verify";
                                CMS.debug(method + msg);
                                auditMessage = CMS.getLogMessage(
                                        AuditEvent.PROOF_OF_POSSESSION,
                                        auditSubjectID,
                                        ILogger.FAILURE,
                                        method + msg);
                                audit(auditMessage);

                                SEQUENCE bpids = getRequestBpids(reqSeq);
                                context.put("decryptedPOP", bpids);
                                throw new ECMCPopFailedException(CMS.getUserMessage(locale,
                                        "CMS_POP_VERIFICATION_ERROR") + ":" + msg);
                            }
                        } else { //decPopVals == null
                            msg = "id_cmc_decryptedPOP contains invalid DecryptedPOP";
                            CMS.debug(method + msg);
                            auditMessage = CMS.getLogMessage(
                                    AuditEvent.PROOF_OF_POSSESSION,
                                    auditSubjectID,
                                    ILogger.FAILURE,
                                    method + msg);
                            audit(auditMessage);

                            SEQUENCE bpids = getRequestBpids(reqSeq);
                            context.put("decryptedPOP", bpids);
                            throw new ECMCPopFailedException(CMS.getUserMessage(locale,
                                    "CMS_POP_VERIFICATION_ERROR") + ":" + msg);
                        }

                        // decryptedPOP is expected to return null;
                        // POPLinkWitnessV2 would have to be checked in
                        // round one, if required
                        return null;
                    }

                    if (id_cmc_idPOPLinkRandom && vals != null) {
                        OCTET_STRING ostr =
                                (OCTET_STRING) (ASN1Util.decode(OCTET_STRING.getTemplate(),
                                ASN1Util.encode(vals.elementAt(0))));
                        randomSeed = ostr.toByteArray();
                        CMS.debug(method + "got randomSeed");
                    }
                } // numcontrols > 0
            }

            SEQUENCE otherMsgSeq = pkiData.getOtherMsgSequence();
            int numOtherMsgs = otherMsgSeq.size();
            if (!context.containsKey("numOfOtherMsgs")) {
                CMS.debug(method + "found numOfOtherMsgs: " + numOtherMsgs);
                context.put("numOfOtherMsgs", Integer.valueOf(numOtherMsgs));
                for (int i = 0; i < numOtherMsgs; i++) {
                    OtherMsg omsg = (OtherMsg) (ASN1Util.decode(OtherMsg.getTemplate(),
                            ASN1Util.encode(otherMsgSeq.elementAt(i))));
                    context.put("otherMsg" + i, omsg);
                }
            }

            /**
             * in CS.cfg, cmc.popLinkWitnessRequired=true
             * will enforce popLinkWitness (or V2);
             */
            boolean popLinkWitnessRequired = false;
            try {
                String configName = "cmc.popLinkWitnessRequired";
                CMS.debug(method + "getting :" + configName);
                popLinkWitnessRequired = CMS.getConfigStore().getBoolean(configName, false);
                if (popLinkWitnessRequired) {
                    CMS.debug(method + "popLinkWitness(V2) required");
                } else {
                    CMS.debug(method + "popLinkWitness(V2) not required");
                }
            } catch (Exception e) {
                // unlikely to get here
                msg = " Failed to retrieve cmc.popLinkWitnessRequired";
                CMS.debug(method + msg);
                throw new EProfileException( msg);
            }

            int nummsgs = reqSeq.size();
            if (nummsgs > 0) {
                CMS.debug(method + "nummsgs =" + nummsgs);
                msgs = new TaggedRequest[reqSeq.size()];
                SEQUENCE bpids = new SEQUENCE();

                boolean valid = true;
                for (int i = 0; i < nummsgs; i++) {
                    msgs[i] = (TaggedRequest) reqSeq.elementAt(i);
                    if (id_cmc_revokeRequest)
                        continue;
                    if (popLinkWitnessRequired &&
                            !context.containsKey("POPLinkWitnessV2") &&
                            !context.containsKey("POPLinkWitness")) {
                        CMS.debug(method + "popLinkWitness(V2) required");
                        if (randomSeed == null || ident_s == null) {
                            msg = "missing needed randomSeed or identification for popLinkWitness(V2)";
                            CMS.debug(method + msg);
                            auditMessage = CMS.getLogMessage(
                                    AuditEvent.CMC_ID_POP_LINK_WITNESS,
                                    auditSubjectID,
                                    ILogger.FAILURE,
                                    method + msg);
                            audit(auditMessage);

                            context.put("POPLinkWitnessV2", bpids);
                            throw new ECMCBadRequestException(CMS.getUserMessage(locale,
                                    "CMS_POP_LINK_WITNESS_VERIFICATION_ERROR") + ":" + msg);
                        }

                        // verifyPOPLinkWitness() will determine if this is
                        // POPLinkWitnessV2 or POPLinkWitness
                        // If failure, context is set in verifyPOPLinkWitness
                        valid = verifyPOPLinkWitness(ident_s, randomSeed, msgs[i], bpids, context);
                        if (valid == false) {
                            if (context.containsKey("POPLinkWitnessV2"))
                                msg = " in POPLinkWitnessV2";
                            else if (context.containsKey("POPLinkWitness"))
                                msg = " in POPLinkWitness";
                            else
                                msg = " failure from verifyPOPLinkWitness";

                            msg = msg + ": ident_s=" + ident_s;
                            CMS.debug(method + msg);
                            auditMessage = CMS.getLogMessage(
                                    AuditEvent.CMC_ID_POP_LINK_WITNESS,
                                    auditSubjectID,
                                    ILogger.FAILURE,
                                    method + msg);
                            audit(auditMessage);
                            throw new ECMCBadRequestException(CMS.getUserMessage(locale,
                                    "CMS_POP_LINK_WITNESS_VERIFICATION_ERROR") + ":" + msg);
                        } else {
                            msg = ": ident_s=" + ident_s;
                            auditMessage = CMS.getLogMessage(
                                    AuditEvent.CMC_ID_POP_LINK_WITNESS,
                                    auditSubjectID,
                                    ILogger.SUCCESS,
                                    method + msg);
                            audit(auditMessage);
                        }
                    }
                } //for
            } else {
                CMS.debug(method + "nummsgs 0; returning...");
                return null;
            }

            CMS.debug(method + "ends");
            return msgs;
        } catch (ECMCBadMessageCheckException e) {
            throw new ECMCBadMessageCheckException(e);
        } catch (ECMCBadIdentityException e) {
            throw new ECMCBadIdentityException(e);
        } catch (ECMCPopFailedException e) {
            throw new ECMCPopFailedException(e);
        } catch (ECMCBadRequestException e) {
            throw new ECMCBadRequestException(e);
        } catch (EProfileException e) {
            throw new EProfileException(e);
        } catch (Exception e) {
            CMS.debug(method + e);
            throw new EProfileException(
                    CMS.getUserMessage(locale, "CMS_PROFILE_INVALID_REQUEST"), e);
        }
    }

    /**
     * verifyDecryptedPOP verifies the POP challenge provided in
     * DecryptedPOP and returns the matching requestID
     *
     * @author cfu
     */
    private BigInteger verifyDecryptedPOP(Locale locale,
            DecryptedPOP decPop,
            OCTET_STRING reqIdOS)
            throws EProfileException, ECMCPopFailedException {
        String method = "EnrollProfile: verifyDecryptedPOP: ";
        CMS.debug(method + "begins");
        String msg = "";

        if (decPop == null || reqIdOS == null) {
            CMS.debug(method + "method parameters cannot be null");
            return null;
        }

        byte[] reqIdBA = reqIdOS.toByteArray();
        BigInteger reqIdBI = new BigInteger(reqIdBA);

        OCTET_STRING witness_os = decPop.getWitness();

        IRequestQueue reqQueue = getRequestQueue();
        IRequest req = null;
        try {
            req = reqQueue.findRequest(new RequestId(reqIdBI));
        } catch (Exception e) {
            msg = method + "after findRequest: " + e;
            CMS.debug(msg);
            return null;
        }

        // now verify the POP witness
        byte[] pop_encryptedData = req.getExtDataInByteArray("pop_encryptedData");
        if (pop_encryptedData == null) {
            msg = method +
                    "pop_encryptedData not found in request:" +
                    reqIdBI.toString();
            CMS.debug(msg);
            return null;
        }

        byte[] pop_sysPubEncryptedSession = req.getExtDataInByteArray("pop_sysPubEncryptedSession");
        if (pop_sysPubEncryptedSession == null) {
            msg = method +
                    "pop_sysPubEncryptedSession not found in request:" +
                    reqIdBI.toString();
            CMS.debug(msg);
            return null;
        }

        byte[] cmc_msg = req.getExtDataInByteArray(IEnrollProfile.CTX_CERT_REQUEST);
        if (cmc_msg == null) {
            msg = method +
                    "cmc_msg not found in request:" +
                    reqIdBI.toString();
            CMS.debug(msg);
            return null;
        }

        ICertificateAuthority authority = (ICertificateAuthority) getAuthority();
        PrivateKey issuanceProtPrivKey = authority.getIssuanceProtPrivKey();
        if (issuanceProtPrivKey != null)
            CMS.debug(method + "issuanceProtPrivKey not null");
        else {
            msg = method + "issuanceProtPrivKey null";
            CMS.debug(msg);
            return null;
        }

        try {
            CryptoToken token = null;
            String tokenName = CMS.getConfigStore().getString("cmc.token", CryptoUtil.INTERNAL_TOKEN_NAME);
            token = CryptoUtil.getKeyStorageToken(tokenName);

            SymmetricKey symKey = CryptoUtil.unwrap(
                    token,
                    SymmetricKey.AES,
                    128,
                    SymmetricKey.Usage.DECRYPT,
                    issuanceProtPrivKey,
                    pop_sysPubEncryptedSession,
                    KeyWrapAlgorithm.RSA);

            if (symKey == null) {
                msg = "symKey null after CryptoUtil.unwrap returned";
                CMS.debug(msg);
                return null;
            }

            byte[] iv = req.getExtDataInByteArray("pop_encryptedDataIV");
            IVParameterSpec ivps = new IVParameterSpec(iv);

            byte[] challenge_b = CryptoUtil.decryptUsingSymmetricKey(
                    token,
                    ivps,
                    pop_encryptedData,
                    symKey,
                    EncryptionAlgorithm.AES_128_CBC);

            if (challenge_b == null) {
                msg = method + "challenge_b null after decryptUsingSymmetricKey returned";
                CMS.debug(msg);
                return null;
            }

            MessageDigest digest = MessageDigest.getInstance(CryptoUtil.getDefaultHashAlgName());
            if (digest == null) {
                msg = method + "digest null after decryptUsingSymmetricKey returned";
                CMS.debug(msg);
                return null;
            }
            HMACDigest hmacDigest = new HMACDigest(digest, challenge_b);
            hmacDigest.update(cmc_msg);
            byte[] proofValue = hmacDigest.digest();
            if (proofValue == null) {
                msg = method + "proofValue null after hmacDigest.digest returned";
                CMS.debug(msg);
                return null;
            }
            boolean witnessChecked = Arrays.equals(proofValue, witness_os.toByteArray());
            if (!witnessChecked) {
                msg = method + "POP challenge witness verification failure";
                CMS.debug(msg);
                return null;
            }
        } catch (Exception e) {
            msg = e.toString();
            CMS.debug(method + msg);
            throw new EProfileException(
                    CMS.getUserMessage(locale, "CMS_PROFILE_INVALID_REQUEST") +
                            e);
        }

        CMS.debug(method + "POP challenge verified!");
        req.setExtData("cmc_POPchallengeRequired", "false");

        CMS.debug(method + "cmc_POPchallengeRequired set back to false");
        CMS.debug(method + "ends");

        return reqIdBI;
    }

    /**
     * getPopLinkWitnessV2control
     *
     * @author cfu
     */
    protected PopLinkWitnessV2 getPopLinkWitnessV2control(ASN1Value value) {
        String method = "EnrollProfile: getPopLinkWitnessV2control: ";

        ByteArrayInputStream bis = new ByteArrayInputStream(
                ASN1Util.encode(value));
        PopLinkWitnessV2 popLinkWitnessV2 = null;

        try {
            popLinkWitnessV2 = (PopLinkWitnessV2) (new PopLinkWitnessV2.Template()).decode(bis);
        } catch (Exception e) {
            CMS.debug(method + e);
        }
        return popLinkWitnessV2;
    }

    /**
     * verifyPopLinkWitnessV2
     *
     * @author cfu
     */
    protected boolean verifyPopLinkWitnessV2(
            PopLinkWitnessV2 popLinkWitnessV2,
            byte[] randomSeed,
            String sharedSecret,
            String ident_string) {
        String method = "EnrollProfile: verifyPopLinkWitnessV2: ";

        if ((popLinkWitnessV2 == null) ||
                (randomSeed == null) ||
                (sharedSecret == null)) {
            CMS.debug(method + " method parameters cannot be null");
            return false;
        }
        AlgorithmIdentifier keyGenAlg = popLinkWitnessV2.getKeyGenAlgorithm();
        AlgorithmIdentifier macAlg = popLinkWitnessV2.getMacAlgorithm();
        OCTET_STRING witness = popLinkWitnessV2.getWitness();
        if (keyGenAlg == null) {
            CMS.debug(method + " keyGenAlg reurned by popLinkWitnessV2.getWitness is null");
            return false;
        }
        if (macAlg == null) {
            CMS.debug(method + " macAlg reurned by popLinkWitnessV2.getWitness is null");
            return false;
        }
        if (witness == null) {
            CMS.debug(method + " witness reurned by popLinkWitnessV2.getWitness is null");
            return false;
        }

        try {
            DigestAlgorithm keyGenAlgID = DigestAlgorithm.fromOID(keyGenAlg.getOID());
            MessageDigest keyGenMDAlg = MessageDigest.getInstance(keyGenAlgID.toString());

            HMACAlgorithm macAlgID = HMACAlgorithm.fromOID(macAlg.getOID());
            MessageDigest macMDAlg = MessageDigest
                    .getInstance(CryptoUtil.getHMACtoMessageDigestName(macAlgID.toString()));

            byte[] witness_bytes = witness.toByteArray();
            return verifyDigest(
                    (ident_string != null) ? (sharedSecret + ident_string).getBytes() : sharedSecret.getBytes(),
                    randomSeed,
                    witness_bytes,
                    keyGenMDAlg, macMDAlg);
        } catch (NoSuchAlgorithmException e) {
            CMS.debug(method + e);
            return false;
        } catch (Exception e) {
            CMS.debug(method + e);
            return false;
        }
    }

    /*
     * verifyPOPLinkWitness now handles POPLinkWitnessV2;
     */
    private boolean verifyPOPLinkWitness(
            UTF8String ident, byte[] randomSeed, TaggedRequest req,
            SEQUENCE bpids, SessionContext context) {
        String method = "EnrollProfile: verifyPOPLinkWitness: ";
        CMS.debug(method + "begins.");

        String ident_string = null;
        if (ident != null) {
            ident_string = ident.toString();
        }

        boolean sharedSecretFound = true;
        String configName = "cmc.sharedSecret.class";
        String sharedSecret = null;
        ISharedToken tokenClass = CMS.getSharedTokenClass(configName);
        if (tokenClass == null) {
            CMS.debug(method + " Failed to retrieve shared secret plugin class");
            sharedSecretFound = false;
        } else {
            if (ident_string != null) {
                sharedSecret = tokenClass.getSharedToken(ident_string);
            } else {
                sharedSecret = tokenClass.getSharedToken(mCMCData);
            }
            if (sharedSecret == null)
                sharedSecretFound = false;
        }

        INTEGER reqId = null;
        byte[] bv = null;

        if (req.getType().equals(TaggedRequest.PKCS10)) {
            String methodPos = method + "PKCS10: ";
            CMS.debug(methodPos + "begins");

            TaggedCertificationRequest tcr = req.getTcr();
            if (!sharedSecretFound) {
                bpids.addElement(tcr.getBodyPartID());
                context.put("POPLinkWitness", bpids);
                return false;
            } else {
                CertificationRequest creq = tcr.getCertificationRequest();
                CertificationRequestInfo cinfo = creq.getInfo();
                SET attrs = cinfo.getAttributes();
                for (int j = 0; j < attrs.size(); j++) {
                    Attribute pkcs10Attr = (Attribute) attrs.elementAt(j);
                    if (pkcs10Attr.getType().equals(OBJECT_IDENTIFIER.id_cmc_popLinkWitnessV2)) {
                        CMS.debug(methodPos + "found id_cmc_popLinkWitnessV2");
                        if (ident_string == null) {
                            bpids.addElement(reqId);
                            context.put("identification", bpids);
                            context.put("POPLinkWitnessV2", bpids);
                            String msg = "id_cmc_popLinkWitnessV2 must be accompanied by id_cmc_identification in this server";
                            CMS.debug(methodPos + msg);
                            return false;
                        }

                        SET witnessVal = pkcs10Attr.getValues();
                        if (witnessVal.size() > 0) {
                            try {
                                PopLinkWitnessV2 popLinkWitnessV2 = getPopLinkWitnessV2control(witnessVal.elementAt(0));
                                boolean valid = verifyPopLinkWitnessV2(popLinkWitnessV2,
                                        randomSeed,
                                        sharedSecret,
                                        ident_string);
                                if (!valid) {
                                    bpids.addElement(reqId);
                                    context.put("POPLinkWitnessV2", bpids);
                                    return valid;
                                }
                                return true;
                            } catch (Exception ex) {
                                CMS.debug(methodPos + ex);
                                return false;
                            }
                        }
                    } else if (pkcs10Attr.getType().equals(OBJECT_IDENTIFIER.id_cmc_idPOPLinkWitness)) {
                        SET witnessVal = pkcs10Attr.getValues();
                        if (witnessVal.size() > 0) {
                            try {
                                OCTET_STRING str = (OCTET_STRING) (ASN1Util.decode(OCTET_STRING.getTemplate(),
                                        ASN1Util.encode(witnessVal.elementAt(0))));
                                bv = str.toByteArray();
                                return verifyDigest(sharedSecret.getBytes(),
                                        randomSeed, bv);
                            } catch (InvalidBERException ex) {
                                return false;
                            }
                        }
                    }
                }

                return false;
            }
        } else if (req.getType().equals(TaggedRequest.CRMF)) {
            String methodPos = method + "CRMF: ";
            CMS.debug(methodPos + "begins");

            CertReqMsg crm = req.getCrm();
            CertRequest certReq = crm.getCertReq();
            reqId = certReq.getCertReqId();
            if (!sharedSecretFound) {
                bpids.addElement(reqId);
                context.put("POPLinkWitness", bpids);
                return false;
            } else {
                for (int i = 0; i < certReq.numControls(); i++) {
                    AVA ava = certReq.controlAt(i);

                    if (ava.getOID().equals(OBJECT_IDENTIFIER.id_cmc_popLinkWitnessV2)) {
                        CMS.debug(methodPos + "found id_cmc_popLinkWitnessV2");
                        if (ident_string == null) {
                            bpids.addElement(reqId);
                            context.put("identification", bpids);
                            context.put("POPLinkWitnessV2", bpids);
                            String msg = "id_cmc_popLinkWitnessV2 must be accompanied by id_cmc_identification in this server";
                            CMS.debug(methodPos + msg);
                            return false;
                        }

                        ASN1Value value = ava.getValue();
                        PopLinkWitnessV2 popLinkWitnessV2 = getPopLinkWitnessV2control(value);

                        boolean valid = verifyPopLinkWitnessV2(popLinkWitnessV2,
                                randomSeed,
                                sharedSecret,
                                ident_string);
                        if (!valid) {
                            bpids.addElement(reqId);
                            context.put("POPLinkWitnessV2", bpids);
                            return valid;
                        }
                    } else if (ava.getOID().equals(OBJECT_IDENTIFIER.id_cmc_idPOPLinkWitness)) {
                        CMS.debug(methodPos + "found id_cmc_idPOPLinkWitness");
                        ASN1Value value = ava.getValue();
                        ByteArrayInputStream bis = new ByteArrayInputStream(
                                ASN1Util.encode(value));
                        OCTET_STRING ostr = null;
                        try {
                            ostr = (OCTET_STRING) (new OCTET_STRING.Template()).decode(bis);
                            bv = ostr.toByteArray();
                        } catch (Exception e) {
                            bpids.addElement(reqId);
                            context.put("POPLinkWitness", bpids);
                            return false;
                        }

                        boolean valid = verifyDigest(sharedSecret.getBytes(),
                                randomSeed, bv);
                        if (!valid) {
                            bpids.addElement(reqId);
                            context.put("POPLinkWitness", bpids);
                            return valid;
                        }
                    }
                }
            }
        }

        return true;
    }

    private boolean verifyDigest(byte[] sharedSecret, byte[] text, byte[] bv) {
        MessageDigest hashAlg;
        try {
            hashAlg = MessageDigest.getInstance("SHA1");
        } catch (NoSuchAlgorithmException ex) {
            CMS.debug("EnrollProfile:verifyDigest: " + ex.toString());
            return false;
        }

        return verifyDigest(sharedSecret, text, bv, hashAlg, hashAlg);
    }

    /**
     * verifyDigest verifies digest using the
     * specified hashAlg and macAlg
     *
     * @param sharedSecret shared secret in bytes
     * @param text data to be verified in bytes
     * @param bv witness in bytes
     * @param hashAlg hashing algorithm
     * @param macAlg message authentication algorithm
     * cfu
     */
    private boolean verifyDigest(byte[] sharedSecret, byte[] text, byte[] bv,
            MessageDigest hashAlg, MessageDigest macAlg) {
        String method = "EnrollProfile:verifyDigest: ";
        byte[] key = null;
        CMS.debug(method + "in verifyDigest: hashAlg=" + hashAlg.toString() +
                "; macAlg=" + macAlg.toString());

        if ((sharedSecret == null) ||
            (text == null) ||
            (bv == null) ||
            (hashAlg == null) ||
            (macAlg == null)) {
            CMS.debug(method + "method parameters cannot be null");
            return false;
        }
        key = hashAlg.digest(sharedSecret);

        byte[] finalDigest = null;
        HMACDigest hmacDigest = new HMACDigest(macAlg, key);
        hmacDigest.update(text);

        finalDigest = hmacDigest.digest();

        if (finalDigest.length != bv.length) {
            CMS.debug(method + " The length of two HMAC digest are not the same.");
            return false;
        }

        for (int j = 0; j < bv.length; j++) {
            if (bv[j] != finalDigest[j]) {
                CMS.debug(method + " The content of two HMAC digest are not the same.");
                return false;
            }
        }

        CMS.debug(method + " The content of two HMAC digest are the same.");
        return true;
    }

    private SEQUENCE getRequestBpids(SEQUENCE reqSeq) {
        SEQUENCE bpids = new SEQUENCE();
        for (int i = 0; i < reqSeq.size(); i++) {
            TaggedRequest req = (TaggedRequest) reqSeq.elementAt(i);
            if (req.getType().equals(TaggedRequest.PKCS10)) {
                TaggedCertificationRequest tcr = req.getTcr();
                bpids.addElement(tcr.getBodyPartID());
            } else if (req.getType().equals(TaggedRequest.CRMF)) {
                CertReqMsg crm = req.getCrm();
                CertRequest request = crm.getCertReq();
                bpids.addElement(request.getCertReqId());
            }
        }

        return bpids;
    }

    /**
     * verifyIdentityProofV2 handles IdentityProofV2 as defined by RFC5272
     *
     * @param attr controlSequence of the PKI request PKIData
     * @param ident value of the id_cmc_identification control
     * @param reqSeq requestSequence of the PKI request PKIData
     * @return boolean true if the witness values correctly verified
     * @author cfu
     */
    private boolean verifyIdentityProofV2(
            SessionContext sessionContext,
            TaggedAttribute attr,
            UTF8String ident,
            SEQUENCE reqSeq) {
        String method = "EnrollProfile:verifyIdentityProofV2: ";
        String msg = "";
        CMS.debug(method + " begins");
        boolean verified = false;
        String auditMessage = method;

        if ((attr == null) ||
                (ident == null) ||
                (reqSeq == null)) {
            CMS.debug(method + "method parameters cannot be null");
            // this is internal error
            return false;
        }

        String ident_string = ident.toString();
        String auditAttemptedCred = null;

        SET vals = attr.getValues(); // getting the IdentityProofV2 structure
        if (vals.size() < 1) {
            msg = " invalid TaggedAttribute in request";
            CMS.debug(method + msg);
            auditMessage = CMS.getLogMessage(
                    AuditEvent.CMC_PROOF_OF_IDENTIFICATION,
                    auditAttemptedCred,
                    ILogger.FAILURE,
                    method + msg);
            audit(auditMessage);
            return false;
        }

        String configName = "cmc.sharedSecret.class";
        ISharedToken tokenClass = CMS.getSharedTokenClass(configName);

        if (tokenClass == null) {
            msg = " Failed to retrieve shared secret plugin class";
            CMS.debug(method + msg);
            auditMessage = CMS.getLogMessage(
                    AuditEvent.CMC_PROOF_OF_IDENTIFICATION,
                    auditAttemptedCred,
                    ILogger.FAILURE,
                    method + msg);
            audit(auditMessage);
            return false;
        }

        String token = null;
        if (ident_string != null) {
            auditAttemptedCred = ident_string;
            token = tokenClass.getSharedToken(ident_string);
        } else
            token = tokenClass.getSharedToken(mCMCData);

        if (token == null) {
            msg = " Failed to retrieve shared secret";
            CMS.debug(method + msg);
            auditMessage = CMS.getLogMessage(
                    AuditEvent.CMC_PROOF_OF_IDENTIFICATION,
                    auditAttemptedCred,
                    ILogger.FAILURE,
                    method + msg);
            audit(auditMessage);
            return false;
        }

        // CMS.debug(method + "Shared Secret returned by tokenClass:" + token);
        try {
            IdentityProofV2 idV2val = (IdentityProofV2) (ASN1Util.decode(IdentityProofV2.getTemplate(),
                    ASN1Util.encode(vals.elementAt(0))));

            DigestAlgorithm hashAlgID = DigestAlgorithm.fromOID(idV2val.getHashAlgID().getOID());
            MessageDigest hashAlg = MessageDigest.getInstance(hashAlgID.toString());

            HMACAlgorithm macAlgId = HMACAlgorithm.fromOID(idV2val.getMacAlgId().getOID());
            MessageDigest macAlg = MessageDigest
                    .getInstance(CryptoUtil.getHMACtoMessageDigestName(macAlgId.toString()));

            OCTET_STRING witness = idV2val.getWitness();
            if (witness == null) {
                msg = " witness reurned by idV2val.getWitness is null";
                CMS.debug(method + msg);
                throw new EBaseException(msg);
            }

            byte[] witness_bytes = witness.toByteArray();
            byte[] request_bytes = ASN1Util.encode(reqSeq); // PKIData reqSequence field
            verified = verifyDigest(
                    (ident_string != null) ? (token + ident_string).getBytes() : token.getBytes(),
                    request_bytes,
                    witness_bytes,
                    hashAlg, macAlg);

            String auditSubjectID = null;

            if (verified) {
                auditSubjectID = (String)
                        sessionContext.get(SessionContext.USER_ID);
                CMS.debug(method + "current auditSubjectID was:"+ auditSubjectID);
                CMS.debug(method + "identity verified. Updating auditSubjectID");
                CMS.debug(method + "updated auditSubjectID is:"+ ident_string);
                auditSubjectID = ident_string;
                sessionContext.put(SessionContext.USER_ID, auditSubjectID);

                auditMessage = CMS.getLogMessage(
                        AuditEvent.CMC_PROOF_OF_IDENTIFICATION,
                        auditSubjectID,
                        ILogger.SUCCESS,
                        "method=" + method);
                audit(auditMessage);
            } else {
                msg = "IdentityProofV2 failed to verify";
                CMS.debug(method + msg);
                throw new EBaseException(msg);
            }
            return verified;
        } catch (Exception e) {
            CMS.debug(method + " Failed with Exception: " + e.toString());
            auditMessage = CMS.getLogMessage(
                    AuditEvent.CMC_PROOF_OF_IDENTIFICATION,
                    auditAttemptedCred,
                    ILogger.FAILURE,
                    method + e.toString());
            audit(auditMessage);
            return false;
        }

    } // verifyIdentityProofV2

    private boolean verifyIdentityProof(
            TaggedAttribute attr, SEQUENCE reqSeq) {
        String method = "verifyIdentityProof: ";
        boolean verified = false;

        SET vals = attr.getValues();
        if (vals.size() < 1)
            return false;

        String configName = "cmc.sharedSecret.class";
            ISharedToken tokenClass = CMS.getSharedTokenClass(configName);
        if (tokenClass == null) {
            CMS.debug(method + " Failed to retrieve shared secret plugin class");
            return false;
        }

        String token = tokenClass.getSharedToken(mCMCData);
        OCTET_STRING ostr = null;
        try {
            ostr = (OCTET_STRING) (ASN1Util.decode(OCTET_STRING.getTemplate(),
                    ASN1Util.encode(vals.elementAt(0))));
        } catch (InvalidBERException e) {
            CMS.debug(method + "Failed to decode the byte value.");
            return false;
        }
        byte[] b = ostr.toByteArray();
        byte[] text = ASN1Util.encode(reqSeq);

        verified = verifyDigest(token.getBytes(), text, b);
        if (verified) {// update auditSubjectID
            //placeholder. Should probably just disable this v1 method
        }
        return verified;
    }

    public void fillTaggedRequest(Locale locale, TaggedRequest tagreq, X509CertInfo info,
            IRequest req)
            throws EProfileException, ECMCPopFailedException, ECMCBadRequestException {
        String auditMessage = null;
        String auditSubjectID = auditSubjectID();

        String method = "EnrollProfile: fillTaggedRequest: ";
        CMS.debug(method + "begins");
        TaggedRequest.Type type = tagreq.getType();
        if (type == null) {
            CMS.debug(method + "TaggedRequest type == null");
            throw new EProfileException(
                    CMS.getUserMessage(locale, "CMS_PROFILE_INVALID_REQUEST")+
                    "TaggedRequest type null");
        }

        if (type.equals(TaggedRequest.PKCS10)) {
            String methodPos = method + "PKCS10: ";
            CMS.debug(methodPos + " TaggedRequest type == pkcs10");
            boolean sigver = true;
            boolean tokenSwitched = false;
            CryptoManager cm = null;
            CryptoToken signToken = null;
            CryptoToken savedToken = null;
            try {
                // for PKCS10, "sigver" would provide the POP
                sigver = CMS.getConfigStore().getBoolean("ca.requestVerify.enabled", true);
                cm = CryptoManager.getInstance();
                if (sigver == true) {
                    CMS.debug(methodPos + "sigver true, POP is to be verified");
                    String tokenName =
                        CMS.getConfigStore().getString("ca.requestVerify.token", CryptoUtil.INTERNAL_TOKEN_NAME);
                    savedToken = cm.getThreadToken();
                    signToken = CryptoUtil.getCryptoToken(tokenName);
                    if (!savedToken.getName().equals(signToken.getName())) {
                        cm.setThreadToken(signToken);
                        tokenSwitched = true;
                    }
                } else {
                    // normally, you would not get here, as you almost always
                    // would want to verify the PKCS10 signature when it's
                    // already there instead of taking a 2nd trip
                    CMS.debug(methodPos + "sigver false, POP is not to be verified now, but instead will be challenged");
                    req.setExtData("cmc_POPchallengeRequired", "true");
                }

                TaggedCertificationRequest tcr = tagreq.getTcr();
                CertificationRequest p10 = tcr.getCertificationRequest();
                ByteArrayOutputStream ostream = new ByteArrayOutputStream();

                p10.encode(ostream);
                PKCS10 pkcs10 = new PKCS10(ostream.toByteArray(), sigver);
                if (sigver) {
                    auditMessage = CMS.getLogMessage(
                            AuditEvent.PROOF_OF_POSSESSION,
                            auditSubjectID,
                            ILogger.SUCCESS,
                            "method="+method);
                    audit(auditMessage);
                }

                req.setExtData("bodyPartId", tcr.getBodyPartID());
                fillPKCS10(locale, pkcs10, info, req);
            } catch (Exception e) {
                CMS.debug(method + e);
                // this will throw
                if (sigver)
                    popFailed(locale, auditSubjectID, auditMessage, e);
            }  finally {
                if ((sigver == true) && (tokenSwitched == true)){
                    cm.setThreadToken(savedToken);
                }
            }
            CMS.debug(methodPos + "done");
        } else if (type.equals(TaggedRequest.CRMF)) {
            String methodPos = method + "CRMF: ";
            CMS.debug(methodPos + " TaggedRequest type == crmf");
            CertReqMsg crm = tagreq.getCrm();
            SessionContext context = SessionContext.getContext();
            Integer nums = (Integer) (context.get("numOfControls"));

            boolean verifyAllow = false; //disable RA by default
            try {
                String configName = "cmc.lraPopWitness.verify.allow";
                CMS.debug(methodPos + "getting :" + configName);
                verifyAllow = CMS.getConfigStore().getBoolean(configName, false);
                CMS.debug(methodPos + "cmc.lraPopWitness.verify.allow is " + verifyAllow);
            } catch (Exception e) {
                // unlikely to get here
                String msg = methodPos + " Failed to retrieve cmc.lraPopWitness.verify.allow";
                CMS.debug(msg);
                throw new EProfileException(method + msg);
            }
            if (verifyAllow) {
                // check if the LRA POP Witness Control attribute exists
                if (nums != null && nums.intValue() > 0) {
                    TaggedAttribute attr = (TaggedAttribute) (context.get(OBJECT_IDENTIFIER.id_cmc_lraPOPWitness));
                    if (attr != null) {
                        parseLRAPopWitness(locale, crm, attr);
                    } else {
                        CMS.debug(
                                methodPos + " verify POP in CMC because LRA POP Witness control attribute doesnt exist in the CMC request.");
                        if (crm.hasPop()) {
                            CMS.debug(methodPos + " hasPop true");
                            verifyPOP(locale, crm);
                        } else { // no signing POP, then do it the hard way
                            CMS.debug(methodPos + "hasPop false, need to challenge");
                            req.setExtData("cmc_POPchallengeRequired", "true");
                        }
                    }
                } else {
                    CMS.debug(
                            methodPos + " verify POP in CMC because LRA POP Witness control attribute doesnt exist in the CMC request.");
                    if (crm.hasPop()) {
                        CMS.debug(methodPos + " hasPop true");
                        verifyPOP(locale, crm);
                    } else { // no signing POP, then do it the hard way
                        CMS.debug(methodPos + "hasPop false, need to challenge");
                        req.setExtData("cmc_POPchallengeRequired", "true");
                    }
                }

            } else { //!verifyAllow

                if (crm.hasPop()) {
                    CMS.debug(methodPos + " hasPop true");
                    verifyPOP(locale, crm);
                } else { // no signing POP, then do it the hard way
                    CMS.debug(methodPos + "hasPop false, need to challenge");
                    req.setExtData("cmc_POPchallengeRequired", "true");
                }
            }

            fillCertReqMsg(locale, crm, info, req);
        } else {
            CMS.debug(method + " unsupported type (not CRMF or PKCS10)");
            throw new ECMCBadRequestException(
                    CMS.getUserMessage(locale, "CMS_PROFILE_INVALID_REQUEST"));
        }
    }

    private void parseLRAPopWitness(Locale locale, CertReqMsg crm,
            TaggedAttribute attr) throws EProfileException {
        SET vals = attr.getValues();
        boolean donePOP = false;
        INTEGER reqId = null;
        if (vals.size() > 0) {
            LraPopWitness lraPop = null;
            try {
                lraPop = (LraPopWitness) (ASN1Util.decode(LraPopWitness.getTemplate(),
                        ASN1Util.encode(vals.elementAt(0))));
            } catch (InvalidBERException e) {
                CMS.debug("EnrollProfile: Unable to parse LRA POP Witness: " + e);
                CMS.debug(e);
                throw new EProfileException(
                        CMS.getUserMessage(locale, "CMS_PROFILE_ENCODING_ERROR"), e);
            }

            SEQUENCE bodyIds = lraPop.getBodyIds();
            reqId = crm.getCertReq().getCertReqId();

            for (int i = 0; i < bodyIds.size(); i++) {
                INTEGER num = (INTEGER) (bodyIds.elementAt(i));
                if (num.toString().equals(reqId.toString())) {
                    donePOP = true;
                    CMS.debug("EnrollProfile: skip POP for request: "
                            + reqId + " because LRA POP Witness control is found.");
                    break;
                }
            }
        }

        if (!donePOP) {
            CMS.debug("EnrollProfile: not skip POP for request: "
                    + reqId
                    + " because this request id is not part of the body list in LRA Pop witness control.");
            verifyPOP(locale, crm);
        }
    }

    public CertReqMsg[] parseCRMF(Locale locale, String certreq)
            throws EProfileException {

        /* cert request must not be null */
        if (certreq == null) {
            CMS.debug("EnrollProfile: parseCRMF() certreq null");
            throw new EProfileException(
                    CMS.getUserMessage(locale, "CMS_PROFILE_INVALID_REQUEST"));
        }
        CMS.debug("EnrollProfile: Start parseCRMF(): "/* + certreq*/);

        CertReqMsg msgs[] = null;
        String creq = normalizeCertReq(certreq);
        try {
            byte data[] = CMS.AtoB(creq);
            ByteArrayInputStream crmfBlobIn =
                    new ByteArrayInputStream(data);
            SEQUENCE crmfMsgs = (SEQUENCE)
                    new SEQUENCE.OF_Template(new
                            CertReqMsg.Template()).decode(crmfBlobIn);
            int nummsgs = crmfMsgs.size();

            if (nummsgs <= 0)
                return null;
            msgs = new CertReqMsg[crmfMsgs.size()];
            for (int i = 0; i < nummsgs; i++) {
                msgs[i] = (CertReqMsg) crmfMsgs.elementAt(i);
            }
            return msgs;
        } catch (Exception e) {
            CMS.debug("EnrollProfile: Unable to parse CRMF request: " + e);
            CMS.debug(e);
            throw new EProfileException(
                    CMS.getUserMessage(locale, "CMS_PROFILE_INVALID_REQUEST"), e);
        }
    }

    private static final OBJECT_IDENTIFIER PKIARCHIVEOPTIONS_OID =
            new OBJECT_IDENTIFIER(new long[] { 1, 3, 6, 1, 5, 5, 7, 5, 1, 4 }
            );

    protected PKIArchiveOptions getPKIArchiveOptions(AVA ava) {
        ASN1Value archVal = ava.getValue();
        ByteArrayInputStream bis = new ByteArrayInputStream(
                ASN1Util.encode(archVal));
        PKIArchiveOptions archOpts = null;

        try {
            archOpts = (PKIArchiveOptions)
                    (new PKIArchiveOptions.Template()).decode(bis);
        } catch (Exception e) {
            CMS.debug("EnrollProfile: getPKIArchiveOptions " + e);
        }
        return archOpts;
    }

    public PKIArchiveOptions toPKIArchiveOptions(byte options[]) {
        ByteArrayInputStream bis = new ByteArrayInputStream(options);
        PKIArchiveOptions archOpts = null;

        try {
            archOpts = (PKIArchiveOptions)
                    (new PKIArchiveOptions.Template()).decode(bis);
        } catch (Exception e) {
            CMS.debug("EnrollProfile: toPKIArchiveOptions " + e);
        }
        return archOpts;
    }

    public byte[] toByteArray(PKIArchiveOptions options) {
        return ASN1Util.encode(options);
    }

    public void fillCertReqMsg(Locale locale, CertReqMsg certReqMsg, X509CertInfo info,
            IRequest req)
            throws EProfileException, ECMCUnsupportedExtException {
        String method = "EnrollProfile: fillCertReqMsg: ";
        try {
            CMS.debug(method + "Start parseCertReqMsg ");
            CertRequest certReq = certReqMsg.getCertReq();
            req.setExtData("bodyPartId", certReq.getCertReqId());
            // handle PKIArchiveOption (key archival)
            for (int i = 0; i < certReq.numControls(); i++) {
                AVA ava = certReq.controlAt(i);

                if (ava.getOID().equals(PKIARCHIVEOPTIONS_OID)) {
                    PKIArchiveOptions opt = getPKIArchiveOptions(ava);

                    //req.set(REQUEST_ARCHIVE_OPTIONS, opt);
                    req.setExtData(REQUEST_ARCHIVE_OPTIONS,
                            toByteArray(opt));
                    try {
                        String transportCert = CMS.getConfigStore().getString("ca.connector.KRA.transportCert", "");
                        req.setExtData(IEnrollProfile.REQUEST_TRANSPORT_CERT, transportCert);
                    } catch (EBaseException ee) {
                        CMS.debug("EnrollProfile: fillCertReqMsg - Exception reading transportCert: "+ ee);
                    }
                }
            }

            CertTemplate certTemplate = certReq.getCertTemplate();

            // parse key
            SubjectPublicKeyInfo spki = certTemplate.getPublicKey();
            ByteArrayOutputStream keyout = new ByteArrayOutputStream();

            spki.encode(keyout);
            byte[] keybytes = keyout.toByteArray();
            X509Key key = new X509Key();

            key.decode(keybytes);

            // XXX - kmccarth - this may simply undo the decoding above
            //                  but for now it's unclear whether X509Key
            //                  changest the format when decoding.
            CertificateX509Key certKey = new CertificateX509Key(key);
            ByteArrayOutputStream certKeyOut = new ByteArrayOutputStream();
            certKey.encode(certKeyOut);
            req.setExtData(REQUEST_KEY, certKeyOut.toByteArray());

            // parse validity
            if (certTemplate.getNotBefore() != null ||
                    certTemplate.getNotAfter() != null) {
                CMS.debug("EnrollProfile:  requested notBefore: " + certTemplate.getNotBefore());
                CMS.debug("EnrollProfile:  requested notAfter:  " + certTemplate.getNotAfter());
                CMS.debug("EnrollProfile:  current CA time:     " + new Date());
                CertificateValidity certValidity = new CertificateValidity(
                        certTemplate.getNotBefore(), certTemplate.getNotAfter());
                ByteArrayOutputStream certValidityOut =
                        new ByteArrayOutputStream();
                certValidity.encode(certValidityOut);
                req.setExtData(REQUEST_VALIDITY, certValidityOut.toByteArray());
            } else {
                CMS.debug("EnrollProfile:  validity not supplied");
            }

            // parse subject
            if (certTemplate.hasSubject()) {
                Name subjectdn = certTemplate.getSubject();
                ByteArrayOutputStream subjectEncStream =
                        new ByteArrayOutputStream();

                subjectdn.encode(subjectEncStream);
                byte[] subjectEnc = subjectEncStream.toByteArray();
                X500Name subject = new X500Name(subjectEnc);

                //info.set(X509CertInfo.SUBJECT,
                //  new CertificateSubjectName(subject));

                req.setExtData(REQUEST_SUBJECT_NAME,
                        new CertificateSubjectName(subject));
                try {
                    String subjectCN = subject.getCommonName();
                    if (subjectCN == null)
                        subjectCN = "";
                    req.setExtData(REQUEST_SUBJECT_NAME + ".cn", subjectCN);
                } catch (Exception ee) {
                    req.setExtData(REQUEST_SUBJECT_NAME + ".cn", "");
                }
                try {
                    String subjectUID = subject.getUserID();
                    if (subjectUID == null)
                        subjectUID = "";
                    req.setExtData(REQUEST_SUBJECT_NAME + ".uid", subjectUID);
                } catch (Exception ee) {
                    req.setExtData(REQUEST_SUBJECT_NAME + ".uid", "");
                }
            }

            // parse extensions
            CertificateExtensions extensions = null;

            // try {
            extensions = req.getExtDataInCertExts(REQUEST_EXTENSIONS);
            //  } catch (CertificateException e) {
            //     extensions = null;
            // } catch (IOException e) {
            //    extensions = null;
            //  }
            if (certTemplate.hasExtensions()) {
                // put each extension from CRMF into CertInfo.
                // index by extension name, consistent with
                // CertificateExtensions.parseExtension() method.
                if (extensions == null)
                    extensions = new CertificateExtensions();
                int numexts = certTemplate.numExtensions();

                /*
                 * there seems to be an issue with constructor in Extension
                 * when feeding SubjectKeyIdentifierExtension;
                 * Special-case it
                 */
                OBJECT_IDENTIFIER SKIoid =
                        new OBJECT_IDENTIFIER(PKIXExtensions.SubjectKey_Id.toString());
                for (int j = 0; j < numexts; j++) {
                    org.mozilla.jss.pkix.cert.Extension jssext =
                            certTemplate.extensionAt(j);
                    boolean isCritical = jssext.getCritical();
                    org.mozilla.jss.asn1.OBJECT_IDENTIFIER jssoid =
                            jssext.getExtnId();
                    CMS.debug(method + "found extension:" + jssoid.toString());
                    long[] numbers = jssoid.getNumbers();
                    int[] oidNumbers = new int[numbers.length];

                    for (int k = numbers.length - 1; k >= 0; k--) {
                        oidNumbers[k] = (int) numbers[k];
                    }
                    ObjectIdentifier oid =
                            new ObjectIdentifier(oidNumbers);
                    org.mozilla.jss.asn1.OCTET_STRING jssvalue =
                            jssext.getExtnValue();
                    ByteArrayOutputStream jssvalueout =
                            new ByteArrayOutputStream();

                    jssvalue.encode(jssvalueout);
                    byte[] extValue = jssvalueout.toByteArray();

                    Extension ext = null;
                    if (jssoid.equals(SKIoid)) {
                        CMS.debug(method + "found SUBJECT_KEY_IDENTIFIER extension");
                        ext = new SubjectKeyIdentifierExtension(false,
                                jssext.getExtnValue().toByteArray());
                    } else {
                        new Extension(oid, isCritical, extValue);
                    }

                    extensions.parseExtension(ext);
                }
                //                info.set(X509CertInfo.EXTENSIONS, extensions);
                req.setExtData(REQUEST_EXTENSIONS, extensions);

            }
        } catch (IOException e) {
            CMS.debug("EnrollProfile: Unable to fill certificate request message: " + e);
            CMS.debug(e);
            throw new ECMCUnsupportedExtException(
                    CMS.getUserMessage(locale, "CMS_PROFILE_INVALID_REQUEST"), e);
        } catch (InvalidKeyException e) {
            CMS.debug("EnrollProfile: Unable to fill certificate request message: " + e);
            CMS.debug(e);
            throw new EProfileException(
                    CMS.getUserMessage(locale, "CMS_PROFILE_INVALID_REQUEST"), e);
        // } catch (CertificateException e) {
        //     CMS.debug(e);
        //     throw new EProfileException(e);
        }
    }

    public PKCS10 parsePKCS10(Locale locale, String certreq)
            throws EProfileException {
        /* cert request must not be null */
        if (certreq == null) {
            CMS.debug("EnrollProfile: parsePKCS10() certreq null");
            throw new EProfileException(
                    CMS.getUserMessage(locale, "CMS_PROFILE_INVALID_REQUEST"));
        }
        CMS.debug("Start parsePKCS10(): " + certreq);

        // trim header and footer
        String creq = normalizeCertReq(certreq);

        // parse certificate into object
        byte data[] = CMS.AtoB(creq);
        PKCS10 pkcs10 = null;
        CryptoManager cm = null;
        CryptoToken savedToken = null;
        boolean sigver = true;

        try {
            cm = CryptoManager.getInstance();
            sigver = CMS.getConfigStore().getBoolean("ca.requestVerify.enabled", true);
            if (sigver) {
                CMS.debug("EnrollProfile: parsePKCS10: signature verification enabled");
                String tokenName = CMS.getConfigStore().getString("ca.requestVerify.token", CryptoUtil.INTERNAL_TOKEN_NAME);
                savedToken = cm.getThreadToken();
                CryptoToken signToken = CryptoUtil.getCryptoToken(tokenName);
                CMS.debug("EnrollProfile: parsePKCS10 setting thread token");
                cm.setThreadToken(signToken);
                pkcs10 = new PKCS10(data);
            } else {
                CMS.debug("EnrollProfile: parsePKCS10: signature verification disabled");
                pkcs10 = new PKCS10(data, sigver);
            }
        } catch (Exception e) {
            CMS.debug("EnrollProfile: Unable to parse PKCS #10 request: " + e);
            CMS.debug(e);
            throw new EProfileException(
                    CMS.getUserMessage(locale, "CMS_PROFILE_INVALID_REQUEST"), e);
        } finally {
            if (sigver) {
                CMS.debug("EnrollProfile: parsePKCS10 restoring thread token");
                cm.setThreadToken(savedToken);
            }
        }

        return pkcs10;
    }

    public void fillPKCS10(Locale locale, PKCS10 pkcs10, X509CertInfo info, IRequest req)
            throws EProfileException, ECMCUnsupportedExtException {
        String method = "EnrollProfile: fillPKCS10: ";
        CMS.debug(method + "begins");
        X509Key key = pkcs10.getSubjectPublicKeyInfo();

        try {
            CertificateX509Key certKey = new CertificateX509Key(key);
            ByteArrayOutputStream certKeyOut = new ByteArrayOutputStream();
            certKey.encode(certKeyOut);
            req.setExtData(IEnrollProfile.REQUEST_KEY, certKeyOut.toByteArray());

            req.setExtData(EnrollProfile.REQUEST_SUBJECT_NAME,
                    new CertificateSubjectName(pkcs10.getSubjectName()));
            try {
                String subjectCN = pkcs10.getSubjectName().getCommonName();
                if (subjectCN == null)
                    subjectCN = "";
                req.setExtData(REQUEST_SUBJECT_NAME + ".cn", subjectCN);
            } catch (Exception ee) {
                req.setExtData(REQUEST_SUBJECT_NAME + ".cn", "");
            }
            try {
                String subjectUID = pkcs10.getSubjectName().getUserID();
                if (subjectUID == null)
                    subjectUID = "";
                req.setExtData(REQUEST_SUBJECT_NAME + ".uid", subjectUID);
            } catch (Exception ee) {
                req.setExtData(REQUEST_SUBJECT_NAME + ".uid", "");
            }

            info.set(X509CertInfo.KEY, certKey);

            PKCS10Attributes p10Attrs = pkcs10.getAttributes();
            if (p10Attrs != null) {
                PKCS10Attribute p10Attr = p10Attrs.getAttribute(CertificateExtensions.NAME);
                if (p10Attr != null && p10Attr.getAttributeId().equals(
                        PKCS9Attribute.EXTENSION_REQUEST_OID)) {
                    CMS.debug(method + "Found PKCS10 extension");
                    Extensions exts0 = (Extensions)
                            (p10Attr.getAttributeValue());
                    DerOutputStream extOut = new DerOutputStream();

                    exts0.encode(extOut);
                    byte[] extB = extOut.toByteArray();
                    DerInputStream extIn = new DerInputStream(extB);
                    CertificateExtensions exts = new CertificateExtensions(extIn);
                    if (exts != null) {
                        CMS.debug(method + "PKCS10 found extensions " + exts);
                        // info.set(X509CertInfo.EXTENSIONS, exts);
                        req.setExtData(REQUEST_EXTENSIONS, exts);
                    }
                } else {
                    CMS.debug(method + "PKCS10 no extension found");
                }
            }

            CMS.debug(method + "Finish parsePKCS10 - " + pkcs10.getSubjectName());
        } catch (IOException e) {
            CMS.debug(method + "Unable to fill PKCS #10: " + e);
            throw new ECMCUnsupportedExtException(
                    CMS.getUserMessage(locale, "CMS_PROFILE_INVALID_REQUEST"), e);
        } catch (CertificateException e) {
            CMS.debug(method + "Unable to fill PKCS #10: " + e);
            throw new EProfileException(
                    CMS.getUserMessage(locale, "CMS_PROFILE_INVALID_REQUEST"), e);
        }
    }

    // for netkey
    public void fillNSNKEY(Locale locale, String sn, String skey, X509CertInfo info, IRequest req)
            throws EProfileException {

        try {
            //cfu - is the algorithm going to be replaced by the policy?
            X509Key key = new X509Key();
            key.decode(CMS.AtoB(skey));

            info.set(X509CertInfo.KEY, new CertificateX509Key(key));
            //                      req.set(EnrollProfile.REQUEST_SUBJECT_NAME,
            //                              new CertificateSubjectName(new
            //                              X500Name("CN="+sn)));
            req.setExtData("screenname", sn);
            // keeping "aoluid" to be backward compatible
            req.setExtData("aoluid", sn);
            req.setExtData("uid", sn);
            CMS.debug("EnrollProfile: fillNSNKEY(): uid=" + sn);

        } catch (Exception e) {
            CMS.debug("EnrollProfile: Unable to fill NSNKEY: " + e);
            CMS.debug(e);
            throw new EProfileException(
                    CMS.getUserMessage(locale, "CMS_PROFILE_INVALID_REQUEST"), e);
        }
    }

    // for house key
    public void fillNSHKEY(Locale locale, String tcuid, String skey, X509CertInfo info, IRequest req)
            throws EProfileException {

        try {
            //cfu - is the algorithm going to be replaced by the policy?
            X509Key key = new X509Key();
            key.decode(CMS.AtoB(skey));

            info.set(X509CertInfo.KEY, new CertificateX509Key(key));
            //                      req.set(EnrollProfile.REQUEST_SUBJECT_NAME,
            //                              new CertificateSubjectName(new
            //                              X500Name("CN="+sn)));
            req.setExtData("tokencuid", tcuid);

            CMS.debug("EnrollProfile: fillNSNKEY(): tokencuid=" + tcuid);

        } catch (Exception e) {
            CMS.debug("EnrollProfile: Unable to fill NSHKEY: " + e);
            CMS.debug(e);
            throw new EProfileException(
                    CMS.getUserMessage(locale, "CMS_PROFILE_INVALID_REQUEST"), e);
        }
    }

    public DerInputStream parseKeyGen(Locale locale, String certreq)
            throws EProfileException {
        byte data[] = CMS.AtoB(certreq);

        DerInputStream derIn = new DerInputStream(data);

        return derIn;
    }

    public void fillKeyGen(Locale locale, DerInputStream derIn, X509CertInfo info, IRequest req
            )
                    throws EProfileException {
        try {

            /* get SPKAC Algorithm & Signature */
            DerValue derSPKACContent[] = derIn.getSequence(3);
            @SuppressWarnings("unused")
            AlgorithmId mAlgId = AlgorithmId.parse(derSPKACContent[1]);
            @SuppressWarnings("unused")
            byte mSignature[] = derSPKACContent[2].getBitString();

            /* get PKAC SPKI & Challenge */
            byte mPKAC[] = derSPKACContent[0].toByteArray();

            derIn = new DerInputStream(mPKAC);
            DerValue derPKACContent[] = derIn.getSequence(2);

            @SuppressWarnings("unused")
            DerValue mDerSPKI = derPKACContent[0];
            X509Key mSPKI = X509Key.parse(derPKACContent[0]);

            @SuppressWarnings("unused")
            String mChallenge;
            DerValue mDerChallenge = derPKACContent[1];

            if (mDerChallenge.length() != 0)
                mChallenge = derPKACContent[1].getIA5String();

            CertificateX509Key certKey = new CertificateX509Key(mSPKI);
            ByteArrayOutputStream certKeyOut = new ByteArrayOutputStream();
            certKey.encode(certKeyOut);
            req.setExtData(IEnrollProfile.REQUEST_KEY, certKeyOut.toByteArray());
            info.set(X509CertInfo.KEY, certKey);
        } catch (IOException e) {
            CMS.debug("EnrollProfile: Unable to fill key gen: " + e);
            CMS.debug(e);
            throw new EProfileException(
                    CMS.getUserMessage(locale, "CMS_PROFILE_INVALID_REQUEST"), e);
        } catch (CertificateException e) {
            CMS.debug("EnrollProfile: Unable to fill key gen: " + e);
            CMS.debug(e);
            throw new EProfileException(
                    CMS.getUserMessage(locale, "CMS_PROFILE_INVALID_REQUEST"), e);
        }
    }

    public String normalizeCertReq(String s) {
        if (s == null) {
            return s;
        }
        s = s.replaceAll("-----BEGIN CERTIFICATE REQUEST-----", "");
        s = s.replaceAll("-----BEGIN NEW CERTIFICATE REQUEST-----", "");
        s = s.replaceAll("-----END CERTIFICATE REQUEST-----", "");
        s = s.replaceAll("-----END NEW CERTIFICATE REQUEST-----", "");

        StringBuffer sb = new StringBuffer();
        StringTokenizer st = new StringTokenizer(s, "\r\n ");

        while (st.hasMoreTokens()) {
            String nextLine = st.nextToken();

            nextLine = nextLine.trim();
            if (nextLine.equals("-----BEGIN CERTIFICATE REQUEST-----"))
                continue;
            if (nextLine.equals("-----BEGIN NEW CERTIFICATE REQUEST-----"))
                continue;
            if (nextLine.equals("-----END CERTIFICATE REQUEST-----"))
                continue;
            if (nextLine.equals("-----END NEW CERTIFICATE REQUEST-----"))
                continue;
            sb.append(nextLine);
        }
        return sb.toString();
    }

    public Locale getLocale(IRequest request) {
        Locale locale = null;
        String language = request.getExtDataInString(
                EnrollProfile.REQUEST_LOCALE);
        if (language != null) {
            locale = new Locale(language);
        }
        return locale;
    }

    /**
     * Populate input
     * <P>
     *
     * (either all "agent" profile cert requests NOT made through a connector, or all "EE" profile cert requests NOT
     * made through a connector)
     * <P>
     *
     * <ul>
     * <li>signed.audit LOGGING_SIGNED_AUDIT_PROFILE_CERT_REQUEST used when a profile cert request is made (before
     * approval process)
     * </ul>
     *
     * @param ctx profile context
     * @param request the certificate request
     * @exception EProfileException an error related to this profile has
     *                occurred
     */
    public void populateInput(IProfileContext ctx, IRequest request)
            throws EProfileException {
        super.populateInput(ctx, request);
    }

    public void populate(IRequest request)
            throws EProfileException {

        String method = "EnrollProfile: populate: ";
        CMS.debug(method + "begins");

        super.populate(request);
    }

    /**
     * Passes the request to the set of constraint policies
     * that validate the request against the profile.
     */
    public void validate(IRequest request)
            throws ERejectException {
        String auditMessage = null;
        String auditSubjectID = auditSubjectID();
        String auditRequesterID = auditRequesterID(request);
        String auditProfileID = auditProfileID();
        String auditCertificateSubjectName = ILogger.SIGNED_AUDIT_EMPTY_VALUE;
        String subject = null;

        CMS.debug("EnrollProfile.validate: start");

        // try {
        X509CertInfo info = request.getExtDataInCertInfo(REQUEST_CERTINFO);

        try {
            CertificateSubjectName sn = (CertificateSubjectName)
                    info.get(X509CertInfo.SUBJECT);

            // if the cert subject name is NOT MISSING, retrieve the
            // actual "auditCertificateSubjectName" and "normalize" it
            if (sn != null) {
                subject = sn.toString();
                if (subject != null) {
                    // NOTE:  This is ok even if the cert subject name
                    //        is "" (empty)!
                    auditCertificateSubjectName = subject.trim();
                    CMS.debug("EnrollProfile.validate: cert subject name:" +
                            auditCertificateSubjectName);
                }
            }

            // store a message in the signed audit log file
            auditMessage = CMS.getLogMessage(
                        AuditEvent.PROFILE_CERT_REQUEST,
                        auditSubjectID,
                        ILogger.SUCCESS,
                        auditRequesterID,
                        auditProfileID,
                        auditCertificateSubjectName);

            audit(auditMessage);
        } catch (CertificateException e) {
            CMS.debug("EnrollProfile: populate " + e);

            // store a message in the signed audit log file
            auditMessage = CMS.getLogMessage(
                        AuditEvent.PROFILE_CERT_REQUEST,
                        auditSubjectID,
                        ILogger.FAILURE,
                        auditRequesterID,
                        auditProfileID,
                        auditCertificateSubjectName);

            audit(auditMessage);
        } catch (IOException e) {
            CMS.debug("EnrollProfile: populate " + e);

            // store a message in the signed audit log file
            auditMessage = CMS.getLogMessage(
                        AuditEvent.PROFILE_CERT_REQUEST,
                        auditSubjectID,
                        ILogger.FAILURE,
                        auditRequesterID,
                        auditProfileID,
                        auditCertificateSubjectName);

            audit(auditMessage);
        }

        super.validate(request);
        Object key = null;

        try {
            key = info.get(X509CertInfo.KEY);
        } catch (CertificateException e) {
        } catch (IOException e) {
        }

        if (key == null) {
            Locale locale = getLocale(request);

            throw new ERejectException(CMS.getUserMessage(
                        locale, "CMS_PROFILE_EMPTY_KEY"));
        }
        /*
        try {
            CMS.debug("EnrollProfile.validate: certInfo : \n" + info);
        } catch (NullPointerException e) {
            // do nothing
        }
        */
        CMS.debug("EnrollProfile.validate: end");
    }

    /**
     * Signed Audit Log Requester ID
     *
     * This method is inherited by all extended "EnrollProfile"s,
     * and is called to obtain the "RequesterID" for
     * a signed audit log message.
     * <P>
     *
     * @param request the actual request
     * @return id string containing the signed audit log message RequesterID
     */
    protected String auditRequesterID(IRequest request) {

        String requesterID = ILogger.UNIDENTIFIED;

        if (request != null) {
            // overwrite "requesterID" if and only if "id" != null
            String id = request.getRequestId().toString();

            if (id != null) {
                requesterID = id.trim();
            }
        }

        return requesterID;
    }

    /**
     * Signed Audit Log Profile ID
     *
     * This method is inherited by all extended "EnrollProfile"s,
     * and is called to obtain the "ProfileID" for
     * a signed audit log message.
     * <P>
     *
     * @return id string containing the signed audit log message ProfileID
     */
    protected String auditProfileID() {

        String profileID = getId();

        if (profileID != null) {
            profileID = profileID.trim();
        } else {
            profileID = ILogger.UNIDENTIFIED;
        }

        return profileID;
    }

    /*
     * verifyPOP - CRMF POP verification for signing keys
     */
    public void verifyPOP(Locale locale, CertReqMsg certReqMsg)
            throws EProfileException, ECMCPopFailedException {
        String method = "EnrollProfile: verifyPOP: ";
        CMS.debug(method + "for signing keys begins.");

        String auditMessage = method;
        String auditSubjectID = auditSubjectID();

        if (!certReqMsg.hasPop()) {
            CMS.debug(method + "missing pop.");
            popFailed(locale, auditSubjectID, auditMessage);
        }
        ProofOfPossession pop = certReqMsg.getPop();
        ProofOfPossession.Type popType = pop.getType();

        if (popType != ProofOfPossession.SIGNATURE) {
            CMS.debug(method + "pop type is not ProofOfPossession.SIGNATURE.");
            popFailed(locale, auditSubjectID, auditMessage);
        }

        try {
            CryptoToken verifyToken = null;
            String tokenName = CMS.getConfigStore().getString("ca.requestVerify.token", CryptoUtil.INTERNAL_TOKEN_NAME);
            if (CryptoUtil.isInternalToken(tokenName)) {
                CMS.debug(method + "POP verification using internal token");
                certReqMsg.verify();
            } else {
                CMS.debug(method + "POP verification using token:" + tokenName);
                verifyToken = CryptoUtil.getCryptoToken(tokenName);
                certReqMsg.verify(verifyToken);
            }

            // store a message in the signed audit log file
            auditMessage = CMS.getLogMessage(
                    AuditEvent.PROOF_OF_POSSESSION,
                    auditSubjectID,
                    ILogger.SUCCESS,
                    "method="+method);
            audit(auditMessage);
        } catch (Exception e) {
            CMS.debug(method + "Unable to verify POP: " + e);
            popFailed(locale, auditSubjectID, auditMessage, e);
        }
        CMS.debug(method + "done.");
    }

    private void popFailed(Locale locale, String auditSubjectID, String msg)
            throws EProfileException, ECMCPopFailedException {
        popFailed(locale, auditSubjectID, msg, null);
    }
    private void popFailed(Locale locale, String auditSubjectID, String msg, Exception e)
            throws EProfileException, ECMCPopFailedException {

            if (e != null)
                msg = msg + e.toString();
            // store a message in the signed audit log file
            String auditMessage = CMS.getLogMessage(
                    AuditEvent.PROOF_OF_POSSESSION,
                    auditSubjectID,
                    ILogger.FAILURE,
                    msg);
            audit(auditMessage);

            if (e != null) {
                throw new ECMCPopFailedException(CMS.getUserMessage(locale,
                        "CMS_POP_VERIFICATION_ERROR"), e);
            } else {
                throw new ECMCPopFailedException(CMS.getUserMessage(locale,
                        "CMS_POP_VERIFICATION_ERROR"));
            }
    }
}