summaryrefslogtreecommitdiffstats
path: root/base/kra/src/com/netscape/kra/SecurityDataProcessor.java
blob: f00cb5b3df7a179aefd538ce7d7a6fde64be611f (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
package com.netscape.kra;

import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Arrays;
import java.util.Hashtable;

import javax.crypto.spec.RC2ParameterSpec;

import org.dogtagpki.server.kra.rest.KeyRequestService;
import org.mozilla.jss.asn1.OBJECT_IDENTIFIER;
import org.mozilla.jss.asn1.OCTET_STRING;
import org.mozilla.jss.crypto.CryptoToken;
import org.mozilla.jss.crypto.EncryptionAlgorithm;
import org.mozilla.jss.crypto.IVParameterSpec;
import org.mozilla.jss.crypto.KeyGenerator;
import org.mozilla.jss.crypto.KeyWrapAlgorithm;
import org.mozilla.jss.crypto.PBEAlgorithm;
import org.mozilla.jss.crypto.PBEKeyGenParams;
import org.mozilla.jss.crypto.PrivateKey;
import org.mozilla.jss.crypto.SymmetricKey;
import org.mozilla.jss.pkcs12.PasswordConverter;
import org.mozilla.jss.pkcs7.ContentInfo;
import org.mozilla.jss.pkcs7.EncryptedContentInfo;
import org.mozilla.jss.pkix.primitive.AlgorithmIdentifier;
import org.mozilla.jss.pkix.primitive.PBEParameter;
import org.mozilla.jss.util.Password;

import com.netscape.certsrv.apps.CMS;
import com.netscape.certsrv.base.EBaseException;
import com.netscape.certsrv.base.IConfigStore;
import com.netscape.certsrv.dbs.keydb.IKeyRecord;
import com.netscape.certsrv.dbs.keydb.IKeyRepository;
import com.netscape.certsrv.dbs.keydb.KeyId;
import com.netscape.certsrv.key.KeyRequestResource;
import com.netscape.certsrv.kra.EKRAException;
import com.netscape.certsrv.kra.IKeyRecoveryAuthority;
import com.netscape.certsrv.logging.AuditEvent;
import com.netscape.certsrv.logging.ILogger;
import com.netscape.certsrv.logging.event.SecurityDataArchivalProcessedEvent;
import com.netscape.certsrv.profile.IEnrollProfile;
import com.netscape.certsrv.request.IRequest;
import com.netscape.certsrv.request.RequestId;
import com.netscape.certsrv.security.IStorageKeyUnit;
import com.netscape.certsrv.security.ITransportKeyUnit;
import com.netscape.cms.logging.Logger;
import com.netscape.cms.logging.SignedAuditLogger;
import com.netscape.cmscore.dbs.KeyRecord;
import com.netscape.cmscore.security.JssSubsystem;
import com.netscape.cmsutil.crypto.CryptoUtil;
import com.netscape.cmsutil.util.Utils;

import netscape.security.util.DerValue;
import netscape.security.util.WrappingParams;
import netscape.security.x509.X509Key;

public class SecurityDataProcessor {

    private static Logger signedAuditLogger = SignedAuditLogger.getLogger();

    public final static String ATTR_KEY_RECORD = "keyRecord";
    public static final String ATTR_SERIALNO = "serialNumber";
    private final static String STATUS_ACTIVE = "active";

    private IKeyRecoveryAuthority kra = null;
    private ITransportKeyUnit transportUnit = null;
    private IStorageKeyUnit storageUnit = null;
    private IKeyRepository keyRepository = null;

    private static boolean allowEncDecrypt_archival = false;
    private static boolean allowEncDecrypt_recovery = false;

    public SecurityDataProcessor(IKeyRecoveryAuthority kra) {
        this.kra = kra;
        transportUnit = kra.getTransportKeyUnit();
        storageUnit = kra.getStorageKeyUnit();
        keyRepository = kra.getKeyRepository();
    }

    public boolean archive(IRequest request)
            throws EBaseException {
        RequestId requestId = request.getRequestId();
        String clientKeyId = request.getExtDataInString(IRequest.SECURITY_DATA_CLIENT_KEY_ID);

        // one way to get data - unexploded pkiArchiveOptions
        String pkiArchiveOptions = request.getExtDataInString(IEnrollProfile.REQUEST_ARCHIVE_OPTIONS);

        // another way - exploded pkiArchiveOptions
        String transWrappedSessionKey = request.getExtDataInString(IEnrollProfile.REQUEST_SESSION_KEY);
        String wrappedSecurityData = request.getExtDataInString(IEnrollProfile.REQUEST_SECURITY_DATA);
        String algParams = request.getExtDataInString(IEnrollProfile.REQUEST_ALGORITHM_PARAMS);
        String algStr = request.getExtDataInString(IEnrollProfile.REQUEST_ALGORITHM_OID);

        // parameters if the secret is a symmetric key
        String dataType = request.getExtDataInString(IRequest.SECURITY_DATA_TYPE);
        String algorithm = request.getExtDataInString(IRequest.SECURITY_DATA_ALGORITHM);
        int strength = request.getExtDataInInteger(IRequest.SECURITY_DATA_STRENGTH);

        // parameter for realm
        String realm = request.getRealm();

        CMS.debug("SecurityDataProcessor.archive. Request id: " + requestId.toString());
        CMS.debug("SecurityDataProcessor.archive wrappedSecurityData: " + wrappedSecurityData);

        IConfigStore config = null;

        try {
            config = CMS.getConfigStore();
            allowEncDecrypt_archival = config.getBoolean("kra.allowEncDecrypt.archival", false);
        } catch (Exception e) {
            throw new EBaseException(CMS.getUserMessage("CMS_BASE_CERT_ERROR", e.toString()));
        }


        String owner = request.getExtDataInString(IRequest.ATTR_REQUEST_OWNER);
        String auditSubjectID = owner;

        //Check here even though restful layer checks for this.
        if (clientKeyId == null || dataType == null) {
            auditArchivalRequestProcessed(auditSubjectID, ILogger.FAILURE, requestId,
                    clientKeyId, null, "Bad data in request");
            throw new EBaseException("Bad data in SecurityDataService.serviceRequest");
        }

        if (wrappedSecurityData != null) {
            if (transWrappedSessionKey == null || algStr == null || algParams == null) {
                throw new EBaseException(
                        "Bad data in SecurityDataService.serviceRequest, no session key");

            }
        } else if (pkiArchiveOptions == null) {
            throw new EBaseException("No data to archive in SecurityDataService.serviceRequest");
        }

        byte[] wrappedSessionKey = null;
        byte[] secdata = null;
        byte[] sparams = null;

        if (wrappedSecurityData == null) {
            // We have PKIArchiveOptions data

            //We need some info from the PKIArchiveOptions wrapped security data
            byte[] encoded = Utils.base64decode(pkiArchiveOptions);

            ArchiveOptions options = ArchiveOptions.toArchiveOptions(encoded);
            algStr = options.getSymmAlgOID();
            wrappedSessionKey = options.getEncSymmKey();
            secdata = options.getEncValue();
            sparams = options.getSymmAlgParams();

        } else {
            wrappedSessionKey = Utils.base64decode(transWrappedSessionKey);
            secdata = Utils.base64decode(wrappedSecurityData);
            sparams = Utils.base64decode(algParams);
        }

        SymmetricKey securitySymKey = null;
        byte[] securityData = null;

        String keyType = null;
        byte [] tmp_unwrapped = null;
        byte [] unwrapped = null;
        if (dataType.equals(KeyRequestResource.SYMMETRIC_KEY_TYPE)) {
            // Symmetric Key
            keyType = KeyRequestResource.SYMMETRIC_KEY_TYPE;

            if (allowEncDecrypt_archival == true) {
                try {
                    tmp_unwrapped = transportUnit.decryptExternalPrivate(
                            wrappedSessionKey,
                            algStr,
                            sparams,
                            secdata,
                            null);

                } catch (Exception e) {
                    throw new EBaseException("Can't decrypt symm key using allEncDecrypt_archival : true .");
                }

                /* making sure leading 0's are removed */
                int first=0;
                for (int j=0; (j< tmp_unwrapped.length) && (tmp_unwrapped[j]==0); j++) {
                    first++;
                }
                unwrapped = Arrays.copyOfRange(tmp_unwrapped, first, tmp_unwrapped.length);
                Arrays.fill(tmp_unwrapped, (byte)0);


            } else {
                try {
                    securitySymKey = transportUnit.unwrap_symmetric(
                            wrappedSessionKey,
                            algStr,
                            sparams,
                            secdata,
                            KeyRequestService.SYMKEY_TYPES.get(algorithm),
                            strength);
                } catch (Exception e) {
                    throw new EBaseException("Can't decrypt symmetric key.", e);
                }
            }

        } else if (dataType.equals(KeyRequestResource.PASS_PHRASE_TYPE)) {
            keyType = KeyRequestResource.PASS_PHRASE_TYPE;
            try {
                securityData = transportUnit.decryptExternalPrivate(
                        wrappedSessionKey,
                        algStr,
                        sparams,
                        secdata,
                        null);
            } catch (Exception e) {
                throw new EBaseException("Can't decrypt passphrase.", e);
            }

        }
        WrappingParams params = null;

        byte[] publicKey = null;
        byte privateSecurityData[] = null;
        boolean doEncrypt = false;

        try {
            params = storageUnit.getWrappingParams(allowEncDecrypt_archival);
            if (securitySymKey != null && unwrapped == null) {
                privateSecurityData = storageUnit.wrap(securitySymKey, params);
            } else if (unwrapped != null && allowEncDecrypt_archival == true) {
                privateSecurityData = storageUnit.encryptInternalPrivate(unwrapped, params);
                Arrays.fill(unwrapped, (byte)0);
                doEncrypt = true;
                CMS.debug("allowEncDecrypt_archival of symmetric key.");
            } else if (securityData != null) {
                privateSecurityData = storageUnit.encryptInternalPrivate(securityData, params);
                doEncrypt = true;
            } else { // We have no data.
                auditArchivalRequestProcessed(auditSubjectID, ILogger.FAILURE, requestId,
                        clientKeyId, null, "Failed to create security data to archive");
                throw new EBaseException("Failed to create security data to archive!");
            }
        } catch (Exception e) {
            CMS.debug("Failed to create security data to archive: " + e.getMessage());
            auditArchivalRequestProcessed(auditSubjectID, ILogger.FAILURE, requestId,
                    clientKeyId, null, CMS.getUserMessage("CMS_KRA_INVALID_PRIVATE_KEY"));

            throw new EBaseException(CMS.getUserMessage("CMS_KRA_INVALID_PRIVATE_KEY"));
        }

        // create key record
        // Note that in this case the owner is the same as the approving agent
        // because the archival request is made by the agent.
        // The algorithm used to generate the symmetric key (being stored as the secret)
        // is set in later in this method. (which is different  from the algStr variable
        // which is the algorithm used for encrypting the secret.)
        KeyRecord rec = new KeyRecord(null, publicKey,
                privateSecurityData, owner,
                null, owner);

        rec.set(IKeyRecord.ATTR_CLIENT_ID, clientKeyId);

        //Now we need a serial number for our new key.

        if (rec.getSerialNumber() != null) {
            auditArchivalRequestProcessed(auditSubjectID, ILogger.FAILURE, requestId,
                    clientKeyId, null, CMS.getUserMessage("CMS_KRA_INVALID_STATE"));
            throw new EBaseException(CMS.getUserMessage("CMS_KRA_INVALID_STATE"));
        }

        BigInteger serialNo = keyRepository.getNextSerialNumber();

        if (serialNo == null) {
            kra.log(ILogger.LL_FAILURE,
                    CMS.getLogMessage("CMSCORE_KRA_GET_NEXT_SERIAL"));
            auditArchivalRequestProcessed(auditSubjectID, ILogger.FAILURE, requestId,
                    clientKeyId, null, "Failed to get  next Key ID");
            throw new EBaseException(CMS.getUserMessage("CMS_KRA_INVALID_STATE"));
        }

        rec.set(KeyRecord.ATTR_ID, serialNo);
        rec.set(KeyRecord.ATTR_DATA_TYPE, keyType);
        rec.set(KeyRecord.ATTR_STATUS, STATUS_ACTIVE);

        if (dataType.equals(KeyRequestResource.SYMMETRIC_KEY_TYPE)) {
            rec.set(KeyRecord.ATTR_ALGORITHM, algorithm);
            rec.set(KeyRecord.ATTR_KEY_SIZE, strength);
        }

        if (realm != null) {
            rec.set(KeyRecord.ATTR_REALM,  realm);
        }

        try {
            rec.setWrappingParams(params, doEncrypt);
        } catch (Exception e) {
            kra.log(ILogger.LL_FAILURE,
                    "Failed to store wrapping parameters: " + e);
            auditArchivalRequestProcessed(auditSubjectID, ILogger.FAILURE, requestId,
                    clientKeyId, null, "Failed to store wrapping parameters");
            throw new EBaseException(CMS.getUserMessage("CMS_KRA_INVALID_STATE"), e);
        }

        CMS.debug("KRA adding Security Data key record " + serialNo);

        keyRepository.addKeyRecord(rec);

        auditArchivalRequestProcessed(auditSubjectID, ILogger.SUCCESS, requestId,
                clientKeyId, new KeyId(serialNo), "None");

        request.setExtData(ATTR_KEY_RECORD, serialNo);
        request.setExtData(IRequest.RESULT, IRequest.RES_SUCCESS);
        return true;
    }

    public boolean recover(IRequest request)
            throws EBaseException {

        CMS.debug("SecurityDataService.recover(): start");
        IConfigStore config = null;

        try {
            config = CMS.getConfigStore();
            allowEncDecrypt_recovery = config.getBoolean("kra.allowEncDecrypt.recovery", false);
        } catch (Exception e) {
            throw new EBaseException(CMS.getUserMessage("CMS_BASE_CERT_ERROR", e.toString()));
        }

        Hashtable<String, Object> params = kra.getVolatileRequest(
                request.getRequestId());
        KeyId keyId = new KeyId(request.getExtDataInBigInteger(ATTR_SERIALNO));
        request.setExtData(ATTR_KEY_RECORD, keyId.toBigInteger());

        if (params == null) {
            CMS.debug("SecurityDataProcessor.recover(): Can't get volatile params.");
            throw new EBaseException("Can't obtain volatile params!");
        }

        String transWrappedSessKeyStr = (String) params.get(IRequest.SECURITY_DATA_TRANS_SESS_KEY);
        byte[] wrappedSessKey = null;
        if (transWrappedSessKeyStr != null) {
            wrappedSessKey = Utils.base64decode(transWrappedSessKeyStr);
        }

        String sessWrappedPassPhraseStr = (String) params.get(IRequest.SECURITY_DATA_SESS_PASS_PHRASE);
        byte[] wrappedPassPhrase = null;
        if (sessWrappedPassPhraseStr != null) {
            wrappedPassPhrase = Utils.base64decode(sessWrappedPassPhraseStr);
        }

        if (transWrappedSessKeyStr == null && sessWrappedPassPhraseStr == null) {
            //We may be in recovery case where no params were initially submitted.
            CMS.debug("SecurityDataProcessor.recover(): No params provided.");
            return false;
        }

        KeyRecord keyRecord = (KeyRecord) keyRepository.readKeyRecord(keyId.toBigInteger());

        String dataType = (String) keyRecord.get(IKeyRecord.ATTR_DATA_TYPE);
        if (dataType == null) dataType = KeyRequestResource.ASYMMETRIC_KEY_TYPE;

        SymmetricKey unwrappedSess = null;
        SymmetricKey symKey = null;
        byte[] unwrappedSecData = null;
        PrivateKey privateKey = null;

        Boolean encrypted = keyRecord.isEncrypted();
        if (encrypted == null) {
            // must be an old key record
            // assume the value of allowEncDecrypt
            encrypted = allowEncDecrypt_recovery;
        }

        if (dataType.equals(KeyRequestResource.SYMMETRIC_KEY_TYPE)) {
            if (encrypted) {
                CMS.debug("Recover symmetric key by decrypting as per allowEncDecrypt_recovery: true.");
                unwrappedSecData = recoverSecurityData(keyRecord);
            } else {
                symKey = recoverSymKey(keyRecord);
            }

        } else if (dataType.equals(KeyRequestResource.PASS_PHRASE_TYPE)) {
            unwrappedSecData = recoverSecurityData(keyRecord);
        } else if (dataType.equals(KeyRequestResource.ASYMMETRIC_KEY_TYPE)) {
            try {
                if (encrypted) {
                    CMS.debug("Recover asymmetric key by decrypting as per allowEncDecrypt_recovery: true.");
                    unwrappedSecData = recoverSecurityData(keyRecord);
                } else {
                    byte[] publicKeyData = keyRecord.getPublicKeyData();
                    byte[] privateKeyData = keyRecord.getPrivateKeyData();

                    PublicKey publicKey = X509Key.parsePublicKey(new DerValue(publicKeyData));
                    privateKey = storageUnit.unwrap(
                            privateKeyData,
                            publicKey,
                            true,
                            keyRecord.getWrappingParams(storageUnit.getOldWrappingParams()));
                }

            } catch (Exception e) {
                throw new EBaseException("Cannot fetch the private key from the database.", e);
            }

        } else {
            throw new EBaseException("Invalid data type stored in the database.");
        }

        CryptoToken ct = transportUnit.getToken();

        String payloadEncryptOID = (String) params.get(IRequest.SECURITY_DATA_PL_ENCRYPTION_OID);
        String payloadWrapName = (String) params.get(IRequest.SECURITY_DATA_PL_WRAPPING_NAME);
        String transportKeyAlgo = transportUnit.getCertificate().getPublicKey().getAlgorithm();

        if (allowEncDecrypt_recovery) {
            if (payloadWrapName == null) {
                // assume old client
                payloadWrapName = "DES3/CBC/Pad";
            } else if (payloadWrapName.equals("AES KeyWrap/Padding") ||
                    payloadWrapName.equals("AES KeyWrap")) {
                // Some HSMs have not implemented AES-KW yet
                // Make sure we select an algorithm that is supported.
                payloadWrapName = "AES/CBC/PKCS5Padding";
            }
        }

        byte[] iv = null;
        byte[] iv_wrap = null;
        try {
            iv = generate_iv(
                    payloadEncryptOID,
                    transportUnit.getOldWrappingParams().getPayloadEncryptionAlgorithm());
            iv_wrap = generate_wrap_iv(
                    payloadWrapName,
                    transportUnit.getOldWrappingParams().getPayloadWrapAlgorithm());
        } catch (Exception e1) {
             throw new EBaseException("Failed to generate IV when wrapping secret", e1);
        }
        String ivStr = iv != null? Utils.base64encode(iv): null;
        String ivStr_wrap = iv_wrap != null ? Utils.base64encode(iv_wrap): null;

        WrappingParams wrapParams = null;
        if (payloadEncryptOID == null) {
            // talking to an old server, use 3DES
            wrapParams = transportUnit.getOldWrappingParams();
            wrapParams.setPayloadEncryptionIV(new IVParameterSpec(iv));
            wrapParams.setPayloadWrappingIV(new IVParameterSpec(iv_wrap));
        } else {
            try {
                wrapParams = new WrappingParams(
                    payloadEncryptOID,
                    payloadWrapName,
                    transportKeyAlgo,
                    iv != null? new IVParameterSpec(iv): null,
                    iv_wrap != null? new IVParameterSpec(iv_wrap): null);
            } catch (Exception e) {
                throw new EBaseException("Cannot generate wrapping params: " + e, e);
            }
        }

        byte[] key_data = null;
        String pbeWrappedData = null;

        if (sessWrappedPassPhraseStr != null) {
            CMS.debug("SecurityDataProcessor.recover(): secure retrieved data with tranport passphrase");
            byte[] unwrappedPass = null;
            Password pass = null;

            try {
                unwrappedSess = transportUnit.unwrap_session_key(ct, wrappedSessKey,
                        SymmetricKey.Usage.DECRYPT, wrapParams);

                unwrappedPass = CryptoUtil.decryptUsingSymmetricKey(
                        ct,
                        wrapParams.getPayloadEncryptionIV(),
                        wrappedPassPhrase,
                        unwrappedSess,
                        wrapParams.getPayloadEncryptionAlgorithm());

                String passStr = new String(unwrappedPass, "UTF-8");
                pass = new Password(passStr.toCharArray());
                passStr = null;

                if (dataType.equals(KeyRequestResource.SYMMETRIC_KEY_TYPE)) {

                    CMS.debug("SecurityDataProcessor.recover(): wrap or encrypt stored symmetric key with transport passphrase");
                    if (encrypted) {
                        CMS.debug("SecurityDataProcessor.recover(): allowEncDecyypt_recovery: true, symmetric key:  create blob with unwrapped key.");
                        pbeWrappedData = createEncryptedContentInfo(ct, null, unwrappedSecData, null, pass);
                    } else {
                        pbeWrappedData = createEncryptedContentInfo(ct, symKey, null, null, pass);
                    }

                } else if (dataType.equals(KeyRequestResource.PASS_PHRASE_TYPE)) {

                    CMS.debug("SecurityDataProcessor.recover(): encrypt stored passphrase with transport passphrase");
                    pbeWrappedData = createEncryptedContentInfo(ct, null, unwrappedSecData, null, pass);
                } else if (dataType.equals(KeyRequestResource.ASYMMETRIC_KEY_TYPE)) {
                    if (encrypted) {
                        CMS.debug("SecurityDataProcessor.recover(): allowEncDecyypt_recovery: true, asymmetric key:  create blob with unwrapped key.");
                        pbeWrappedData = createEncryptedContentInfo(ct, null, unwrappedSecData, null, pass);
                    } else {
                        CMS.debug("SecurityDataProcessor.recover(): wrap stored private key with transport passphrase");
                        pbeWrappedData = createEncryptedContentInfo(ct, null, null, privateKey,
                                pass);
                    }
                }

                params.put(IRequest.SECURITY_DATA_PASS_WRAPPED_DATA, pbeWrappedData);

            } catch (Exception e) {
                throw new EBaseException("Cannot unwrap passphrase: " + e, e);

            } finally {
                if (pass != null) {
                    pass.clear();
                }

                if (unwrappedPass != null) {
                    java.util.Arrays.fill(unwrappedPass, (byte) 0);
                }
            }

        } else {
            CMS.debug("SecurityDataProcessor.recover(): secure retrieved data with session key");

            if (dataType.equals(KeyRequestResource.SYMMETRIC_KEY_TYPE)) {
                CMS.debug("SecurityDataProcessor.recover(): wrap or encrypt stored symmetric key with session key");
                try {
                    if (encrypted) {
                        CMS.debug("SecurityDataProcessor.recover(): encrypt symmetric key with session key as per allowEncDecrypt_recovery: true.");
                        unwrappedSess = transportUnit.unwrap_session_key(ct, wrappedSessKey,
                                SymmetricKey.Usage.ENCRYPT, wrapParams);
                        key_data = CryptoUtil.encryptUsingSymmetricKey(
                                ct,
                                unwrappedSess,
                                unwrappedSecData,
                                wrapParams.getPayloadEncryptionAlgorithm(),
                                wrapParams.getPayloadEncryptionIV());
                    } else {
                        unwrappedSess = transportUnit.unwrap_session_key(ct, wrappedSessKey,
                                SymmetricKey.Usage.WRAP, wrapParams);
                        key_data = CryptoUtil.wrapUsingSymmetricKey(
                                ct,
                                unwrappedSess,
                                symKey,
                                wrapParams.getPayloadWrappingIV(),
                                wrapParams.getPayloadWrapAlgorithm());
                    }

                } catch (Exception e) {
                    throw new EBaseException("Cannot wrap symmetric key: " + e, e);
                }

            } else if (dataType.equals(KeyRequestResource.PASS_PHRASE_TYPE)) {
                CMS.debug("SecurityDataProcessor.recover(): encrypt stored passphrase with session key");
                try {
                    unwrappedSess = transportUnit.unwrap_session_key(ct, wrappedSessKey,
                            SymmetricKey.Usage.ENCRYPT, wrapParams);

                    key_data = CryptoUtil.encryptUsingSymmetricKey(
                            ct,
                            unwrappedSess,
                            unwrappedSecData,
                            wrapParams.getPayloadEncryptionAlgorithm(),
                            wrapParams.getPayloadEncryptionIV());
                } catch (Exception e) {
                    throw new EBaseException("Cannot encrypt passphrase: " + e, e);
                }

            } else if (dataType.equals(KeyRequestResource.ASYMMETRIC_KEY_TYPE)) {
                CMS.debug("SecurityDataProcessor.recover(): wrap or encrypt stored private key with session key");
                try {
                    if (encrypted) {
                        CMS.debug("SecurityDataProcessor.recover(): encrypt symmetric key.");
                        unwrappedSess = transportUnit.unwrap_session_key(ct, wrappedSessKey,
                                SymmetricKey.Usage.ENCRYPT, wrapParams);

                        key_data = CryptoUtil.encryptUsingSymmetricKey(
                                ct,
                                unwrappedSess,
                                unwrappedSecData,
                                wrapParams.getPayloadEncryptionAlgorithm(),
                                wrapParams.getPayloadEncryptionIV());

                    } else {
                        unwrappedSess = transportUnit.unwrap_session_key(ct, wrappedSessKey,
                                SymmetricKey.Usage.WRAP, wrapParams);
                        key_data = CryptoUtil.wrapUsingSymmetricKey(
                                ct,
                                unwrappedSess,
                                privateKey,
                                wrapParams.getPayloadWrappingIV(),
                                wrapParams.getPayloadWrapAlgorithm());
                    }

                } catch (Exception e) {
                    throw new EBaseException("Cannot wrap private key: " + e, e);
                }
            }

            String wrappedKeyData = Utils.base64encode(key_data);
            params.put(IRequest.SECURITY_DATA_SESS_WRAPPED_DATA, wrappedKeyData);
        }

        params.put(IRequest.SECURITY_DATA_PL_ENCRYPTION_OID,
                wrapParams.getPayloadEncryptionAlgorithmName());

        params.put(IRequest.SECURITY_DATA_PL_WRAPPING_NAME,
                wrapParams.getPayloadWrapAlgorithm().toString());

        if (encrypted || dataType.equals(KeyRequestResource.PASS_PHRASE_TYPE)) {
            params.put(IRequest.SECURITY_DATA_PL_WRAPPED, Boolean.toString(false));
            if (wrapParams.getPayloadEncryptionIV() != null) {
                params.put(IRequest.SECURITY_DATA_IV_STRING_OUT, ivStr);
            }
        } else {
            //secret has wrapped using a key wrapping algorithm
            params.put(IRequest.SECURITY_DATA_PL_WRAPPED, Boolean.toString(true));
            if (wrapParams.getPayloadWrappingIV() != null) {
                params.put(IRequest.SECURITY_DATA_IV_STRING_OUT, ivStr_wrap);
            }
        }

        if(unwrappedSecData != null && unwrappedSecData.length > 0) {
            Arrays.fill(unwrappedSecData, (byte)0);
        }

        params.put(IRequest.SECURITY_DATA_TYPE, dataType);
        request.setExtData(IRequest.RESULT, IRequest.RES_SUCCESS);

        return false; //return true ? TODO
    }

    /***
     * This method returns an IV for the Encryption Algorithm referenced in OID.
     * If the oid is null, we return an IV for the default encryption algorithm.
     * The method checks to see if the encryption algorithm requires an IV by checking
     * the parameterClasses() for the encryption algorithm.
     *
     * @param oid           -- OID of encryption algorithm (as a string)
     * @param defaultAlg    -- default encryption algorithm
     * @return              -- initialization vector or null if none needed
     * @throws Exception if algorithm is not found, or if default and OID are null.
     *                   (ie. algorithm is unknown)
     */
    private byte[] generate_iv(String oid, EncryptionAlgorithm defaultAlg) throws Exception {

        EncryptionAlgorithm alg = oid != null? EncryptionAlgorithm.fromOID(new OBJECT_IDENTIFIER(oid)):
            defaultAlg;

        if (alg == null) {
            throw new EBaseException("Cannot determine encryption algorithm to generate IV");
        };

        if (alg.getParameterClasses() == null)
            return null;

        int numBytes = alg.getIVLength();
        byte[] bytes = new byte[numBytes];

        JssSubsystem jssSubsystem = (JssSubsystem) CMS.getSubsystem(JssSubsystem.ID);
        SecureRandom random = jssSubsystem.getRandomNumberGenerator();
        random.nextBytes(bytes);

        return bytes;
    }

    /***
     * This method returns an IV for the KeyWrap algorithm referenced in wrapName.
     * If the wrapName is null, we return an IV for the default wrap algorithm.
     * The method checks to see if the key wrap algorithm requires an IV by checking
     * the parameterClasses() for the key wrap algorithm.
     *
     * @param wrapName      -- name of the key wrap algorithm (as defined in JSS)
     * @param defaultAlg    -- default wrapping parameters
     * @return              -- initialization vector or null if none needed
     * @throws Exception if algorithm is not found, or if default and OID are null.
     *                   (ie. algorithm is unknown)
     */
    private byte[] generate_wrap_iv(String wrapName, KeyWrapAlgorithm defaultAlg) throws Exception {

        KeyWrapAlgorithm alg = wrapName != null ? KeyWrapAlgorithm.fromString(wrapName) :
            defaultAlg;

        if (alg == null) {
            throw new EBaseException("Cannot determine keywrap algorithm to generate IV");
        }

        if (alg.getParameterClasses() == null)
            return null;

        int numBytes = alg.getBlockSize();
        byte[] bytes = new byte[numBytes];

        JssSubsystem jssSubsystem = (JssSubsystem) CMS.getSubsystem(JssSubsystem.ID);
        SecureRandom random = jssSubsystem.getRandomNumberGenerator();
        random.nextBytes(bytes);

        return bytes;
    }

    public SymmetricKey recoverSymKey(KeyRecord keyRecord)
            throws EBaseException {

        try {
            SymmetricKey symKey =
                    storageUnit.unwrap(
                            keyRecord.getPrivateKeyData(),
                            KeyRequestService.SYMKEY_TYPES.get(keyRecord.getAlgorithm()),
                            keyRecord.getKeySize(),
                            keyRecord.getWrappingParams(storageUnit.getOldWrappingParams()));
            return symKey;
        } catch (Exception e) {
            throw new EKRAException(CMS.getUserMessage("CMS_KRA_RECOVERY_FAILED_1",
                    "recoverSymKey() " + e.toString()));
        }
    }

    public byte[] recoverSecurityData(KeyRecord keyRecord)
            throws EBaseException {
        try {
            return storageUnit.decryptInternalPrivate(
                    keyRecord.getPrivateKeyData(),
                    keyRecord.getWrappingParams(storageUnit.getOldWrappingParams()));
        } catch (Exception e) {
            CMS.debug("Failed to recover security data: " + e);
            throw new EKRAException(CMS.getUserMessage("CMS_KRA_RECOVERY_FAILED_1",
                    "recoverSecurityData() " + e.toString()));
        }
    }

    //ToDo: This might fit in JSS.
    private static EncryptedContentInfo
            createEncryptedContentInfoPBEOfKey(PBEAlgorithm keyGenAlg, Password password, byte[] salt,
                    int iterationCount,
                    KeyGenerator.CharToByteConverter charToByteConverter,
                    SymmetricKey symKey, PrivateKey privateKey, CryptoToken token)
                    throws Exception {

        if (keyGenAlg == null) {
            throw new NoSuchAlgorithmException("Key generation algorithm  is NULL");
        }
        PBEAlgorithm pbeAlg = keyGenAlg;

        KeyGenerator kg = token.getKeyGenerator(keyGenAlg);
        PBEKeyGenParams pbekgParams = new PBEKeyGenParams(
                password, salt, iterationCount);
        if (charToByteConverter != null) {
            kg.setCharToByteConverter(charToByteConverter);
        }
        kg.initialize(pbekgParams);
        SymmetricKey key = kg.generate();

        EncryptionAlgorithm encAlg = pbeAlg.getEncryptionAlg();
        AlgorithmParameterSpec params = null;
        if (encAlg.getParameterClass().equals(IVParameterSpec.class)) {
            params = new IVParameterSpec(kg.generatePBE_IV());
        } else if (encAlg.getParameterClass().equals(
                RC2ParameterSpec.class)) {
            params = new RC2ParameterSpec(key.getStrength(),
                                kg.generatePBE_IV());
        }

        byte[] encrypted = null;
        if (symKey != null) {
            encrypted = CryptoUtil.wrapUsingSymmetricKey(token, key, symKey, (IVParameterSpec) params,
                    KeyWrapAlgorithm.DES3_CBC_PAD);
        } else if (privateKey != null) {
            encrypted = CryptoUtil.wrapUsingSymmetricKey(token, key, privateKey, (IVParameterSpec) params,
                    KeyWrapAlgorithm.DES3_CBC_PAD);
        }
        if (encrypted == null) {
            //TODO - think about the exception to be thrown
        }
        PBEParameter pbeParam = new PBEParameter(salt, iterationCount);
        AlgorithmIdentifier encAlgID = new AlgorithmIdentifier(
                keyGenAlg.toOID(), pbeParam);

        EncryptedContentInfo encCI = new EncryptedContentInfo(
                ContentInfo.DATA,
                encAlgID,
                new OCTET_STRING(encrypted));

        return encCI;

    }

    private static String createEncryptedContentInfo(CryptoToken ct, SymmetricKey symKey, byte[] securityData, PrivateKey privateKey,
            Password password)
            throws EBaseException {

        EncryptedContentInfo cInfo = null;
        String retData = null;
        PBEAlgorithm keyGenAlg = PBEAlgorithm.PBE_SHA1_DES3_CBC;

        byte[] encoded = null;
        try {
            PasswordConverter passConverter = new
                    PasswordConverter();
            byte salt[] = { 0x01, 0x01, 0x01, 0x01 };
            if (symKey != null) {

                cInfo = createEncryptedContentInfoPBEOfKey(keyGenAlg, password, salt,
                        1,
                        passConverter,
                        symKey, null, ct);

            } else if (securityData != null) {

                cInfo = EncryptedContentInfo.createPBE(keyGenAlg, password, salt, 1, passConverter, securityData);
            } else if (privateKey != null) {
                cInfo = createEncryptedContentInfoPBEOfKey(keyGenAlg, password, salt,
                        1,
                        passConverter,
                        null, privateKey, ct);
            }

            if(cInfo == null) {
                throw new EBaseException("Can't create a PBE wrapped EncryptedContentInfo!");
            }

            ByteArrayOutputStream oStream = new ByteArrayOutputStream();
            cInfo.encode(oStream);
            encoded = oStream.toByteArray();
            retData = Utils.base64encode(encoded);

        } catch (Exception e) {
            throw new EBaseException("Can't create a PBE wrapped EncryptedContentInfo! " + e.toString());
        }

        return retData;
    }

    private void audit(String msg) {
        signedAuditLogger.log(msg);
    }

    protected void audit(AuditEvent event) {

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

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

        audit(message);
    }

    private void auditArchivalRequestProcessed(String subjectID, String status, RequestId requestID, String clientKeyID,
            KeyId keyID, String reason) {
        audit(new SecurityDataArchivalProcessedEvent(
                subjectID,
                status,
                null,
                requestID,
                clientKeyID,
                keyID,
                reason,
                null));
    }
}