summaryrefslogtreecommitdiffstats
path: root/pki/base/common/src/com/netscape/cms/servlet/cert/scep/CRSEnrollment.java
blob: 246d9a478d140a6bd5ba12dfd756e770d4ad78d6 (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
// --- BEGIN COPYRIGHT BLOCK ---
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; version 2 of the License.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
// (C) 2007 Red Hat, Inc.
// All rights reserved.
// --- END COPYRIGHT BLOCK ---
package com.netscape.cms.servlet.cert.scep;

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import netscape.ldap.*;
import java.security.*;
import java.security.MessageDigest;

import netscape.security.x509.*;
import netscape.security.pkcs.*;
import netscape.security.util.*;
import com.netscape.certsrv.base.*;
import com.netscape.certsrv.authority.*;
import com.netscape.certsrv.logging.*;
import com.netscape.certsrv.request.*;
import com.netscape.certsrv.request.IRequestQueue;
import com.netscape.certsrv.ca.*;
import com.netscape.certsrv.authentication.*;
import com.netscape.certsrv.authentication.AuthCredentials;
import com.netscape.certsrv.profile.*;
import com.netscape.certsrv.ldap.*;
import com.netscape.certsrv.publish.*;
import com.netscape.certsrv.apps.*;
import com.netscape.certsrv.common.*;
import com.netscape.cms.servlet.profile.*;
import org.mozilla.jss.pkcs7.*;
import org.mozilla.jss.asn1.*;
import org.mozilla.jss.*;
import org.mozilla.jss.util.*;
import org.mozilla.jss.crypto.*;
import org.mozilla.jss.pkix.cert.Certificate;
import com.netscape.cmsutil.scep.CRSPKIMessage;


/**
 * This servlet deals with PKCS#10-based certificate requests from
 * CRS, now called SCEP, and defined at:
 *    http://search.ietf.org/internet-drafts/draft-nourse-scep-02.txt
 * 
 * The router is hardcoded to look for the http://host:80/cgi-bin/pkiclient.exe
 *
 * The HTTP parameters are 'operation' and 'message'
 * operation can be either 'GetCACert' or 'PKIOperation'
 *
 * @version $Revision$, $Date$
 */
public class CRSEnrollment extends HttpServlet
{
  protected IProfileSubsystem     mProfileSubsystem = null;
  protected String                mProfileId = null;
  protected ICertAuthority        mAuthority;
  protected IConfigStore          mConfig = null;
  protected IAuthSubsystem        mAuthSubsystem;
  protected String                mAppendDN=null;
  protected String                mEntryObjectclass=null;
  protected boolean               mCreateEntry=false;
  protected boolean               mFlattenDN=false;

  private   String                mAuthManagerName;
  private   String                mSubstoreName;
  private   boolean               mEnabled = false;
  private   boolean               mUseCA = true;
  private   String                mNickname = null;
  private   String                mTokenName = "";
  private   String                mHashAlgorithm = "SHA1";
  private   String                mHashAlgorithmList = null;
  private   String[]              mAllowedHashAlgorithm;
  private   String                mConfiguredEncryptionAlgorithm = "DES3";
  private   String                mEncryptionAlgorithm = "DES3";
  private   String                mEncryptionAlgorithmList = null;
  private   String[]              mAllowedEncryptionAlgorithm;
  private   Random                mRandom = null;
  private   int                   mNonceSizeLimit = 0;
  protected ILogger mLogger =      CMS.getLogger();
  private ICertificateAuthority ca;
		/* for hashing challenge password */
  protected MessageDigest mSHADigest = null;
    
  private static final String PROP_SUBSTORENAME   = "substorename";
  private static final String PROP_AUTHORITY   = "authority";
  private static final String PROP_CRS        = "crs";
  private static final String PROP_CRSCA      = "casubsystem";
  private static final String PROP_CRSAUTHMGR = "authName";
  private static final String PROP_APPENDDN   = "appendDN";
  private static final String PROP_CREATEENTRY= "createEntry";
  private static final String PROP_FLATTENDN  = "flattenDN";
  private static final String PROP_ENTRYOC    = "entryObjectclass";
    
  // URL parameters
  private static final String URL_OPERATION   = "operation";
  private static final String URL_MESSAGE     = "message";

  // possible values for 'operation'
  private static final String OP_GETCACERT    = "GetCACert";
  private static final String OP_PKIOPERATION = "PKIOperation";

  public static final String AUTH_PASSWORD    = "pwd";

  public static final String AUTH_CREDS       = "AuthCreds";
  public static final String AUTH_TOKEN       = "AuthToken";
  public static final String AUTH_FAILED      = "AuthFailed";
 
  public static final String SANE_DNSNAME     = "DNSName";
  public static final String SANE_IPADDRESS   = "IPAddress";

  public static final String CERTINFO         = "CertInfo";
  public static final String SUBJECTNAME      = "SubjectName";


  public static ObjectIdentifier OID_UNSTRUCTUREDNAME    = null;
  public static ObjectIdentifier OID_UNSTRUCTUREDADDRESS = null;
  public static ObjectIdentifier OID_SERIALNUMBER        = null;

  public CRSEnrollment(){}

  public static Hashtable toHashtable(HttpServletRequest req) {
       Hashtable httpReqHash = new Hashtable();
       Enumeration names = req.getParameterNames();
       while (names.hasMoreElements()) {
               String name = (String)names.nextElement();
               httpReqHash.put(name, req.getParameter(name));
       }
       return httpReqHash;
   }

  public void init(ServletConfig sc) {
      // Find the CertificateAuthority we should use for CRS.
	  String crsCA = sc.getInitParameter(PROP_AUTHORITY);
	  if (crsCA == null)
		  crsCA = "ca";
	  mAuthority = (ICertAuthority) CMS.getSubsystem(crsCA);
	  ca = (ICertificateAuthority)mAuthority;

	  if (mAuthority == null) {
          log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_CANT_FIND_AUTHORITY",crsCA));
	  }

      try {
          if (mAuthority instanceof ISubsystem) {
              IConfigStore authorityConfig = ((ISubsystem)mAuthority).getConfigStore();
              IConfigStore scepConfig = authorityConfig.getSubStore("scep");
              mEnabled = scepConfig.getBoolean("enable", false);
              mHashAlgorithm = scepConfig.getString("hashAlgorithm", "SHA1");
              mConfiguredEncryptionAlgorithm = scepConfig.getString("encryptionAlgorithm", "DES3");
              mNonceSizeLimit = scepConfig.getInteger("nonceSizeLimit", 0);
              mHashAlgorithmList = scepConfig.getString("allowedHashAlgorithms", "SHA1,SHA256,SHA512");
              mAllowedHashAlgorithm = mHashAlgorithmList.split(",");
              mEncryptionAlgorithmList = scepConfig.getString("allowedEncryptionAlgorithms", "DES3");
              mAllowedEncryptionAlgorithm = mEncryptionAlgorithmList.split(",");
              mNickname = scepConfig.getString("nickname", ca.getNickname());
              if (mNickname.equals(ca.getNickname())) {
                  mTokenName = ca.getSigningUnit().getTokenName();
              } else {
                  mTokenName = scepConfig.getString("tokenname", "");
                  mUseCA = false;
              }
              if (!(mTokenName.equalsIgnoreCase(Constants.PR_INTERNAL_TOKEN) ||
                    mTokenName.equalsIgnoreCase("Internal Key Storage Token") ||
                    mTokenName.length() == 0)) {
                  int i = mNickname.indexOf(':');
                  if (!((i > -1) && (mTokenName.length() == i) && (mNickname.startsWith(mTokenName)))) {
                      mNickname = mTokenName + ":" + mNickname;
                  }
              }
          }
      } catch (EBaseException e) {
          CMS.debug("CRSEnrollment: init: EBaseException: "+e);
      } 
      mEncryptionAlgorithm = mConfiguredEncryptionAlgorithm;
      CMS.debug("CRSEnrollment: init: SCEP support is "+((mEnabled)?"enabled":"disabled")+".");
      CMS.debug("CRSEnrollment: init: SCEP nickname: "+mNickname);
      CMS.debug("CRSEnrollment: init:   CA nickname: "+ca.getNickname());
      CMS.debug("CRSEnrollment: init:    Token name: "+mTokenName);
      CMS.debug("CRSEnrollment: init: Is SCEP using CA keys: "+mUseCA);
      CMS.debug("CRSEnrollment: init: mNonceSizeLimit: "+mNonceSizeLimit);
      CMS.debug("CRSEnrollment: init: mHashAlgorithm: "+mHashAlgorithm);
      CMS.debug("CRSEnrollment: init: mHashAlgorithmList: "+mHashAlgorithmList);
      for (int i = 0; i < mAllowedHashAlgorithm.length; i++) {
          mAllowedHashAlgorithm[i] = mAllowedHashAlgorithm[i].trim();
          CMS.debug("CRSEnrollment: init: mAllowedHashAlgorithm["+i+"]="+mAllowedHashAlgorithm[i]);
      }
      CMS.debug("CRSEnrollment: init: mEncryptionAlgorithm: "+mEncryptionAlgorithm);
      CMS.debug("CRSEnrollment: init: mEncryptionAlgorithmList: "+mEncryptionAlgorithmList);
      for (int i = 0; i < mAllowedEncryptionAlgorithm.length; i++) {
          mAllowedEncryptionAlgorithm[i] = mAllowedEncryptionAlgorithm[i].trim();
          CMS.debug("CRSEnrollment: init: mAllowedEncryptionAlgorithm["+i+"]="+mAllowedEncryptionAlgorithm[i]);
      }

      try {
	      mProfileSubsystem = (IProfileSubsystem)CMS.getSubsystem("profile");
          mProfileId  = sc.getInitParameter("profileId");
          CMS.debug("CRSEnrollment: init: mProfileId="+mProfileId);

	      mAuthSubsystem   = (IAuthSubsystem)CMS.getSubsystem(CMS.SUBSYSTEM_AUTH);
          mAuthManagerName  = sc.getInitParameter(PROP_CRSAUTHMGR);
          mAppendDN         = sc.getInitParameter(PROP_APPENDDN);
		  String tmp = sc.getInitParameter(PROP_CREATEENTRY);
		  if (tmp != null && tmp.trim().equalsIgnoreCase("true"))
			  mCreateEntry = true;
		  else
			  mCreateEntry = false;
		  tmp = sc.getInitParameter(PROP_FLATTENDN);
		  if (tmp != null && tmp.trim().equalsIgnoreCase("true"))
			  mFlattenDN = true;
		  else
			  mFlattenDN = false;
          mEntryObjectclass = sc.getInitParameter(PROP_ENTRYOC);
		  if (mEntryObjectclass == null)
			  mEntryObjectclass = "cep";
          mSubstoreName = sc.getInitParameter(PROP_SUBSTORENAME);
		  if (mSubstoreName == null)
			  mSubstoreName = "default";
      } catch (Exception e) {
      } 

      OID_UNSTRUCTUREDNAME    = X500NameAttrMap.getDefault().getOid("UNSTRUCTUREDNAME");
      OID_UNSTRUCTUREDADDRESS = X500NameAttrMap.getDefault().getOid("UNSTRUCTUREDADDRESS");
      OID_SERIALNUMBER        = X500NameAttrMap.getDefault().getOid("SERIALNUMBER");


	try {
      mSHADigest = MessageDigest.getInstance("SHA1");
    }
    catch (NoSuchAlgorithmException e) {
      }

      mRandom = new Random();
  }


  /**
   *
   * Service a CRS Request. It all starts here. This is where the message from the
   * router is processed
   *
   * @param httpReq     The HttpServletRequest.
   * @param httpResp    The HttpServletResponse.
   *
   */
  public void service(HttpServletRequest httpReq,
                      HttpServletResponse httpResp)
    throws ServletException
    {
		boolean running_state = CMS.isInRunningState();
		if (!running_state)
			throw new ServletException(
				"CMS server is not ready to serve.");

        String operation = null;
        String message   = null;
        mEncryptionAlgorithm = mConfiguredEncryptionAlgorithm;
        
      
        // Parse the URL from the HTTP Request. Split it up into
        // a structure which enables us to read the form elements
        IArgBlock input = CMS.createArgBlock(toHashtable(httpReq));
        
        try {            
            // Read in two form parameters - the router sets these
            operation = (String)input.get(URL_OPERATION);
            CMS.debug("operation=" + operation);
            message   = (String)input.get(URL_MESSAGE);
            CMS.debug("message=" + message);
            
            if (!mEnabled) {
                CMS.debug("CRSEnrollment: SCEP support is disabled.");
                throw new ServletException("SCEP support is disabled.");
            }
            if (operation == null) {
                // 'operation' is mandatory.
                throw new ServletException("Bad request: operation missing from URL");
            }
            
            /** 
             *  the router can make two kinds of requests
             *  1) simple request for CA cert
             *  2) encoded, signed, enveloped request for anything else (PKIOperation)
             */
            
            if (operation.equals(OP_GETCACERT)) {
                handleGetCACert(httpReq, httpResp);  
            }
            else if (operation.equals(OP_PKIOPERATION)) {
                String decodeMode   = (String)input.get("decode");
                if (decodeMode == null || decodeMode.equals("false")) {
                  handlePKIOperation(httpReq, httpResp, message);
                } else {
                  decodePKIMessage(httpReq, httpResp, message);
                }
            }
            else {
                CMS.debug("Invalid operation " + operation);
                throw new ServletException("unknown operation requested: "+operation);
            }
                    
        }
        catch (ServletException e)
        {
            CMS.debug("ServletException " + e);
            throw new ServletException(e.getMessage().toString());
        }
        catch (Exception e)
            {
                CMS.debug("Service exception " + e);
                log(ILogger.LL_FAILURE,e.getMessage());
            }
        
    }

    /**
     *  Log a message to the system log
     */


    private void log(int level, String msg) {
        
        mLogger.log(ILogger.EV_SYSTEM, ILogger.S_OTHER,
                    level, "CEP Enrollment: "+msg);
    }

    private boolean isAlgorithmAllowed (String[] allowedAlgorithm, String algorithm) {
        boolean allowed = false;

        if (algorithm != null && algorithm.length() > 0) {
            for (int i = 0; i < allowedAlgorithm.length; i++) {
                if (algorithm.equalsIgnoreCase(allowedAlgorithm[i])) {
                    allowed = true;
                }
            }
        }

        return allowed;
    }

    public IAuthToken authenticate(AuthCredentials credentials, IProfileAuthenticator authenticator,
        HttpServletRequest request)  throws EBaseException {

        // build credential
        Enumeration authNames = authenticator.getValueNames();

        if (authNames != null) {
            while (authNames.hasMoreElements()) {
                String authName = (String) authNames.nextElement();

                credentials.set(authName, request.getParameter(authName));
            }
        }

        credentials.set("clientHost", request.getRemoteHost());
        IAuthToken authToken = authenticator.authenticate(credentials);
        if (authToken == null) {
          return null;
        }
        SessionContext sc = SessionContext.getContext();
        if (sc != null) {
          sc.put(SessionContext.AUTH_MANAGER_ID, authenticator.getName());
          String userid = authToken.getInString(IAuthToken.USER_ID);
          if (userid != null) {
            sc.put(SessionContext.USER_ID, userid);
          }
        }

        return authToken;
    }

  /**
   *  Return the CA certificate back to the requestor.
   *  This needs to be changed so that if the CA has a certificate chain,
   *  the whole thing should get packaged as a PKIMessage (degnerate PKCS7 - no
   *  signerInfo)
   */
    
  public void handleGetCACert(HttpServletRequest httpReq,
                              HttpServletResponse httpResp) 
    throws ServletException {
      java.security.cert.X509Certificate[]  chain = null;

      CertificateChain certChain = mAuthority.getCACertChain();
        
      try {
          if (certChain == null) {
              throw new ServletException("Internal Error: cannot get CA Cert");
          }

          chain = certChain.getChain();
        
          byte[] bytes = null;
		  
          int i = 0;
          String message   = (String)httpReq.getParameter(URL_MESSAGE);
          CMS.debug("handleGetCACert message=" + message);
          if (message != null) {
            try {
              int j = Integer.parseInt(message);
              if (j < chain.length) {
                i = j;
              }
            } catch (NumberFormatException e1) {
            }
          }
          CMS.debug("handleGetCACert selected chain=" + i);

          if (mUseCA) {
              bytes = chain[i].getEncoded();
          } else {
              CryptoContext cx = new CryptoContext();
              bytes = cx.getSigningCert().getEncoded();
          }

          httpResp.setContentType("application/x-x509-ca-cert");


// The following code may be used one day to encode
// the RA/CA cert chain for RA mode, but it will need some
// work.

  /******
              SET certs  = new SET();
              for (int i=0; i<chain.length; i++) {
                  ANY cert   = new ANY(chain[i].getEncoded());
                  certs.addElement(cert);
              }

              SignedData crsd  = new SignedData(
                      new SET(),         // empty set of digestAlgorithmID's
                      new ContentInfo(
                      new OBJECT_IDENTIFIER(new long[] {1,2,840,113549,1,7,1}),
                                             null), //empty content
                      certs,
                      null,     // no CRL's
                      new SET() // empty SignerInfos
                      );

              ContentInfo wrap = new ContentInfo(ContentInfo.SIGNED_DATA, crsd);

              ByteArrayOutputStream baos = new ByteArrayOutputStream();
              wrap.encode(baos);

              bytes = baos.toByteArray();

              httpResp.setContentType("application/x-x509-ca-ra-cert");
  *****/ 

          httpResp.setContentLength(bytes.length);
          httpResp.getOutputStream().write(bytes);
          httpResp.getOutputStream().flush();

          CMS.debug("Output certificate chain:");
          CMS.debug(bytes);
      }
      catch (Exception e) {
          CMS.debug("handleGetCACert exception " + e);
          log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ERROR_SENDING_DER_ENCODE_CERT",e.getMessage()));
          throw new ServletException("Failed sending DER encoded version of CA cert to client");
      }

  }
    
  public String getPasswordFromP10(PKCS10 p10) 
  {
     PKCS10Attributes p10atts = p10.getAttributes();
     Enumeration e = p10atts.getElements();
              
     try {
       while (e.hasMoreElements()) {
         PKCS10Attribute p10a = (PKCS10Attribute)e.nextElement();
         CertAttrSet attr = p10a.getAttributeValue();

         if (attr.getName().equals(ChallengePassword.NAME)) {
           if (attr.get(ChallengePassword.PASSWORD) != null) {
             return (String)attr.get(ChallengePassword.PASSWORD);
           }
         }
       }
     } catch(Exception e1) {
       // do nothing
     }
     return null;
  }

  /**
   *  If the 'operation' is 'PKIOperation', the 'message' part of the URL is a
   *  PKIMessage structure. We decode it to see what type message it is.
   */

  /**
   * Decodes the PKI message and return information to RA.
   */
  public void decodePKIMessage(HttpServletRequest httpReq,
                                 HttpServletResponse httpResp,
                                 String msg)
    throws ServletException {

      CryptoContext cx=null;

      CRSPKIMessage req=null;
        
      byte[] decodedPKIMessage;
      byte[] response=null;
      String responseData = "";
        
      decodedPKIMessage = com.netscape.osutil.OSUtil.AtoB(msg);
            
      try {
          ByteArrayInputStream is = new ByteArrayInputStream(decodedPKIMessage);

          // We make two CRSPKIMessages. One of them, is the request, so we initialize
          // it from the DER given to us from the router.
          // The second is the response, and we'll fill this in as we go.

          if (decodedPKIMessage.length < 50) {
		  	throw new ServletException("CRS request is too small to be a real request ("+
				decodedPKIMessage.length+" bytes)");
			}
		  try {
          	req = new CRSPKIMessage(is);
          	String ea = req.getEncryptionAlgorithm();
            if (!isAlgorithmAllowed (mAllowedEncryptionAlgorithm, ea)) {
                CMS.debug("CRSEnrollment: decodePKIMessage:  Encryption algorithm '"+ea+
                          "' is not allowed ("+mEncryptionAlgorithmList+").");
                throw new ServletException("Encryption algorithm '"+ea+
                                           "' is not allowed ("+mEncryptionAlgorithmList+").");
            }
          	String da = req.getDigestAlgorithmName();
            if (!isAlgorithmAllowed (mAllowedHashAlgorithm, da)) {
                CMS.debug("CRSEnrollment: decodePKIMessage:  Hashing algorithm '"+da+
                          "' is not allowed ("+mHashAlgorithmList+").");
                throw new ServletException("Hashing algorithm '"+da+
                                           "' is not allowed ("+mHashAlgorithmList+").");
            }
          	if (ea != null) {
          	    mEncryptionAlgorithm = ea;
          	}
		  }
		  catch (Exception e) {
            CMS.debug(e);
		  	throw new ServletException("Could not decode the request.");
		  }
                
          // Create a new crypto context for doing all the crypto operations
          cx = new CryptoContext();

          // Verify Signature on message (throws exception if sig bad)
          verifyRequest(req,cx);
          unwrapPKCS10(req,cx);

          IProfile profile = mProfileSubsystem.getProfile(mProfileId);
          if (profile == null) {
              CMS.debug("Profile '" + mProfileId + "' not found.");
              throw new ServletException("Profile '" + mProfileId + "' not found.");
          } else {
              CMS.debug("Found profile '" + mProfileId + "'.");
          }

          IProfileAuthenticator authenticator = null;
          try {
              CMS.debug("Retrieving authenticator");
              authenticator = profile.getAuthenticator();
              if (authenticator == null) {
                  CMS.debug("Authenticator not found.");
                  throw new ServletException("Authenticator not found.");
              } else {
                  CMS.debug("Got authenticator=" + authenticator.getClass().getName());
              }
          } catch (EProfileException e) {
              throw new ServletException("Authenticator not found.");
          }
          AuthCredentials credentials = new AuthCredentials();
          IAuthToken authToken = null;
          // for ssl authentication; pass in servlet for retrieving
          // ssl client certificates
          SessionContext context = SessionContext.getContext();

          // insert profile context so that input parameter can be retrieved
          context.put("sslClientCertProvider", new SSLClientCertProvider(httpReq));

          try {
              authToken = authenticate(credentials, authenticator, httpReq);
          } catch (Exception e) {
              CMS.debug("Authentication failure: "+ e.getMessage());
              throw new ServletException("Authentication failure: "+ e.getMessage());
          }
          if (authToken == null) {
              CMS.debug("Authentication failure.");
              throw new ServletException("Authentication failure.");
          }

          // Deal with Transaction ID
          String transactionID = req.getTransactionID();
          responseData = responseData + 
              "<TransactionID>" + transactionID + "</TransactionID>";

          // End-User or RA's IP address
          responseData = responseData + 
              "<RemoteAddr>" + httpReq.getRemoteAddr() + "</RemoteAddr>";

          responseData = responseData + 
              "<RemoteHost>" + httpReq.getRemoteHost() + "</RemoteHost>";
                
          // Deal with Nonces
          byte[] sn = req.getSenderNonce();
                
          // Deal with message type
          String mt = req.getMessageType();
          responseData = responseData + 
              "<MessageType>" + mt + "</MessageType>";

          PKCS10 p10 = (PKCS10)req.getP10();
          X500Name p10subject      = p10.getSubjectName();
          responseData = responseData + 
              "<SubjectName>" + p10subject.toString() + "</SubjectName>";

          String pkcs10Attr = "";
              PKCS10Attributes p10atts = p10.getAttributes();
              Enumeration e = p10atts.getElements();
              
              while (e.hasMoreElements()) {
                  PKCS10Attribute p10a = (PKCS10Attribute)e.nextElement();
                  CertAttrSet attr = p10a.getAttributeValue();


                  if (attr.getName().equals(ChallengePassword.NAME)) {
					  if (attr.get(ChallengePassword.PASSWORD) != null) {
                                pkcs10Attr = pkcs10Attr + 
                                         "<ChallengePassword><Password>" + (String)attr.get(ChallengePassword.PASSWORD) + "</Password></ChallengePassword>";
                      }
                  
                  }
                  String extensionsStr = "";
                  if (attr.getName().equals(ExtensionsRequested.NAME)) {

					Enumeration exts = ((ExtensionsRequested)attr).getExtensions().elements();
					while (exts.hasMoreElements()) {
						Extension ext = (Extension) exts.nextElement();

						if (ext.getExtensionId().equals(
							OIDMap.getOID(SubjectAlternativeNameExtension.IDENT)) ) {
							DerOutputStream dos = new DerOutputStream();
							SubjectAlternativeNameExtension sane = new SubjectAlternativeNameExtension(
									Boolean.valueOf(false),  // noncritical
									ext.getExtensionValue());

								
							Vector v = 
                              (Vector) sane.get(SubjectAlternativeNameExtension. SUBJECT_NAME);

							Enumeration gne = v.elements();

                            StringBuffer subjAltNameStr = new StringBuffer();
							while (gne.hasMoreElements()) {
								GeneralNameInterface gni = (GeneralNameInterface) gne.nextElement();
								if (gni instanceof GeneralName) {
									GeneralName genName = (GeneralName) gni;

									String gn = genName.toString();
									int colon = gn.indexOf(':');
									String gnType = gn.substring(0,colon).trim();
									String gnValue = gn.substring(colon+1).trim();

                                    subjAltNameStr.append("<");
                                    subjAltNameStr.append(gnType);
                                    subjAltNameStr.append(">");
                                    subjAltNameStr.append(gnValue);
                                    subjAltNameStr.append("</");
                                    subjAltNameStr.append(gnType);
                                    subjAltNameStr.append(">");
								}
							} // while
                            extensionsStr = "<SubjAltName>" +
                                 subjAltNameStr.toString() + "</SubjAltName>";
						} // if
					} // while
                    pkcs10Attr = pkcs10Attr + 
                                         "<Extensions>" + extensionsStr + "</Extensions>";
				} // if extensions
              } // while
          responseData = responseData + 
              "<PKCS10>" + pkcs10Attr + "</PKCS10>";

      } catch (ServletException e) {
          throw new ServletException(e.getMessage().toString());
      } catch (CRSInvalidSignatureException e) {
          CMS.debug("handlePKIMessage exception " + e);
          CMS.debug(e);
      } catch (Exception e) {
          CMS.debug("handlePKIMessage exception " + e);
          CMS.debug(e);
          throw new ServletException("Failed to process message in CEP servlet: "+ e.getMessage());
      }

      // We have now processed the request, and need to make the response message
      
      try {   

          responseData = "<XMLResponse>" + responseData + "</XMLResponse>";
          // Get the response coding
          response = responseData.getBytes();
            
          // Encode the httpResp into B64
          httpResp.setContentType("application/xml");
          httpResp.setContentLength(response.length);
          httpResp.getOutputStream().write(response);
          httpResp.getOutputStream().flush();

          int i1 = responseData.indexOf("<Password>");
          if (i1 > -1) {
              i1 += 10; // 10 is a length of "<Password>"
              int i2 = responseData.indexOf("</Password>", i1);
              if (i2 > -1) {
                  responseData = responseData.substring(0, i1) + "********" +
                                 responseData.substring(i2, responseData.length());
              }
          }

          CMS.debug("Output (decoding) PKIOperation response:");
          CMS.debug(responseData);
      }
      catch (Exception e) {
          throw new ServletException("Failed to create response for CEP message"+e.getMessage());
      }

  }
    
  
  /**
   *   finds a request with this transaction ID.
   *   If could not find any request - return null
   *   If could only find 'rejected' or 'cancelled' requests, return null
   *   If found 'pending' or 'completed' request - return that request
   */
    
    
  public void handlePKIOperation(HttpServletRequest httpReq,
                                 HttpServletResponse httpResp,
                                 String msg)
    throws ServletException {


      CryptoContext cx=null;

      CRSPKIMessage req=null;
      CRSPKIMessage crsResp=null;
        
      byte[] decodedPKIMessage;
      byte[] response=null;
      X509CertImpl cert = null;
        
      decodedPKIMessage = com.netscape.osutil.OSUtil.AtoB(msg);
            
      try {
          ByteArrayInputStream is = new ByteArrayInputStream(decodedPKIMessage);

          // We make two CRSPKIMessages. One of them, is the request, so we initialize
          // it from the DER given to us from the router.
          // The second is the response, and we'll fill this in as we go.

          if (decodedPKIMessage.length < 50) {
		  	throw new ServletException("CRS request is too small to be a real request ("+
				decodedPKIMessage.length+" bytes)");
			}
		  try {
          	req = new CRSPKIMessage(is);
          	String ea = req.getEncryptionAlgorithm();
            if (!isAlgorithmAllowed (mAllowedEncryptionAlgorithm, ea)) {
                CMS.debug("CRSEnrollment: handlePKIOperation:  Encryption algorithm '"+ea+
                          "' is not allowed ("+mEncryptionAlgorithmList+").");
                throw new ServletException("Encryption algorithm '"+ea+
                                           "' is not allowed ("+mEncryptionAlgorithmList+").");
            }
          	String da = req.getDigestAlgorithmName();
            if (!isAlgorithmAllowed (mAllowedHashAlgorithm, da)) {
                CMS.debug("CRSEnrollment: handlePKIOperation:  Hashing algorithm '"+da+
                          "' is not allowed ("+mHashAlgorithmList+").");
                throw new ServletException("Hashing algorithm '"+da+
                                           "' is not allowed ("+mHashAlgorithmList+").");
            }
          	if (ea != null) {
          	    mEncryptionAlgorithm = ea;
          	}
          	crsResp = new CRSPKIMessage();
		  }
          catch (ServletException e) {
              throw new ServletException(e.getMessage().toString());
          }
		  catch (Exception e) {
            CMS.debug(e);
		  	throw new ServletException("Could not decode the request.");
		  }
		  crsResp.setMessageType(crsResp.mType_CertRep);
                
          // Create a new crypto context for doing all the crypto operations
          cx = new CryptoContext();

          // Verify Signature on message (throws exception if sig bad)
          verifyRequest(req,cx);
                
          // Deal with Transaction ID
          String transactionID = req.getTransactionID();
          if (transactionID == null) {
              throw new ServletException("Error: malformed PKIMessage - missing transactionID");
          }
          else {
              crsResp.setTransactionID(transactionID);
          }
                
          // Deal with Nonces
          byte[] sn = req.getSenderNonce();
          if (sn == null) {
              throw new ServletException("Error: malformed PKIMessage - missing sendernonce");
          }
          else {
              if (mNonceSizeLimit > 0 && sn.length > mNonceSizeLimit) {
                  byte[] snLimited = (mNonceSizeLimit > 0)? new byte[mNonceSizeLimit]: null;
                  System.arraycopy(sn, 0, snLimited, 0, mNonceSizeLimit);
                  crsResp.setRecipientNonce(snLimited);
              } else {
                  crsResp.setRecipientNonce(sn);
              }
              byte[] serverNonce = new byte[16];
              mRandom.nextBytes(serverNonce);
              crsResp.setSenderNonce(serverNonce);
              // crsResp.setSenderNonce(new byte[] {0});
          }
                
          // Deal with message type
          String mt = req.getMessageType();
          if (mt == null) {
              throw new ServletException("Error: malformed PKIMessage - missing messageType");
          }

          // now run appropriate code, depending on message type
          if (mt.equals(req.mType_PKCSReq)) {
              CMS.debug("Processing PKCSReq");
              try {
                // Check if there is an existing request. If this returns non-null,
				// then the request is 'active' (either pending or completed) in 
				// which case, we compare the hash of the new request to the hash of the
                // one in the queue - if they are the same, I return the state of the 
                // original request - as if it was 'getCertInitial' message.
                // If the hashes are different, then the user attempted to enroll
                // for a new request with the same txid, which is not allowed - 
                // so we return 'failure'.

				IRequest cmsRequest= findRequestByTransactionID(req.getTransactionID(),true);

                // If there was no request (with a cert) with this transaction ID, 
                // process it as a new request

                cert = handlePKCSReq(httpReq, cmsRequest,req,crsResp,cx);
                
              }
              catch (CRSFailureException e) {
                  throw new ServletException("Couldn't handle CEP request (PKCSReq) - "+e.getMessage());
              }
          }
          else if (mt.equals(req.mType_GetCertInitial)) {
              CMS.debug("Processing GetCertInitial");
              cert = handleGetCertInitial(req,crsResp);
          } else {
              CMS.debug("Invalid request type " + mt);
          }
      }
      catch (ServletException e) {
          throw new ServletException(e.getMessage().toString());
      }
      catch (CRSInvalidSignatureException e) {
          CMS.debug("handlePKIMessage exception " + e);
          CMS.debug(e);
          crsResp.setFailInfo(crsResp.mFailInfo_badMessageCheck);
      }
      catch (Exception e) {
          CMS.debug("handlePKIMessage exception " + e);
          CMS.debug(e);
          throw new ServletException("Failed to process message in CEP servlet: "+ e.getMessage());
      }

      // We have now processed the request, and need to make the response message
      
      try {   
          // make the response
          processCertRep(cx, cert,crsResp, req);

          // Get the response coding
          response = crsResp.getResponse();
            
          // Encode the crsResp into B64
          httpResp.setContentType("application/x-pki-message");
          httpResp.setContentLength(response.length);
          httpResp.getOutputStream().write(response);
          httpResp.getOutputStream().flush();

          CMS.debug("Output PKIOperation response:");
          CMS.debug(CMS.BtoA(response));
      }
      catch (Exception e) {
          throw new ServletException("Failed to create response for CEP message"+e.getMessage());
      }

  }
    
  
  /**
   *   finds a request with this transaction ID.
   *   If could not find any request - return null
   *   If could only find 'rejected' or 'cancelled' requests, return null
   *   If found 'pending' or 'completed' request - return that request
   */
    
  public IRequest findRequestByTransactionID(String txid, boolean ignoreRejected)
    throws EBaseException {

      /* Check if certificate request has been completed */
        
      IRequestQueue rq  = ca.getRequestQueue();
      IRequest foundRequest = null;

      Enumeration rids    = rq.findRequestsBySourceId(txid);
	  if (rids == null) { return null; }

      int count=0;
      while (rids.hasMoreElements()) {
			RequestId rid = (RequestId) rids.nextElement();
			if (rid == null) {
				continue;
			}
			
      		IRequest request = rq.findRequest(rid);
			if (request == null) {
				continue;
			}
			if ( !ignoreRejected || 
				request.getRequestStatus().equals(RequestStatus.PENDING) ||
			    request.getRequestStatus().equals(RequestStatus.COMPLETE)) {
				if (foundRequest != null) {
				}
			foundRequest = request;
			}
		}
	 return foundRequest;
  }
    
  /** 
   *  Called if the router is requesting us to send it its certificate
   *  Examine request queue for a request matching the transaction ID.
   *  Ignore any rejected or cancelled requests.
   *
   *  If a request is found in the pending state, the response should be
   *  'pending'
   *
   *  If a request is found in the completed state, the response should be
   *  to return the certificate
   *
   *  If no request is found, the response should be to return null
   *
   */

  public X509CertImpl handleGetCertInitial(CRSPKIMessage req,CRSPKIMessage resp) 
  {
      IRequest foundRequest=null;

      // already done by handlePKIOperation
      // resp.setRecipientNonce(req.getSenderNonce());
      // resp.setSenderNonce(null);

	  try {
	  	foundRequest = findRequestByTransactionID(req.getTransactionID(),false);
	  } catch (EBaseException e) {
      }

	  if (foundRequest == null) {
	  	resp.setFailInfo(resp.mFailInfo_badCertId);
	  	resp.setPKIStatus(resp.mStatus_FAILURE);
		return null;
	  }

      return makeResponseFromRequest(req,resp,foundRequest);
  }


  public void verifyRequest(CRSPKIMessage req, CryptoContext cx)     
    throws  CRSInvalidSignatureException {

      // Get Signed Data
      
      byte[] reqAAbytes = req.getAA();
      byte[] reqAAsig = req.getAADigest();
        
  }


  /**
   *  Create an entry for this user in the publishing directory
   *
   */

   private boolean createEntry(String dn)
   {
      boolean result = false;

      IPublisherProcessor ldapPub = mAuthority.getPublisherProcessor();
      if (ldapPub == null || !ldapPub.enabled()) {
          log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ERROR_CREATE_ENTRY_FROM_CEP")); 

          return result;
      }

      ILdapConnFactory connFactory = ((IPublisherProcessor)ldapPub).getLdapConnModule().getLdapConnFactory();
      if (connFactory == null) {
          return result;
      }

      LDAPConnection connection=null;
      try {
         connection = connFactory.getConn();
         String[] objectclasses = { "top", mEntryObjectclass };
         LDAPAttribute ocAttrs = new LDAPAttribute("objectclass",objectclasses);

         LDAPAttributeSet attrSet = new LDAPAttributeSet();
         attrSet.add(ocAttrs);

         LDAPEntry newEntry = new LDAPEntry(dn, attrSet);
         connection.add(newEntry);
         result=true;
      }
      catch (Exception e) {
          log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_FAIL_CREAT_ENTRY_EXISTS",dn));
      }
      finally {
          try {
             connFactory.returnConn(connection);
          }
          catch (Exception f) {}
      }
      return result;
    }



  /**
   *  Here we decrypt the PKCS10 message from the client
   *
   */
    
  public void unwrapPKCS10(CRSPKIMessage req, CryptoContext cx)
    throws   ServletException, 
             CryptoManager.NotInitializedException,
			 CryptoContext.CryptoContextException,
             CRSFailureException {
        
      byte[] decryptedP10bytes = null;
      SymmetricKey sk;
      SymmetricKey skinternal;
      SymmetricKey.Type skt;
      KeyWrapper kw;
      Cipher cip;
      EncryptionAlgorithm ea;
      boolean errorInRequest = false;

      // Unwrap the session key with the Cert server key
	try {
      kw = cx.getKeyWrapper();

      kw.initUnwrap(cx.getPrivateKey(),null);

      skt = SymmetricKey.Type.DES;
      ea = EncryptionAlgorithm.DES_CBC;
      if (mEncryptionAlgorithm != null && mEncryptionAlgorithm.equals("DES3")) {
          skt = SymmetricKey.Type.DES3;
          ea = EncryptionAlgorithm.DES3_CBC;
      }

      sk = kw.unwrapSymmetric(req.getWrappedKey(),
                              skt,
                              SymmetricKey.Usage.DECRYPT,
                              0);  // keylength is ignored
          
     skinternal = cx.getDESKeyGenerator().clone(sk);
          
     cip = skinternal.getOwningToken().getCipherContext(ea);
          
     cip.initDecrypt(skinternal,(new IVParameterSpec(req.getIV())));
        
     decryptedP10bytes = cip.doFinal(req.getEncryptedPkcs10());
     CMS.debug("decryptedP10bytes:");
     CMS.debug(decryptedP10bytes);
          
     req.setP10(new PKCS10(decryptedP10bytes));
     } catch (Exception e) {
        CMS.debug("failed to unwrap PKCS10 " + e);
		throw new CRSFailureException("Could not unwrap PKCS10 blob: "+e.getMessage());
     }
          
  }



private void getDetailFromRequest(CRSPKIMessage req, CRSPKIMessage crsResp)
  throws CRSFailureException {

      IRequest issueReq = null;
      X509CertImpl issuedCert=null;
      Vector extensionsRequested = null;
      SubjectAlternativeNameExtension sane = null;
      CertAttrSet requested_ext = null;

      try {
             PKCS10 p10 = (PKCS10)req.getP10();

             if (p10 == null) {
			     crsResp.setFailInfo(crsResp.mFailInfo_badMessageCheck);
		  	     crsResp.setPKIStatus(crsResp.mStatus_FAILURE);
			     throw new CRSFailureException("Failed to decode pkcs10 from CEP request");
		      }
                
              AuthCredentials authCreds = new AuthCredentials();

              String challengePassword = null;
              // Here, we make a new CertInfo - it's a new start for a certificate
                    
              X509CertInfo certInfo = CMS.getDefaultX509CertInfo();
                
              // get some stuff out of the request
              X509Key key              = p10.getSubjectPublicKeyInfo();
              X500Name p10subject      = p10.getSubjectName();

              X500Name subject=null;

              // The following code will copy all the attributes
			  // into the AuthCredentials so they can be used for
			  // authentication
			  //
			  // Optionally, you can re-map the subject name from:
              //   one RDN, with many AVA's    to
              //   many RDN's with one AVA in each.

              Enumeration rdne     = p10subject.getRDNs();
              Vector      rdnv = new Vector();

			  Hashtable sanehash = new Hashtable();

              X500NameAttrMap xnap = X500NameAttrMap.getDefault();
              while (rdne.hasMoreElements()) {
                  RDN rdn = (RDN) rdne.nextElement();
                  int i=0;
                  AVA[] oldavas = rdn.getAssertion();
                  for (i=0; i<rdn.getAssertionLength(); i++) {
                      AVA[] newavas = new AVA[1];
                      newavas[0]    = oldavas[i];
					  
				      authCreds.set(xnap.getName(oldavas[i].getOid()),
					        oldavas[i].getValue().getAsString());
					  
					  if (oldavas[i].getOid().equals(OID_UNSTRUCTUREDNAME)) {
						
						  sanehash.put(SANE_DNSNAME,oldavas[i].getValue().getAsString());
					  }	
					  if (oldavas[i].getOid().equals(OID_UNSTRUCTUREDADDRESS)) {
						  sanehash.put(SANE_IPADDRESS,oldavas[i].getValue().getAsString());
					  }	

                      RDN newrdn    = new RDN(newavas);
					  if (mFlattenDN) {
                          rdnv.addElement(newrdn);
                      }
                  }
              }

              if (mFlattenDN) subject  = new X500Name(rdnv);
              else subject = p10subject;

                
				// create default key usage extension
              KeyUsageExtension kue = new KeyUsageExtension();
              kue.set(KeyUsageExtension.DIGITAL_SIGNATURE, Boolean.valueOf(true));
              kue.set(KeyUsageExtension.KEY_ENCIPHERMENT, Boolean.valueOf(true));


              PKCS10Attributes p10atts = p10.getAttributes();
              Enumeration e = p10atts.getElements();
              
              while (e.hasMoreElements()) {
                  PKCS10Attribute p10a = (PKCS10Attribute)e.nextElement();
                  CertAttrSet attr = p10a.getAttributeValue();


                  if (attr.getName().equals(ChallengePassword.NAME)) {
					  if (attr.get(ChallengePassword.PASSWORD) != null) {
		              		req.put(AUTH_PASSWORD,
									(String)attr.get(ChallengePassword.PASSWORD));
		              		req.put(ChallengePassword.NAME,
                           		hashPassword(
									(String)attr.get(ChallengePassword.PASSWORD)));
							}
                      }
                  
                  if (attr.getName().equals(ExtensionsRequested.NAME)) {

					Enumeration exts = ((ExtensionsRequested)attr).getExtensions().elements();
					while (exts.hasMoreElements()) {
						Extension ext = (Extension) exts.nextElement();

						if (ext.getExtensionId().equals(
							OIDMap.getOID(KeyUsageExtension.IDENT)) ) {
							
							kue = new KeyUsageExtension(
									new Boolean(false), // noncritical
									ext.getExtensionValue());
						}

						if (ext.getExtensionId().equals(
							OIDMap.getOID(SubjectAlternativeNameExtension.IDENT)) ) {
							DerOutputStream dos = new DerOutputStream();
							sane = new SubjectAlternativeNameExtension(
									new Boolean(false),  // noncritical
									ext.getExtensionValue());

								
							Vector v = 
                              (Vector) sane.get(SubjectAlternativeNameExtension. SUBJECT_NAME);

							Enumeration gne = v.elements();

							while (gne.hasMoreElements()) {
								GeneralNameInterface gni = (GeneralNameInterface) gne.nextElement();
								if (gni instanceof GeneralName) {
									GeneralName genName = (GeneralName) gni;

									String gn = genName.toString();
									int colon = gn.indexOf(':');
									String gnType = gn.substring(0,colon).trim();
									String gnValue = gn.substring(colon+1).trim();

				      				authCreds.set(gnType,gnValue);
								}
							}
						}
					}
                  }
              }

			  if (authCreds != null) req.put(AUTH_CREDS,authCreds);

			try {
			  if (sane == null)  sane = makeDefaultSubjectAltName(sanehash);
			} catch (Exception sane_e) {
				log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ENROLL_FAIL_NO_SUBJ_ALT_NAME",
						sane_e.getMessage()));
			}
				
                    

		  try {
              if (mAppendDN != null && ! mAppendDN.equals("")) {

				  X500Name newSubject = new X500Name(subject.toString());
                  subject = new X500Name( subject.toString().concat(","+mAppendDN));
              }

		  } catch (Exception sne) {
	     	log(ILogger.LL_INFO, "Unable to use appendDN parameter: "+mAppendDN+". Error is "+sne.getMessage()+" Using unmodified subjectname");
		  }

			  if (subject != null) req.put(SUBJECTNAME, subject);

              if (key == null || subject == null) {
                  // log 
                  //throw new ERegistrationException(RegistrationResources.ERROR_MALFORMED_P10);
              }



              certInfo.set(X509CertInfo.VERSION,
                           new CertificateVersion(CertificateVersion.V3));
                    
              certInfo.set(X509CertInfo.SUBJECT,
                           new CertificateSubjectName(subject));
                    
              certInfo.set(X509CertInfo.KEY,
                           new CertificateX509Key(key));
              
              CertificateExtensions ext = new CertificateExtensions();

              if (kue != null) {
                  ext.set(KeyUsageExtension.NAME, kue);
              }

              // add subjectAltName extension, if present
              if (sane != null) {
                  ext.set(SubjectAlternativeNameExtension.NAME, sane);
              }

              certInfo.set(X509CertInfo.EXTENSIONS,ext);

			  req.put(CERTINFO, certInfo);
      } catch (Exception e) {
	     crsResp.setFailInfo(crsResp.mFailInfo_badMessageCheck);
	     crsResp.setPKIStatus(crsResp.mStatus_FAILURE);
	     return ;
	  }   // NEED TO FIX
  }
                  

  private SubjectAlternativeNameExtension makeDefaultSubjectAltName(Hashtable ht) {

    // if no subjectaltname extension was requested, we try to make it up
    // from some of the elements of the subject name

	int itemCount = ht.size();
	GeneralNameInterface[] gn = new GeneralNameInterface[ht.size()];

	itemCount = 0;
	Enumeration en = ht.keys();
    while (en.hasMoreElements()) {
		String key = (String) en.nextElement();
		if (key.equals(SANE_DNSNAME)) {
			gn[itemCount++] = new DNSName((String)ht.get(key));
		}
		if (key.equals(SANE_IPADDRESS)) {
			gn[itemCount++] = new IPAddressName((String)ht.get(key));
        }
    }

	try {
		return new SubjectAlternativeNameExtension( new GeneralNames(gn) );
	} catch (Exception e) {
		log(ILogger.LL_INFO, CMS.getLogMessage("CMSGW_ENROLL_FAIL_NO_SUBJ_ALT_NAME",
			e.getMessage()));	  
		return null;
	}
  }
              


  // Perform authentication

  /*
   * if the authentication is set up for CEP, and the user provides
   * some credential, an attempt is made to authenticate the user
   * If this fails, this method will return true
   * If it is sucessful, this method will return true and
   * an authtoken will be in the request
   *
   * If authentication is not configured, this method will
   * return false. The request will be processed in the usual
   * way, but no authtoken will be in the request.
   *
   * In other word, this method returns true if the request
   * should be aborted, false otherwise.
   */

  private boolean authenticateUser(CRSPKIMessage req) {
		  boolean authenticationFailed = true;

		  if (mAuthManagerName == null) {
			return false;
		  }

		  String password = (String)req.get(AUTH_PASSWORD);

          AuthCredentials authCreds = (AuthCredentials)req.get(AUTH_CREDS);

		  if (authCreds == null) {
			  authCreds = new AuthCredentials();
		  }

		  // authtoken starts as null
          AuthToken token = null;

          	  if (password != null && !password.equals(""))  {
				try {
               		authCreds.set(AUTH_PASSWORD,password);
				} catch (Exception e) {}
			  }
			  

                try {
                 token = (AuthToken)mAuthSubsystem.authenticate(authCreds,mAuthManagerName);
                   authCreds.delete(AUTH_PASSWORD);
				// if we got here, the authenticate call must not have thrown
				// an exception
                   authenticationFailed = false;
              	}
              	catch (EInvalidCredentials ex) {
                   // Invalid credentials - we must reject the request
                   authenticationFailed = true;
              	}
              	catch (EMissingCredential mc) {
                   // Misssing credential - we'll log, and process manually
                   authenticationFailed = false;
              	}
              	catch (EBaseException ex) {
                  // If there's some other error, we'll reject
                  // So, we just continue on, - AUTH_TOKEN will not be set.
              	}

	 	 if (token != null) {
	     	req.put(AUTH_TOKEN,token);
		 }

         return authenticationFailed;
   }

  private boolean areFingerprintsEqual(IRequest req, Hashtable fingerprints)
  {
	
	Hashtable old_fprints = req.getExtDataInHashtable(IRequest.FINGERPRINTS);
	if (old_fprints == null) { return false; }

    byte[] old_md5 = CMS.AtoB((String) old_fprints.get("MD5"));
	byte[] new_md5 = (byte[]) fingerprints.get("MD5");

	if (old_md5.length != new_md5.length) return false;
	
	for (int i=0;i<old_md5.length; i++) {
		if (old_md5[i] != new_md5[i]) return false;
	}
	return true;
  }

  public X509CertImpl handlePKCSReq(HttpServletRequest httpReq,
                                 IRequest cmsRequest, CRSPKIMessage req, 
									CRSPKIMessage crsResp, CryptoContext cx)
    throws   ServletException, 
             CryptoManager.NotInitializedException,
             CRSFailureException {

	try {
       unwrapPKCS10(req,cx);
	   Hashtable fingerprints = makeFingerPrints(req);

       if (cmsRequest != null) {
			if (areFingerprintsEqual(cmsRequest, fingerprints)) {
               CMS.debug("created response from request");
				return makeResponseFromRequest(req,crsResp,cmsRequest);
			}
			else {
                CMS.debug("duplicated transaction id");
		  		log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ENROLL_FAIL_DUP_TRANS_ID"));	  
		  		crsResp.setFailInfo(crsResp.mFailInfo_badRequest);
		  		crsResp.setPKIStatus(crsResp.mStatus_FAILURE);
		  		return null;
			}
		}

	   getDetailFromRequest(req,crsResp);
	   boolean authFailed = authenticateUser(req);
 
	   if (authFailed) {
          CMS.debug("authentication failed");
		  log(ILogger.LL_SECURITY, CMS.getLogMessage("CMSGW_ENROLL_FAIL_NO_AUTH"));	  
		  crsResp.setFailInfo(crsResp.mFailInfo_badIdentity);
		  crsResp.setPKIStatus(crsResp.mStatus_FAILURE);


          // perform audit log
          String auditMessage = CMS.getLogMessage(
                            "LOGGING_SIGNED_AUDIT_NON_PROFILE_CERT_REQUEST_5",
                            httpReq.getRemoteAddr(),
                            ILogger.FAILURE,
                            req.getTransactionID(),
                            "CRSEnrollment",
                            ILogger.SIGNED_AUDIT_EMPTY_VALUE);
          ILogger signedAuditLogger = CMS.getSignedAuditLogger();
          if (signedAuditLogger != null) {
            signedAuditLogger.log(ILogger.EV_SIGNED_AUDIT,
                     null, ILogger.S_SIGNED_AUDIT,
                     ILogger.LL_SECURITY, auditMessage);
          }

		  return null;
	   }
	   else {
		  IRequest ireq = postRequest(httpReq, req,crsResp);
		

          CMS.debug("created response");
		  return makeResponseFromRequest(req,crsResp, ireq);
	   }
	} catch (CryptoContext.CryptoContextException e) {
        CMS.debug("failed to decrypt the request " + e);
		log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ENROLL_FAIL_NO_DECRYPT_PKCS10",
			e.getMessage()));	  
		crsResp.setFailInfo(crsResp.mFailInfo_badMessageCheck);
		crsResp.setPKIStatus(crsResp.mStatus_FAILURE);
	} catch (EBaseException e) {
        CMS.debug("operation failure - " + e);
		log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_ERNOLL_FAIL_NO_NEW_REQUEST_POSTED",
			e.getMessage()));	  
		crsResp.setFailInfo(crsResp.mFailInfo_internalCAError);
		crsResp.setPKIStatus(crsResp.mStatus_FAILURE);
	}
	return null;
  }


//////   post the request 

/*
  needed:

  token (authtoken)
  certInfo
  fingerprints       x
  req.transactionID
  crsResp
*/  

private IRequest postRequest(HttpServletRequest httpReq, CRSPKIMessage req, CRSPKIMessage crsResp) 
throws EBaseException {
	 X500Name subject = (X500Name)req.get(SUBJECTNAME);

     if (mCreateEntry) {
		 if (subject == null) {
             CMS.debug( "CRSEnrollment::postRequest() - subject is null!" );
             return null;
		 }
         createEntry(subject.toString());
     }

     // use profile framework to handle SCEP
     if (mProfileId != null) {
       PKCS10 pkcs10data = (PKCS10)req.getP10();
       String pkcs10blob = CMS.BtoA(pkcs10data.toByteArray());

       // XXX authentication handling
       CMS.debug("Found profile=" + mProfileId);
       IProfile profile = mProfileSubsystem.getProfile(mProfileId);
       if (profile == null) {
         CMS.debug("profile " + mProfileId + " not found");
         return null;
       }
       IProfileContext ctx = profile.createContext();

       IProfileAuthenticator authenticator = null;
       try {
            CMS.debug("Retrieving authenticator");
            authenticator = profile.getAuthenticator();
            if (authenticator == null) {
              CMS.debug("No authenticator Found");
            } else {
              CMS.debug("Got authenticator=" + authenticator.getClass().getName());
            }
       } catch (EProfileException e) {
            // authenticator not installed correctly
       }

       IAuthToken authToken = null;

       // for ssl authentication; pass in servlet for retrieving
       // ssl client certificates
       SessionContext context = SessionContext.getContext();


        // insert profile context so that input parameter can be retrieved
       context.put("profileContext", ctx);
       context.put("sslClientCertProvider",
            new SSLClientCertProvider(httpReq));

       String p10Password = getPasswordFromP10(pkcs10data);
        AuthCredentials credentials = new AuthCredentials();
        credentials.set("UID", httpReq.getRemoteAddr());
        credentials.set("PWD", p10Password);

       if (authenticator == null) {
          // XXX - to help caRouterCert to work, we need to 
          // add authentication to caRouterCert
          authToken = new AuthToken(null);
       } else { 
         authToken = authenticate(credentials, authenticator, httpReq);
       }

       IRequest reqs[] = null;
       CMS.debug("CRSEnrollment: Creating profile requests");
       ctx.set(IEnrollProfile.CTX_CERT_REQUEST_TYPE, "pkcs10");
       ctx.set(IEnrollProfile.CTX_CERT_REQUEST, pkcs10blob);
       Locale locale = Locale.getDefault();
       reqs = profile.createRequests(ctx, locale);
       if (reqs == null) {
         CMS.debug("CRSEnrollment: No request has been created");
         return null;
       } else {
         CMS.debug("CRSEnrollment: Request (" + reqs.length + ") have been created");
       }
       // set transaction id
       reqs[0].setSourceId(req.getTransactionID());
       reqs[0].setExtData("profile", "true");
       reqs[0].setExtData("profileId", mProfileId);
       reqs[0].setExtData(IEnrollProfile.CTX_CERT_REQUEST_TYPE, IEnrollProfile.REQ_TYPE_PKCS10);
       reqs[0].setExtData(IEnrollProfile.CTX_CERT_REQUEST, pkcs10blob);
       reqs[0].setExtData("requestor_name", "");
       reqs[0].setExtData("requestor_email", "");
       reqs[0].setExtData("requestor_phone", "");
       reqs[0].setExtData("profileRemoteHost", httpReq.getRemoteHost());
       reqs[0].setExtData("profileRemoteAddr", httpReq.getRemoteAddr());
       reqs[0].setExtData("profileApprovedBy", profile.getApprovedBy());

       CMS.debug("CRSEnrollment: Populating inputs");
       profile.populateInput(ctx, reqs[0]);
       CMS.debug("CRSEnrollment: Populating requests");
       profile.populate(reqs[0]);

       CMS.debug("CRSEnrollment: Submitting request");
       profile.submit(authToken, reqs[0]);
       CMS.debug("CRSEnrollment: Done submitting request");
       profile.getRequestQueue().markAsServiced(reqs[0]);
       CMS.debug("CRSEnrollment: Request marked as serviced");

       return reqs[0];

     }

     IRequestQueue rq = ca.getRequestQueue();
     IRequest pkiReq = rq.newRequest(IRequest.ENROLLMENT_REQUEST);

	 AuthToken token = (AuthToken) req.get(AUTH_TOKEN);
     if (token != null) { 
          pkiReq.setExtData(IRequest.AUTH_TOKEN,token);
     }

     pkiReq.setExtData(IRequest.HTTP_PARAMS, IRequest.CERT_TYPE, IRequest.CEP_CERT);
	 X509CertInfo certInfo = (X509CertInfo) req.get(CERTINFO);
     pkiReq.setExtData(IRequest.CERT_INFO, new X509CertInfo[] { certInfo } );
     pkiReq.setExtData("cepsubstore", mSubstoreName);

	 try {
	 	String chpwd = (String)req.get(ChallengePassword.NAME);
        if (chpwd != null) {
	 		pkiReq.setExtData("challengePhrase",
				chpwd );
		}
	 } catch (Exception pwex) {
	 }

     Hashtable fingerprints = (Hashtable)req.get(IRequest.FINGERPRINTS);
     if (fingerprints.size() > 0) {
         Hashtable encodedPrints = new Hashtable(fingerprints.size());
         Enumeration e = fingerprints.keys();
         while (e.hasMoreElements()) {
             String key = (String)e.nextElement();
             byte[] value = (byte[])fingerprints.get(key);
             encodedPrints.put(key, CMS.BtoA(value));
         }
         pkiReq.setExtData(IRequest.FINGERPRINTS, encodedPrints);
	 }

     pkiReq.setSourceId(req.getTransactionID());
                 
     rq.processRequest(pkiReq);

     crsResp.setPKIStatus(crsResp.mStatus_SUCCESS);

     mLogger.log(ILogger.EV_AUDIT, ILogger.S_OTHER,
                            AuditFormat.LEVEL,
                            AuditFormat.ENROLLMENTFORMAT,
                            new Object[] {
                            pkiReq.getRequestId(),
                            AuditFormat.FROMROUTER,
                            mAuthManagerName == null ? AuditFormat.NOAUTH : mAuthManagerName,
                            "pending",
                            subject ,
                            ""}
                            );
                  
	  return pkiReq;
  }



  public Hashtable makeFingerPrints(CRSPKIMessage req) {
        Hashtable fingerprints = new Hashtable();

        MessageDigest md;
        String[] hashes = new String[] {"MD2", "MD5", "SHA1", "SHA256", "SHA512"};
        PKCS10 p10 = (PKCS10)req.getP10();

        for (int i=0;i<hashes.length;i++) {
		    try {
               	md = MessageDigest.getInstance(hashes[i]);
               	md.update(p10.getCertRequestInfo());
               	fingerprints.put(hashes[i],md.digest());
			}
			catch (NoSuchAlgorithmException nsa) {}
        }

		if (fingerprints != null) {
	    	req.put(IRequest.FINGERPRINTS,fingerprints);
		}
		return fingerprints;
  }

  
  // Take a look to see if the request was successful, and fill
  // in the response message


  private X509CertImpl makeResponseFromRequest(CRSPKIMessage crsReq, CRSPKIMessage crsResp,
                                      IRequest pkiReq)
    {

        X509CertImpl issuedCert=null;

        RequestStatus status = pkiReq.getRequestStatus();

        String profileId = pkiReq.getExtDataInString("profileId");
        if (profileId != null) {
          CMS.debug("CRSEnrollment: Found profile request");
          X509CertImpl cert =
                 pkiReq.getExtDataInCert(IEnrollProfile.REQUEST_ISSUED_CERT);
          if (cert == null) {
            CMS.debug("CRSEnrollment: No certificate has been found");
          } else {
            CMS.debug("CRSEnrollment: Found certificate");
          }
          crsResp.setPKIStatus(crsResp.mStatus_SUCCESS);
          return cert;
        }


        if ( status.equals(RequestStatus.COMPLETE)) {
            Integer success = pkiReq.getExtDataInInteger(IRequest.RESULT);


            if (success.equals(IRequest.RES_SUCCESS)) {
                // The cert was issued, lets send it back to the router
                X509CertImpl[] issuedCertBuf =
                  pkiReq.getExtDataInCertArray(IRequest.ISSUED_CERTS);
                if (issuedCertBuf == null || issuedCertBuf.length == 0) {
                    //  writeError("Internal Error: Bad operation",httpReq,httpResp);
                    CMS.debug( "CRSEnrollment::makeResponseFromRequest() - " +
                               "Bad operation" );
                    return null;
                }
                issuedCert = issuedCertBuf[0];
                crsResp.setPKIStatus(crsResp.mStatus_SUCCESS);
                            
            }
            else {  // status is not 'success' - there must've been a problem
                            
                crsResp.setPKIStatus(crsResp.mStatus_FAILURE);
                crsResp.setFailInfo(crsResp.mFailInfo_badAlg);
            }
        }
        else if (status.equals(RequestStatus.REJECTED_STRING) ||
                 status.equals(RequestStatus.CANCELED_STRING)) {
                crsResp.setPKIStatus(crsResp.mStatus_FAILURE);
                crsResp.setFailInfo(crsResp.mFailInfo_badRequest);
            }
        else  {   // not complete
            crsResp.setPKIStatus(crsResp.mStatus_PENDING);
        }

        return issuedCert;
    }






  /**
   *  This needs to be re-written to log the messages to the system log, since there
   *  will be no visual webpage feedback for the user. (he's using a router)
   */

  private void writeError(String errMsg, HttpServletRequest httpReq,
                          HttpServletResponse httpResp)
    throws IOException
    {
    }


   protected String hashPassword(String pwd) {
        String salt = "lala123";
        byte[] pwdDigest = mSHADigest.digest((salt+pwd).getBytes());
        String b64E = com.netscape.osutil.OSUtil.BtoA(pwdDigest);
        return "{SHA}"+b64E;
    }




  /**
   *  Make the CRSPKIMESSAGE response
   */


  private void processCertRep(CryptoContext cx,
                              X509CertImpl issuedCert,
                              CRSPKIMessage crsResp,
                              CRSPKIMessage crsReq) 
    throws CRSFailureException {
      byte[] msgdigest = null;
      byte[] encryptedDesKey = null;
        
      try {
          if (issuedCert != null) {
                
              SymmetricKey sk;
              SymmetricKey skinternal;

              KeyGenAlgorithm kga = KeyGenAlgorithm.DES;
              EncryptionAlgorithm ea = EncryptionAlgorithm.DES_CBC;
              if (mEncryptionAlgorithm != null && mEncryptionAlgorithm.equals("DES3")) {
                  kga = KeyGenAlgorithm.DES3;
                  ea = EncryptionAlgorithm.DES3_CBC;
              }

              // 1. Make the Degenerated PKCS7 with the recipient's certificate in it
                
              byte toBeEncrypted[] =
                crsResp.makeSignedRep(1,  // version
                                      issuedCert.getEncoded()
                                      );
                
              // 2. Encrypt the above byte array with a new random DES key
                
              sk = cx.getDESKeyGenerator().generate();
                
              skinternal = cx.getInternalToken().getKeyGenerator(kga).clone(sk);
                
              byte[] padded = Cipher.pad(toBeEncrypted, ea.getBlockSize());


              // This should be changed to generate proper DES IV.

              Cipher cipher = cx.getInternalToken().getCipherContext(ea);
              IVParameterSpec desIV =
                new IVParameterSpec(new byte[]{
                    (byte)0xff, (byte)0x00,
                      (byte)0xff, (byte)0x00,
                      (byte)0xff, (byte)0x00,
                      (byte)0xff, (byte)0x00 } );
                
              cipher.initEncrypt(sk,desIV);
              byte[] encryptedData = cipher.doFinal(padded);
                
              crsResp.makeEncryptedContentInfo(desIV.getIV(),encryptedData, mEncryptionAlgorithm);
                
              // 3. Extract the recipient's public key
                
              PublicKey rcpPK = crsReq.getSignerPublicKey();
                
                
              // 4. Encrypt the DES key with the public key
                
              // we have to move the key onto the interal token.
              //skinternal = cx.getInternalKeyStorageToken().cloneKey(sk);
              skinternal = cx.getInternalToken().cloneKey(sk);
                
              KeyWrapper kw = cx.getInternalKeyWrapper();
              kw.initWrap(rcpPK, null);
              encryptedDesKey = kw.wrap(skinternal);
                
              crsResp.setRcpIssuerAndSerialNumber(crsReq.getSgnIssuerAndSerialNumber());
              crsResp.makeRecipientInfo(0, encryptedDesKey );
                
          }

                
          byte[] ed = crsResp.makeEnvelopedData(0);

          // 7. Make Digest of SignedData Content 
          MessageDigest md = MessageDigest.getInstance(mHashAlgorithm);
          msgdigest = md.digest(ed);

          crsResp.setMsgDigest(msgdigest);
                
      }
        
      catch (Exception e) {
          throw new CRSFailureException("Failed to create inner response to CEP message: "+e.getMessage());
      }
        
                        
      // 5. Make a RecipientInfo
        
      // The issuer name & serial number here, should be that of
      // the EE's self-signed Certificate
      // [I can get it from the req blob, but later, I should
      //  store the recipient's self-signed certificate with the request
      //  so I can get at it later. I need to do this to support
      //  'PENDING']
        
        
      try {
            
          // 8. Make Authenticated Attributes
          // we can just pull the transaction ID out of the request.
          // Later, we will have to put it out of the Request queue,
          // so we can support PENDING
          crsResp.setTransactionID(crsReq.getTransactionID());
          // recipientNonce and SenderNonce have already been set
            
          crsResp.makeAuthenticatedAttributes();
          //      crsResp.makeAuthenticatedAttributes_old();                  
            


          // now package up the rest of the SignerInfo
          {
              byte[] signingcertbytes = cx.getSigningCert().getEncoded();
                

              Certificate.Template sgncert_t = new Certificate.Template();
              Certificate sgncert =
                (Certificate) sgncert_t.decode(new ByteArrayInputStream(signingcertbytes));
                
              IssuerAndSerialNumber sgniasn =
                new IssuerAndSerialNumber(sgncert.getInfo().getIssuer(),
                                          sgncert.getInfo().getSerialNumber());
                
              crsResp.setSgnIssuerAndSerialNumber(sgniasn);
                
              // 10. Make SignerInfo
              crsResp.makeSignerInfo(1, cx.getPrivateKey(), mHashAlgorithm);

              // 11. Make SignedData
              crsResp.makeSignedData(1, signingcertbytes, mHashAlgorithm);

              crsResp.debug();
          }
      }
      catch (Exception e) {
          throw new CRSFailureException("Failed to create outer response to CEP request: "+e.getMessage());
      }
        
        
      // if debugging, dump out the response into a file
        
  }



  class CryptoContext {
    private CryptoManager cm;
    private CryptoToken internalToken;
    private CryptoToken keyStorageToken;
    private CryptoToken internalKeyStorageToken;
    private KeyGenerator DESkg;
	private Enumeration externalTokens = null;
    private org.mozilla.jss.crypto.X509Certificate signingCert;
    private org.mozilla.jss.crypto.PrivateKey signingCertPrivKey;
	private int signingCertKeySize = 0;


    class CryptoContextException extends Exception {
      public CryptoContextException() { super(); }
      public CryptoContextException(String s) { super(s); }
    }

    public CryptoContext()
      throws CryptoContextException
      {
          try {
              KeyGenAlgorithm kga = KeyGenAlgorithm.DES;
              if (mEncryptionAlgorithm != null && mEncryptionAlgorithm.equals("DES3")) {
                  kga = KeyGenAlgorithm.DES3;
              }
              cm = CryptoManager.getInstance();
              internalToken = cm.getInternalCryptoToken();
              DESkg = internalToken.getKeyGenerator(kga);
              if (mTokenName.equalsIgnoreCase(Constants.PR_INTERNAL_TOKEN) ||
                  mTokenName.equalsIgnoreCase("Internal Key Storage Token") ||
                  mTokenName.length() == 0) {
                  keyStorageToken = cm.getInternalKeyStorageToken();
                  internalKeyStorageToken = keyStorageToken;
                  CMS.debug("CRSEnrollment: CryptoContext: internal token name: '"+mTokenName+"'");
              } else {
                  keyStorageToken = cm.getTokenByName(mTokenName);
                  internalKeyStorageToken = null;
              }
              if (!mUseCA && internalKeyStorageToken == null) {
                  PasswordCallback cb = CMS.getPasswordCallback(); 
                  keyStorageToken.login(cb); // ONE_TIME by default.
              }
              signingCert = cm.findCertByNickname(mNickname);
              signingCertPrivKey = cm.findPrivKeyByCert(signingCert);
			  byte[] encPubKeyInfo = signingCert.getPublicKey().getEncoded();
			  SEQUENCE.Template outer = SEQUENCE.getTemplate();
			  outer.addElement( ANY.getTemplate() ); // algid
			  outer.addElement( BIT_STRING.getTemplate() );
			  SEQUENCE outerSeq = (SEQUENCE) ASN1Util.decode(outer, encPubKeyInfo);
			  BIT_STRING bs = (BIT_STRING) outerSeq.elementAt(1);
			  byte[] encPubKey = bs.getBits();
			  if( bs.getPadCount() != 0) {
			  	  throw new CryptoContextException("Internal error: Invalid Public key. Not an integral number of bytes.");
			  }
			  SEQUENCE.Template inner = new SEQUENCE.Template();
			  inner.addElement( INTEGER.getTemplate());
			  inner.addElement( INTEGER.getTemplate());
			  SEQUENCE pubKeySeq = (SEQUENCE) ASN1Util.decode(inner, encPubKey);
			  INTEGER modulus = (INTEGER) pubKeySeq.elementAt(0);
			  signingCertKeySize = modulus.bitLength();
			  
			  try {
              FileOutputStream fos = new FileOutputStream("pubkey.der");
              fos.write(signingCert.getPublicKey().getEncoded());
              fos.close();
			  } catch (Exception e) {}

          }
		  catch (InvalidBERException e) {
		  	  throw new CryptoContextException("Internal Error: Bad internal Certificate Representation. Not a valid RSA-signed certificate");
			  }
          catch (CryptoManager.NotInitializedException e) {
              throw new CryptoContextException("Crypto Manager not initialized");
          }
          catch (NoSuchAlgorithmException e) {
              throw new CryptoContextException("Cannot create DES key generator");
          }
          catch (ObjectNotFoundException e) {
              throw new CryptoContextException("Certificate not found: "+ca.getNickname());
          }
          catch (TokenException e) {
              throw new CryptoContextException("Problem with Crypto Token: "+e.getMessage());
          }
          catch (NoSuchTokenException e) {
              throw new CryptoContextException("Crypto Token not found: "+e.getMessage());
          }
          catch (IncorrectPasswordException e) {
              throw new CryptoContextException("Incorrect Password.");
          }
      }


    public KeyGenerator getDESKeyGenerator() {
        return DESkg;
    }

    public CryptoToken getInternalToken() {
        return internalToken;
    }

    public void setExternalTokens( Enumeration tokens ) {
        externalTokens = tokens;
    }

    public Enumeration getExternalTokens() {
        return externalTokens;
    }

    public CryptoToken getInternalKeyStorageToken() {
        return internalKeyStorageToken;
    }

    public CryptoToken getKeyStorageToken() {
        return keyStorageToken;
    }

    public CryptoManager getCryptoManager() {
        return cm;
    }

    public KeyWrapper getKeyWrapper() 
      throws CryptoContextException {
        try {
            return signingCertPrivKey.getOwningToken().getKeyWrapper(KeyWrapAlgorithm.RSA);
        }
        catch (TokenException e) {
            throw new CryptoContextException("Problem with Crypto Token: "+e.getMessage());
        }
        catch (NoSuchAlgorithmException e) {
            throw new CryptoContextException(e.getMessage());
        }
    }

    public KeyWrapper getInternalKeyWrapper() 
      throws CryptoContextException {
        try {
            return getInternalToken().getKeyWrapper(KeyWrapAlgorithm.RSA);
        }
        catch (TokenException e) {
            throw new CryptoContextException("Problem with Crypto Token: "+e.getMessage());
        }
        catch (NoSuchAlgorithmException e) {
            throw new CryptoContextException(e.getMessage());
        }
    }

    public org.mozilla.jss.crypto.PrivateKey getPrivateKey() {
        return signingCertPrivKey;
    }

    public org.mozilla.jss.crypto.X509Certificate getSigningCert() {
        return signingCert;
    }
        
  }


  /* General failure. The request/response cannot be processed. */


  class CRSFailureException extends Exception {
    public CRSFailureException() { super(); }
    public CRSFailureException(String s) { super(s); }
  }

  class CRSInvalidSignatureException extends Exception {
    public CRSInvalidSignatureException() { super(); }
    public CRSInvalidSignatureException(String s) { super(s); }
  }

    

  class CRSPolicyException extends Exception {
      public CRSPolicyException() { super(); }
      public CRSPolicyException(String s) { super(s); }
  }

}