File: XENCCipherImpl.cpp

package info (click to toggle)
xml-security-c 3.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 4,444 kB
  • sloc: cpp: 25,072; sh: 4,495; makefile: 361; perl: 228
file content (1104 lines) | stat: -rw-r--r-- 34,996 bytes parent folder | download
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
/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/*
 * XSEC
 *
 * XENCCipherImpl := Implementation of the main encryption worker class
 *
 * $Id$
 *
 */

// XSEC Includes

#include <xsec/enc/XSECKeyInfoResolver.hpp>
#include <xsec/enc/XSECCryptoException.hpp>
#include <xsec/framework/XSECAlgorithmMapper.hpp>
#include <xsec/framework/XSECAlgorithmHandler.hpp>
#include <xsec/framework/XSECDefs.hpp>
#include <xsec/framework/XSECEnv.hpp>
#include <xsec/framework/XSECError.hpp>
#include <xsec/enc/XSECCryptoKey.hpp>
#include <xsec/transformers/TXFMChain.hpp>
#include <xsec/transformers/TXFMBase.hpp>
#include <xsec/transformers/TXFMC14n.hpp>
#include <xsec/transformers/TXFMSB.hpp>
#include <xsec/transformers/TXFMURL.hpp>
#include <xsec/transformers/TXFMDocObject.hpp>
#include <xsec/transformers/TXFMConcatChains.hpp>
#include <xsec/utils/XSECPlatformUtils.hpp>
#include <xsec/utils/XSECBinTXFMInputStream.hpp>

#include "XENCCipherImpl.hpp"
#include "XENCEncryptedDataImpl.hpp"
#include "XENCEncryptedKeyImpl.hpp"
#include "XENCEncryptionMethodImpl.hpp"
#include "XENCAlgorithmHandlerDefault.hpp"
#include "../../utils/XSECAutoPtr.hpp"
#include "../../utils/XSECDOMUtils.hpp"

#include <xercesc/dom/DOMNode.hpp>
#include <xercesc/dom/DOMElement.hpp>
#include <xercesc/util/XMLUniDefs.hpp>
#include <xercesc/parsers/XercesDOMParser.hpp>
#include <xercesc/framework/MemBufInputSource.hpp>
#include <xercesc/util/Janitor.hpp>

// With all the characters - just uplift entire thing

XERCES_CPP_NAMESPACE_USE

#include <iostream>
using std::cout;

// --------------------------------------------------------------------------------
//			Constant Strings
// --------------------------------------------------------------------------------


const XMLCh s_tagname[] = {

chLatin_f, chLatin_r, chLatin_a, chLatin_g, chLatin_m, chLatin_e, chLatin_n, chLatin_t, chNull };

const XMLCh s_noData[] = { chLatin_n, chLatin_o, chLatin_D, chLatin_a, chLatin_t, chLatin_a, chNull };

const XMLCh s_ds[] = { chLatin_d, chLatin_s, chNull };

// --------------------------------------------------------------------------------
//			Constructors
// --------------------------------------------------------------------------------

XENCCipherImpl::XENCCipherImpl(DOMDocument * doc) :
    mp_doc(doc), mp_encryptedData(NULL), mp_key(NULL), mp_kek(NULL), mp_keyInfoResolver(NULL) {

    XSECnew(mp_env, XSECEnv(doc));
    mp_env->setDSIGNSPrefix(s_ds);
    m_keyDerived = false;
    m_kekDerived = false;
    m_useExcC14nSerialisation = true;

}

XENCCipherImpl::~XENCCipherImpl() {

    if (mp_encryptedData != NULL)
        delete mp_encryptedData;

    if (mp_key != NULL)
        delete mp_key;

    if (mp_kek != NULL)
        delete mp_kek;

    if (mp_env != NULL)
        delete mp_env;

    if (mp_keyInfoResolver != NULL)
        delete mp_keyInfoResolver;

}

// --------------------------------------------------------------------------------
//			Initialiser
// --------------------------------------------------------------------------------

void XENCCipherImpl::Initialise(void) {

    XENCAlgorithmHandlerDefault def;

    // Register default encryption algorithm handlers

    XSECPlatformUtils::registerAlgorithmHandler(DSIGConstants::s_unicodeStrURI3DES_CBC, def);
    XSECPlatformUtils::registerAlgorithmHandler(DSIGConstants::s_unicodeStrURIAES128_CBC, def);
    XSECPlatformUtils::registerAlgorithmHandler(DSIGConstants::s_unicodeStrURIAES192_CBC, def);
    XSECPlatformUtils::registerAlgorithmHandler(DSIGConstants::s_unicodeStrURIAES256_CBC, def);
    XSECPlatformUtils::registerAlgorithmHandler(DSIGConstants::s_unicodeStrURIAES128_GCM, def);
    XSECPlatformUtils::registerAlgorithmHandler(DSIGConstants::s_unicodeStrURIAES192_GCM, def);
    XSECPlatformUtils::registerAlgorithmHandler(DSIGConstants::s_unicodeStrURIAES256_GCM, def);
    XSECPlatformUtils::registerAlgorithmHandler(DSIGConstants::s_unicodeStrURIKW_3DES, def);
    XSECPlatformUtils::registerAlgorithmHandler(DSIGConstants::s_unicodeStrURIKW_AES128, def);
    XSECPlatformUtils::registerAlgorithmHandler(DSIGConstants::s_unicodeStrURIKW_AES192, def);
    XSECPlatformUtils::registerAlgorithmHandler(DSIGConstants::s_unicodeStrURIKW_AES256, def);
    //XSECPlatformUtils::registerAlgorithmHandler(DSIGConstants::s_unicodeStrURIKW_AES128_PAD, def);
    //XSECPlatformUtils::registerAlgorithmHandler(DSIGConstants::s_unicodeStrURIKW_AES192_PAD, def);
    //XSECPlatformUtils::registerAlgorithmHandler(DSIGConstants::s_unicodeStrURIKW_AES256_PAD, def);
    XSECPlatformUtils::registerAlgorithmHandler(DSIGConstants::s_unicodeStrURIRSA_1_5, def);
    XSECPlatformUtils::registerAlgorithmHandler(DSIGConstants::s_unicodeStrURIRSA_OAEP_MGFP1, def);
    XSECPlatformUtils::registerAlgorithmHandler(DSIGConstants::s_unicodeStrURIRSA_OAEP, def);

}

// --------------------------------------------------------------------------------
//			Set/get the namespace prefix to be used when creating nodes
// --------------------------------------------------------------------------------

void XENCCipherImpl::setXENCNSPrefix(const XMLCh * prefix) {

    mp_env->setXENCNSPrefix(prefix);

}

const XMLCh * XENCCipherImpl::getXENCNSPrefix(void) const {

    return mp_env->getXENCNSPrefix();

}
// --------------------------------------------------------------------------------
//			Key Info resolvers
// --------------------------------------------------------------------------------

void XENCCipherImpl::setKeyInfoResolver(const XSECKeyInfoResolver * resolver) {

    if (mp_keyInfoResolver != NULL)
        delete mp_keyInfoResolver;

    mp_keyInfoResolver = resolver->clone();

}

// --------------------------------------------------------------------------------
//			Key Info resolvers
// --------------------------------------------------------------------------------

XENCEncryptedData * XENCCipherImpl::getEncryptedData() const {

    return mp_encryptedData;

}
// --------------------------------------------------------------------------------
//			Keys
// --------------------------------------------------------------------------------

void XENCCipherImpl::setKey(XSECCryptoKey * key) {

    if (mp_key != NULL)
        delete mp_key;

    mp_key = key;
    m_keyDerived = false;

}

void XENCCipherImpl::setKEK(XSECCryptoKey * key) {

    if (mp_kek != NULL)
        delete mp_kek;

    mp_kek = key;
    m_kekDerived = false;

}

// --------------------------------------------------------------------------------
//			Serialise/Deserialise an element
// --------------------------------------------------------------------------------

DOMDocumentFragment * XENCCipherImpl::deSerialise(safeBuffer &content, DOMNode * ctx) {

    DOMDocumentFragment * result;

    // Create the context to parse the document against
    safeBuffer sb, sbt;
    sb.sbXMLChIn(DSIGConstants::s_unicodeStrEmpty);
    //sb.sbXMLChAppendCh(chUnicodeMarker);
    //sb.sbXMLChCat8("<?xml version=\"1.0\" encoding=\"UTF-16\"?><");
    sb.sbXMLChAppendCh(chOpenAngle);
    sb.sbXMLChCat(s_tagname);

    // Run through each node up to the document node and find any
    // xmlns: nodes that may be needed during the parse of the decrypted content

    DOMNode * ctxParent = ctx->getParentNode();
    DOMNode * wk = ctxParent;

    while (wk != NULL) {

        DOMNamedNodeMap * atts = wk->getAttributes();
        XMLSize_t length;
        if (atts != NULL)
            length = atts->getLength();
        else
            length = 0;

        for (XMLSize_t i = 0; i < length; ++i) {
            DOMNode * att = atts->item(i);
            if (strEquals(att->getNodeName(), DSIGConstants::s_unicodeStrXmlns) ||
                    (XMLString::compareNString(att->getNodeName(), DSIGConstants::s_unicodeStrXmlns, 5) == 0 &&
                            att->getNodeName()[5] == chColon)) {

                // Check to see if this node has already been found
                DOMNode * p = ctxParent;
                bool found = false;
                while (p != wk) {
                    DOMNamedNodeMap * tstAtts = p->getAttributes();
                    if (tstAtts != NULL && tstAtts->getNamedItem(att->getNodeName()) != NULL) {
                        found = true;
                        break;
                    }
                    p = p->getParentNode();
                }
                if (found == false) {

                    // This is an attribute node that needs to be added
                    sb.sbXMLChAppendCh(chSpace);
                    sb.sbXMLChCat(att->getNodeName());
                    sb.sbXMLChAppendCh(chEqual);
                    sb.sbXMLChAppendCh(chDoubleQuote);
                    sb.sbXMLChCat(att->getNodeValue());
                    sb.sbXMLChAppendCh(chDoubleQuote);
                }
            }
        }
        wk = wk->getParentNode();
    }
    sb.sbXMLChAppendCh(chCloseAngle);

    char* prefix = transcodeToUTF8(sb.rawXMLChBuffer());
    sbt = prefix;
    XSEC_RELEASE_XMLCH(prefix);

    const char * crcb = content.rawCharBuffer();
    int offset = 0;
    if (crcb[0] == '<' && crcb[1] == '?') {
        // Have a PI prefix - get rid of it
        int i = 2;
        while (crcb[i] != '\0' && crcb[i] != '>')
            ++i;

        if (crcb[i] == '>')
            offset = i + 1;
    }

    sbt.sbStrcatIn(&crcb[offset]);

    // Terminate the string
    sb.sbXMLChIn(DSIGConstants::s_unicodeStrEmpty);
    sb.sbXMLChAppendCh(chOpenAngle);
    sb.sbXMLChAppendCh(chForwardSlash);
    sb.sbXMLChCat(s_tagname);
    sb.sbXMLChAppendCh(chCloseAngle);

    char* trailer = transcodeToUTF8(sb.rawXMLChBuffer());
    sbt.sbStrcatIn(trailer);
    XSEC_RELEASE_XMLCH(trailer);

    // Create an input source
    XMLSize_t bytes = XMLString::stringLen(sbt.rawCharBuffer());
    MemBufInputSource memIS((const XMLByte*) sbt.rawBuffer(), bytes, "XSECMem");

    XercesDOMParser parser;
    parser.setDoNamespaces(true);
    parser.setLoadExternalDTD(false);

    SecurityManager securityManager;
    securityManager.setEntityExpansionLimit(XSEC_ENTITY_EXPANSION_LIMIT);
    parser.setSecurityManager(&securityManager);

    parser.parse(memIS);
    XMLSize_t errorCount = parser.getErrorCount();
    if (errorCount > 0)
        throw XSECException(XSECException::CipherError, "Errors occurred during de-serialisation of decrypted element content");

    DOMDocument * doc = parser.getDocument();

    // Create a DocumentFragment to hold the children of the parsed doc element
    DOMDocument *ctxDocument = ctx->getOwnerDocument();
    result = ctxDocument->createDocumentFragment();
    Janitor<DOMDocumentFragment> j_result(result);

    // Now get the children of the document into a DOC fragment
    DOMNode * fragElt = doc->getDocumentElement();
    DOMNode * child;

    if (fragElt != NULL) {
        child = fragElt->getFirstChild();
    } else {

        throw XSECException(XSECException::CipherError, "XENCCipher::deSerialse - re-parsed document unexpectedly empty");
    }

    while (child != NULL) {
        result->appendChild(ctxDocument->importNode(child, true));
        child = child->getNextSibling();
    }

    // Done!

    j_result.release();
    return result;
}

// --------------------------------------------------------------------------------
//			Decrypt an Element and replace in original document
// --------------------------------------------------------------------------------

XSECCryptoKey * XENCCipherImpl::decryptKeyFromKeyInfoList(DSIGKeyInfoList * kil) {

    XSECCryptoKey * ret = NULL;
    const XSECAlgorithmHandler *handler;

    int kLen = (int) kil->getSize();

    for (int i = 0; ret == NULL && i < kLen; ++i) {

        if (kil->item(i)->getKeyInfoType() == DSIGKeyInfo::KEYINFO_ENCRYPTEDKEY) {

            XENCEncryptedKey * ek = (XENCEncryptedKey*) (kil->item(i));
            volatile XMLByte buffer[1024];
            try {
                // Have to cast off volatile
                int keySize = decryptKey(ek, (XMLByte *) buffer, 1024);

                if (keySize > 0) {
                    // Try to map the key

                    XENCEncryptionMethod * encryptionMethod = mp_encryptedData->getEncryptionMethod();

                    if (encryptionMethod != NULL) {

                        handler = XSECPlatformUtils::g_algorithmMapper->mapURIToHandler(
                            mp_encryptedData->getEncryptionMethod()->getAlgorithm());

                        if (handler != NULL)
                            ret = handler->createKeyForURI(mp_encryptedData->getEncryptionMethod()->getAlgorithm(),
                                (XMLByte *) buffer, keySize);
                    }
                }
            }

            catch (const XSECCryptoException&) {
                /* Do nothing - this is likely to be a bad decrypt on a public key */
            } catch (...) {
                memset((void *) buffer, 0, 1024);
                throw;
            }

            // Clear out the key buffer
            memset((void *) buffer, 0, 1024);
        }
    }

    return ret;
}

XENCEncryptedData * XENCCipherImpl::loadEncryptedData(DOMElement * element) {

    // First of all load the element
    if (mp_encryptedData != NULL)
        delete mp_encryptedData;

    XSECnew(mp_encryptedData, XENCEncryptedDataImpl(mp_env, element));

    // Load
    mp_encryptedData->load();

    return mp_encryptedData;

}

DOMDocument * XENCCipherImpl::decryptElement(DOMElement * element) {

    // First of all load the element
    if (mp_encryptedData != NULL)
        delete mp_encryptedData;

    XSECnew(mp_encryptedData, XENCEncryptedDataImpl(mp_env, element));

    // Load
    mp_encryptedData->load();

    return decryptElement();

}

DOMNode * XENCCipherImpl::decryptElementDetached(DOMElement * element) {

    // First of all load the element
    if (mp_encryptedData != NULL)
        delete mp_encryptedData;

    XSECnew(mp_encryptedData, XENCEncryptedDataImpl(mp_env, element));

    // Load
    mp_encryptedData->load();

    return decryptElementDetached();

}

DOMNode * XENCCipherImpl::decryptElementDetached() {

    const XSECAlgorithmHandler *handler;

    if (mp_encryptedData == NULL) {

        throw XSECException(XSECException::CipherError, "XENCCipherImpl::decryptElement - no element loaded for decryption");

    }

    // Check that this is a valid type
    const XMLCh * typeURI = mp_encryptedData->getType();

    if (typeURI != NULL && !strEquals(typeURI, DSIGConstants::s_unicodeStrURIXENC_ELEMENT) && !strEquals(typeURI,
        DSIGConstants::s_unicodeStrURIXENC_CONTENT)) {

        throw XSECException(XSECException::CipherError, "XENCCipherImpl::decryptElement - Type not Element or Content");

    }

    if (m_keyDerived && mp_key) {
        delete mp_key;
        mp_key = NULL;
    }

    // Make sure we have a key before we do anything else too drastic
    if (mp_key == NULL) {

        if (mp_keyInfoResolver != NULL)
            mp_key = mp_keyInfoResolver->resolveKey(mp_encryptedData->getKeyInfoList());

        if (mp_key == NULL) {

            mp_key = decryptKeyFromKeyInfoList(mp_encryptedData->getKeyInfoList());

        }

        if (mp_key == NULL) {

            throw XSECException(XSECException::CipherError, "XENCCipherImpl::decryptElement - No key set and cannot resolve");
        }

        m_keyDerived = true;
    }

    // Get the raw encrypted data
    TXFMChain * c = mp_encryptedData->createCipherTXFMChain();
    Janitor<TXFMChain> j_c(c);

    // Get the Algorithm handler for the algorithm
    XENCEncryptionMethod * encryptionMethod = mp_encryptedData->getEncryptionMethod();

    if (encryptionMethod != NULL) {

        handler
            = XSECPlatformUtils::g_algorithmMapper->mapURIToHandler(mp_encryptedData->getEncryptionMethod()->getAlgorithm());

    }

    else {

        handler = XSECPlatformUtils::g_algorithmMapper->mapURIToHandler(XSECAlgorithmMapper::s_defaultEncryptionMapping);

    }

    safeBuffer sb("");
    unsigned int decryptLen;

    if (handler != NULL) {

        decryptLen = handler->decryptToSafeBuffer(c, mp_encryptedData->getEncryptionMethod(), mp_key,
            mp_env->getParentDocument(), sb);
    } else {

        // Very strange if we get here - any problems should throw an
        // exception in the AlgorithmMapper.

        throw XSECException(XSECException::CipherError,
            "XENCCipherImpl::decryptElement - Error retrieving a handler for algorithm");

    }

    sb[decryptLen] = '\0';

    // Now de-serialise
    DOMElement * element = mp_encryptedData->getElement();
    DOMDocumentFragment * frag = deSerialise(sb, element);

    return frag;

}

DOMDocument * XENCCipherImpl::decryptElement() {

    // Call the worker
    DOMElement * element = mp_encryptedData->getElement();
    DOMDocumentFragment * frag = (DOMDocumentFragment *) decryptElementDetached();

    if (frag != NULL) {

        // Have something to replace current element with
        DOMNode * p = element->getParentNode();

        // By inserting the DocumentFragment, we effectively insert the children
        p->replaceChild(frag, element);

        // Delete the frag and the old element
        frag->release();
        element->release();

    }

    return mp_env->getParentDocument();

}

// --------------------------------------------------------------------------------
//			Decrypt data to an input stream
// --------------------------------------------------------------------------------

XSECBinTXFMInputStream * XENCCipherImpl::decryptToBinInputStream(
    XERCES_CPP_NAMESPACE_QUALIFIER DOMElement * element
) {

    const XSECAlgorithmHandler *handler;

    // First of all load the element
    if (mp_encryptedData != NULL)
    	delete mp_encryptedData;

    XSECnew(mp_encryptedData,
        XENCEncryptedDataImpl(mp_env, element));

    // Load
    mp_encryptedData->load();

    // Check key is valid
    if (m_keyDerived && mp_key) {
        delete mp_key;
        mp_key = NULL;
    }

    // Make sure we have a key before we do anything else too drastic
    if (mp_key == NULL) {

        if (mp_keyInfoResolver != NULL)
        mp_key = mp_keyInfoResolver->resolveKey(mp_encryptedData->getKeyInfoList());

        if (mp_key == NULL) {

            mp_key = decryptKeyFromKeyInfoList(mp_encryptedData->getKeyInfoList());

        }

        if (mp_key == NULL) {

            throw XSECException(XSECException::CipherError,
                "XENCCipherImpl::decryptToBinInputStream - No key set and cannot resolve");
        }

        m_keyDerived = true;
    }

    // Get the raw encrypted data
    TXFMChain * c = mp_encryptedData->createCipherTXFMChain();
    Janitor<TXFMChain> j_c(c);

    // Get the Algorithm handler for the algorithm
    XENCEncryptionMethod * encryptionMethod = mp_encryptedData->getEncryptionMethod();

    if (encryptionMethod != NULL) {

        handler =
        XSECPlatformUtils::g_algorithmMapper->mapURIToHandler(
            mp_encryptedData->getEncryptionMethod()->getAlgorithm());

    }

    else {

        handler =
        XSECPlatformUtils::g_algorithmMapper->mapURIToHandler(
            XSECAlgorithmMapper::s_defaultEncryptionMapping);

    }

    if (handler != NULL) {

        if (handler->appendDecryptCipherTXFM(c,
                mp_encryptedData->getEncryptionMethod(),
                mp_key,
                mp_env->getParentDocument()) != true) {
            throw XSECException(XSECException::CipherError,
                "XENCCipherImpl::decryptToBinInputStream - error appending final transform");
        }

    }
    else {

        // Very strange if we get here - any problems should throw an
        // exception in the AlgorithmMapper.

        throw XSECException(XSECException::CipherError,
            "XENCCipherImpl::decryptElement - Error retrieving a handler for algorithm");

    }

    // Wrap in a Bin input stream
    XSECBinTXFMInputStream * ret;
    ret = new XSECBinTXFMInputStream(c); // Probs with MSVC++ mean no XSECnew
    j_c.release(); // Now owned by "ret"

    return ret;

}

// --------------------------------------------------------------------------------
//			Decrypt a key in an XENCEncryptedKey element
// --------------------------------------------------------------------------------

int XENCCipherImpl::decryptKey(XENCEncryptedKey * encryptedKey, XMLByte * rawKey, int maxKeySize) {

    // Check KEK is valid
    if (m_kekDerived && mp_kek) {
        delete mp_kek;
        mp_kek = NULL;
    }

    // Make sure we have a key before we do anything else too drastic
    if (mp_kek == NULL) {

        if (mp_keyInfoResolver != NULL)
            mp_kek = mp_keyInfoResolver->resolveKey(encryptedKey->getKeyInfoList());

        if (mp_kek == NULL) {

            throw XSECException(XSECException::CipherError, "XENCCipherImpl::decryptKey - No KEK set and cannot resolve");
        }
        m_kekDerived = true;
    }

    // Get the raw encrypted data
    TXFMChain * c = ((XENCEncryptedKeyImpl *) encryptedKey)->createCipherTXFMChain();
    Janitor<TXFMChain> j_c(c);

    // Get the Algorithm handler for the algorithm
    XENCEncryptionMethod * encryptionMethod = encryptedKey->getEncryptionMethod();
    const XSECAlgorithmHandler *handler;

    if (encryptionMethod != NULL) {

        handler = XSECPlatformUtils::g_algorithmMapper->mapURIToHandler(encryptedKey->getEncryptionMethod()->getAlgorithm());

    }

    else {

        handler = XSECPlatformUtils::g_algorithmMapper->mapURIToHandler(XSECAlgorithmMapper::s_defaultEncryptionMapping);

    }

    safeBuffer sb("");
    unsigned int keySize;

    if (handler != NULL) {

        keySize = handler->decryptToSafeBuffer(c, encryptedKey->getEncryptionMethod(), mp_kek, mp_env->getParentDocument(), sb);
    } else {

        // Very strange if we get here - any problems should throw an
        // exception in the AlgorithmMapper.

        throw XSECException(XSECException::CipherError,
            "XENCCipherImpl::decryptElement - Error retrieving a handler for algorithm");

    }

    keySize = (keySize < (unsigned int) maxKeySize ? keySize : (unsigned int) maxKeySize);
    memcpy(rawKey, sb.rawBuffer(), keySize);

    return keySize;
}
// --------------------------------------------------------------------------------
//			Decrypt a key from a DOM structure
// --------------------------------------------------------------------------------

int XENCCipherImpl::decryptKey(DOMElement * keyNode, XMLByte * rawKey, int maxKeySize) {

    XENCEncryptedKey * encryptedKey = loadEncryptedKey(keyNode);
    Janitor<XENCEncryptedKey> j_encryptedKey(encryptedKey);

    // Now decrypt!
    return decryptKey(encryptedKey, rawKey, maxKeySize);

}

XENCEncryptedKey * XENCCipherImpl::loadEncryptedKey(DOMElement * keyNode) {

    XENCEncryptedKeyImpl * encryptedKey;
    XSECnew(encryptedKey, XENCEncryptedKeyImpl(mp_env, keyNode));
    Janitor<XENCEncryptedKeyImpl> j_encryptedKey(encryptedKey);

    // Load
    encryptedKey->load();

    j_encryptedKey.release();
    return encryptedKey;

}
// --------------------------------------------------------------------------------
//			Encrypt a BinInputStream
// --------------------------------------------------------------------------------

XENCEncryptedData * XENCCipherImpl::encryptBinInputStream(
    XERCES_CPP_NAMESPACE_QUALIFIER BinInputStream * plainText,
    const XMLCh * algorithmURI) {

    TXFMURL * uri;
    XSECnew(uri, TXFMURL(mp_doc, NULL));

    uri->setInput(plainText);
    TXFMChain c(uri);

    return encryptTXFMChain(&c, algorithmURI);

}

// --------------------------------------------------------------------------------
//			Encrypt a TXFMChain
// --------------------------------------------------------------------------------

XENCEncryptedData * XENCCipherImpl::encryptTXFMChain(TXFMChain * plainText, const XMLCh * algorithmURI) {

    // Make sure we have a key before we do anything too drastic
    if (mp_key == NULL) {
        throw XSECException(XSECException::CipherError, "XENCCipherImpl::encryptTXFMChain - No key set");
    }
    else if (algorithmURI == NULL) {
        throw XSECException(XSECException::CipherError, "XENCCipherImpl::encryptTXFMChain - No algorithm set");
    }

    // Create the element with a dummy encrypted value

    if (mp_encryptedData != NULL) {
        delete mp_encryptedData;
        mp_encryptedData = NULL;
    }

    XSECnew(mp_encryptedData, XENCEncryptedDataImpl(mp_env));
    mp_encryptedData->createBlankEncryptedData(XENCCipherData::VALUE_TYPE, algorithmURI, s_noData);

    // Perform the encryption
    const XSECAlgorithmHandler *handler = XSECPlatformUtils::g_algorithmMapper->mapURIToHandler(algorithmURI);
    if (!handler) {
        // Very strange if we get here - any problems should throw an
        // exception in the AlgorithmMapper.

        throw XSECException(XSECException::CipherError,
            "XENCCipherImpl::encryptTXFMChain - Error retrieving a handler for algorithm");
    }

    safeBuffer sb;
    handler->encryptToSafeBuffer(plainText, mp_encryptedData->getEncryptionMethod(), mp_key, mp_env->getParentDocument(), sb);

    // Set the value
    XENCCipherValue * val = mp_encryptedData->getCipherData()->getCipherValue();

    val->setCipherString(sb.sbStrToXMLCh());

    return mp_encryptedData;

}

// --------------------------------------------------------------------------------
//			Encrypt a key
// --------------------------------------------------------------------------------

XENCEncryptedKey * XENCCipherImpl::encryptKey(
        const unsigned char* keyBuffer,
        unsigned int keyLen,
        const XMLCh* algorithmURI,
        const XMLCh* mgfURI,
        unsigned char* oaepParams,
        unsigned int oaepParamsLen) {

    if (mp_kek == NULL) {
        throw XSECException(XSECException::CipherError, "XENCCipherImpl::encryptKey - No KEK set");
    }
    else if (algorithmURI == NULL) {
        throw XSECException(XSECException::CipherError, "XENCCipherImpl::encryptKey - No algorithm set");
    }

    // Create the element with a dummy encrypted value

    XENCEncryptedKeyImpl * encryptedKey;

    XSECnew(encryptedKey, XENCEncryptedKeyImpl(mp_env));
    Janitor<XENCEncryptedKeyImpl> j_encryptedKey(encryptedKey);

    encryptedKey->createBlankEncryptedKey(XENCCipherData::VALUE_TYPE, algorithmURI, s_noData);

    if (mgfURI)
        encryptedKey->getEncryptionMethod()->setMGF(mgfURI);

    if (oaepParams != NULL && oaepParamsLen > 0) {
        unsigned char * oaepParamsB64;
        XSECnew(oaepParamsB64, unsigned char[oaepParamsLen * 2]);
        ArrayJanitor<unsigned char> j_oaepParamsB64(oaepParamsB64);

        XSECCryptoBase64 * b64 = XSECPlatformUtils::g_cryptoProvider->base64();
        Janitor<XSECCryptoBase64> j_b64(b64);

        b64->encodeInit();
        int sz = b64->encode(oaepParams, oaepParamsLen, oaepParamsB64, oaepParamsLen *2);
        sz += b64->encodeFinish(&oaepParamsB64[sz], (oaepParamsLen * 2)  - sz);
        oaepParamsB64[sz] = '\0';

        XSECAutoPtrXMLCh xBuf((char*) oaepParamsB64);

        encryptedKey->getEncryptionMethod()->setOAEPparams(xBuf.get());
    }

    // Create a transform chain to do pass the key to the encryption.

    safeBuffer rawKey;
    rawKey.isSensitive();
    rawKey.sbMemcpyIn(keyBuffer, keyLen);

    TXFMSB * tsb;
    XSECnew(tsb, TXFMSB(mp_doc));

    TXFMChain * c;
    XSECnew(c, TXFMChain(tsb));
    Janitor<TXFMChain> j_c(c);

    tsb->setInput(rawKey, keyLen);

    // Perform the encryption
    const XSECAlgorithmHandler *handler = XSECPlatformUtils::g_algorithmMapper->mapURIToHandler(algorithmURI);
    if (!handler) {
        // Very strange if we get here - any problems should throw an
        // exception in the AlgorithmMapper.

        throw XSECException(XSECException::CipherError, "XENCCipherImpl::encryptKey - Error retrieving a handler for algorithm");
    }

    safeBuffer sb;
    handler->encryptToSafeBuffer(c, encryptedKey->getEncryptionMethod(), mp_kek, mp_env->getParentDocument(), sb);

    // Set the value
    XENCCipherValue * val = encryptedKey->getCipherData()->getCipherValue();

    val->setCipherString(sb.sbStrToXMLCh());

    j_encryptedKey.release();
    return encryptedKey;
}

// --------------------------------------------------------------------------------
//			Create an EncryptedData element
// --------------------------------------------------------------------------------

XENCEncryptedData * XENCCipherImpl::createEncryptedData(XENCCipherData::XENCCipherDataType type, const XMLCh * algorithm,
    const XMLCh * value) {

    // Clean out anything currently being used
    if (mp_encryptedData != NULL) {
        delete mp_encryptedData;
        mp_encryptedData = NULL;
    }
    // Create a new EncryptedData element

    XSECnew(mp_encryptedData, XENCEncryptedDataImpl(mp_env));
    mp_encryptedData->createBlankEncryptedData(type, algorithm, value);

    return mp_encryptedData;
}

// --------------------------------------------------------------------------------
//			Encrypt an element
// --------------------------------------------------------------------------------

DOMNode * XENCCipherImpl::encryptElementDetached(DOMElement * element, const XMLCh * algorithmURI) {

    // Make sure we have a key before we do anything too drastic
    if (mp_key == NULL) {
        throw XSECException(XSECException::CipherError, "XENCCipherImpl::encryptElement - No key set");
    }
    else if (algorithmURI == NULL) {
        throw XSECException(XSECException::CipherError, "XENCCipherImpl::encryptElement - No algorithm set");
    }

    // Create a transform chain to do the encryption
    TXFMDocObject * tdocObj;
    XSECnew(tdocObj, TXFMDocObject(mp_doc));
    TXFMChain * c;
    XSECnew(c, TXFMChain(tdocObj));

    Janitor<TXFMChain> j_c(c);

    tdocObj->setInput(mp_doc, element);

    // Now need to serialise the element - easiest to just use a canonicalizer
    TXFMC14n *tc14n;
    XSECnew(tc14n, TXFMC14n(mp_doc));
    c->appendTxfm(tc14n);

    tc14n->activateComments();
    if (m_useExcC14nSerialisation)
        tc14n->setExclusive();

    // Do the hard work

    encryptTXFMChain(c, algorithmURI);

    mp_encryptedData->setType(DSIGConstants::s_unicodeStrURIXENC_ELEMENT);
    return mp_encryptedData->getElement();

}

DOMDocument * XENCCipherImpl::encryptElement(DOMElement * element, const XMLCh * algorithmURI) {

    // Do the actual encryption work
    encryptElementDetached(element, algorithmURI);

    // Replace original element
    DOMNode * p = element->getParentNode();

    if (p == NULL) {
        throw XSECException(XSECException::CipherError, "XENCCipherImpl::encryptElement - Passed in element has no parent");
    }

    p->replaceChild(mp_encryptedData->getElement(), element);

    // Clear up the old child
    element->release();

    return mp_doc;

}

// --------------------------------------------------------------------------------
//			Encrypt an element's children
// --------------------------------------------------------------------------------

DOMDocument * XENCCipherImpl::encryptElementContent(
    XERCES_CPP_NAMESPACE_QUALIFIER DOMElement * element,
    const XMLCh * algorithmURI) {

    // Do the work
    encryptElementContentDetached(element, algorithmURI);

    // Delete current children
    DOMNode * n = element->getFirstChild();
    while (n != NULL) {

        element->removeChild(n);
        n->release();

        n = element->getFirstChild();

    }

    // Now add the EncryptedData
    element->appendChild(mp_encryptedData->getElement());

    return mp_doc;

}

DOMNode * XENCCipherImpl::encryptElementContentDetached(
    XERCES_CPP_NAMESPACE_QUALIFIER DOMElement * element,
    const XMLCh * algorithmURI) {

    // Make sure we have a key before we do anything too drastic
    if (mp_key == NULL) {
        throw XSECException(XSECException::CipherError,
            "XENCCipherImpl::encryptElementContentDetached - No key set");
    }
    else if (algorithmURI == NULL) {
        throw XSECException(XSECException::CipherError, "XENCCipherImpl::encryptElementContentDetached - No algorithm set");
    }

    // Create a transform chain to do the encryption
    // We use a concat transformer so we can concatinate the bytestreams
    // from the serialisation of each child in turn

    TXFMConcatChains * tcat;
    XSECnew(tcat, TXFMConcatChains(mp_doc));
    TXFMChain * c;
    XSECnew(c, TXFMChain(tcat));
    Janitor<TXFMChain> j_c(c);

    DOMNode *n = element->getFirstChild();

    while (n != NULL) {

        TXFMDocObject * tdocObj;
        XSECnew(tdocObj, TXFMDocObject(mp_doc));
        TXFMChain * tc;
        XSECnew(tc, TXFMChain(tdocObj));

        // Add to the concat object, which will own it, so if anything throws
        // the memory will be released.

        tcat->setInput(tc);
        tdocObj->setInput(mp_doc, n);

        // Now need to serialise the element - easiest to just use a canonicaliser
        TXFMC14n *tc14n;
        XSECnew(tc14n, TXFMC14n(mp_doc));
        tc->appendTxfm(tc14n);

        tc14n->activateComments();
        if (m_useExcC14nSerialisation)
        tc14n->setExclusive();

        n = n->getNextSibling();

    }

    encryptTXFMChain(c, algorithmURI);

    mp_encryptedData->setType(DSIGConstants::s_unicodeStrURIXENC_CONTENT);

    return mp_encryptedData->getElement();

}

// --------------------------------------------------------------------------------
//			Pretty Print functions
// --------------------------------------------------------------------------------

void XENCCipherImpl::setExclusiveC14nSerialisation(bool flag) {

    m_useExcC14nSerialisation = flag;
}

bool XENCCipherImpl::getExclusiveC14nSerialisation() const {

    return m_useExcC14nSerialisation;

}

// --------------------------------------------------------------------------------
//			Exclusive C14n serialisation setting
// --------------------------------------------------------------------------------

void XENCCipherImpl::setPrettyPrint(bool flag) {

    mp_env->setPrettyPrintFlag(flag);

}

bool XENCCipherImpl::getPrettyPrint(void) const {

    return mp_env->getPrettyPrintFlag();

}