Remove catch(...) handler occurrences.
[shibboleth/cpp-xmltooling.git] / xmltooling / encryption / impl / Encrypter.cpp
1 /*
2  *  Copyright 2001-2006 Internet2
3  * 
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /**
18  * Encrypter.cpp
19  * 
20  * Methods for encrypting XMLObjects and other data.
21  */
22
23 #include "internal.h"
24 #include "encryption/Encrypter.h"
25
26 #include <xsec/enc/XSECCryptoException.hpp>
27 #include <xsec/framework/XSECException.hpp>
28 #include <xsec/framework/XSECAlgorithmMapper.hpp>
29 #include <xsec/framework/XSECAlgorithmHandler.hpp>
30 #include <xsec/xenc/XENCEncryptedData.hpp>
31 #include <xsec/xenc/XENCEncryptedKey.hpp>
32
33 using namespace xmlencryption;
34 using namespace xmlsignature;
35 using namespace xmltooling;
36 using namespace std;
37
38 Encrypter::~Encrypter()
39 {
40     XMLToolingInternalConfig::getInternalConfig().m_xsecProvider->releaseCipher(m_cipher);
41     memset(m_keyBuffer,0,32);
42 }
43
44 void Encrypter::checkParams(EncryptionParams& encParams, KeyEncryptionParams* kencParams)
45 {
46     if (encParams.m_keyBufferSize==0) {
47         if (encParams.m_key) {
48             if (kencParams)
49                 throw EncryptionException("Generating EncryptedKey inline requires the encryption key in raw form.");
50         }
51         else if (!encParams.m_key) {
52             if (!kencParams)
53                 throw EncryptionException("Using a generated encryption key requires a KeyEncryptionParams object.");
54
55             // We're generating a random key. The maximum supported length is AES-256, so we need 32 bytes.
56             if (XSECPlatformUtils::g_cryptoProvider->getRandom(m_keyBuffer,32)<32)
57                 throw EncryptionException("Unable to generate random data; was PRNG seeded?");
58             encParams.m_keyBuffer=m_keyBuffer;
59             encParams.m_keyBufferSize=32;
60         }
61     }
62     
63     if (!encParams.m_key) {
64         // We have to have a raw key now, so we need to build a wrapper around it.
65         XSECAlgorithmHandler* handler =XSECPlatformUtils::g_algorithmMapper->mapURIToHandler(encParams.m_algorithm);
66         if (handler != NULL)
67             encParams.m_key = handler->createKeyForURI(
68                 encParams.m_algorithm,const_cast<unsigned char*>(encParams.m_keyBuffer),encParams.m_keyBufferSize
69                 );
70
71         if (!encParams.m_key)
72             throw EncryptionException("Unable to build wrapper for key, unknown algorithm?");
73     }
74     
75     // Set the encryption key.
76     m_cipher->setKey(encParams.m_key->clone());
77 }
78
79 EncryptedData* Encrypter::encryptElement(DOMElement* element, EncryptionParams& encParams, KeyEncryptionParams* kencParams)
80 {
81     // We can reuse the cipher object if the document hasn't changed.
82     
83     if (m_cipher && m_cipher->getDocument()!=element->getOwnerDocument()) {
84         XMLToolingInternalConfig::getInternalConfig().m_xsecProvider->releaseCipher(m_cipher);
85         m_cipher=NULL;
86     }
87     
88     if (!m_cipher)
89         m_cipher=XMLToolingInternalConfig::getInternalConfig().m_xsecProvider->newCipher(element->getOwnerDocument());
90     
91     try {
92         checkParams(encParams,kencParams);
93         m_cipher->encryptElementDetached(element, ENCRYPT_NONE, encParams.m_algorithm);
94         return decorateAndUnmarshall(encParams, kencParams);
95     }
96     catch(XSECException& e) {
97         auto_ptr_char temp(e.getMsg());
98         throw EncryptionException(string("XMLSecurity exception while encrypting: ") + temp.get());
99     }
100     catch(XSECCryptoException& e) {
101         throw EncryptionException(string("XMLSecurity exception while encrypting: ") + e.getMsg());
102     }
103 }
104
105 EncryptedData* Encrypter::encryptElementContent(DOMElement* element, EncryptionParams& encParams, KeyEncryptionParams* kencParams)
106 {
107     // We can reuse the cipher object if the document hasn't changed.
108
109     if (m_cipher && m_cipher->getDocument()!=element->getOwnerDocument()) {
110         XMLToolingInternalConfig::getInternalConfig().m_xsecProvider->releaseCipher(m_cipher);
111         m_cipher=NULL;
112     }
113     
114     if (!m_cipher)
115         m_cipher=XMLToolingInternalConfig::getInternalConfig().m_xsecProvider->newCipher(element->getOwnerDocument());
116     
117     try {
118         checkParams(encParams,kencParams);
119         m_cipher->encryptElementContentDetached(element, ENCRYPT_NONE, encParams.m_algorithm);
120         return decorateAndUnmarshall(encParams, kencParams);
121     }
122     catch(XSECException& e) {
123         auto_ptr_char temp(e.getMsg());
124         throw EncryptionException(string("XMLSecurity exception while encrypting: ") + temp.get());
125     }
126     catch(XSECCryptoException& e) {
127         throw EncryptionException(string("XMLSecurity exception while encrypting: ") + e.getMsg());
128     }
129 }
130
131 EncryptedData* Encrypter::encryptStream(istream& input, EncryptionParams& encParams, KeyEncryptionParams* kencParams)
132 {
133     // Get a fresh cipher object and document.
134
135     if (m_cipher) {
136         XMLToolingInternalConfig::getInternalConfig().m_xsecProvider->releaseCipher(m_cipher);
137         m_cipher=NULL;
138     }
139     
140     DOMDocument* doc=NULL;
141     try {
142         doc=XMLToolingConfig::getConfig().getParser().newDocument();
143         XercesJanitor<DOMDocument> janitor(doc);
144         m_cipher=XMLToolingInternalConfig::getInternalConfig().m_xsecProvider->newCipher(doc);
145         
146         checkParams(encParams,kencParams);
147         StreamInputSource::StreamBinInputStream xstream(input);
148         m_cipher->encryptBinInputStream(&xstream, ENCRYPT_NONE, encParams.m_algorithm);
149         EncryptedData* xmlEncData = decorateAndUnmarshall(encParams, kencParams);
150         return xmlEncData;
151     }
152     catch(XSECException& e) {
153         auto_ptr_char temp(e.getMsg());
154         throw EncryptionException(string("XMLSecurity exception while encrypting: ") + temp.get());
155     }
156     catch(XSECCryptoException& e) {
157         throw EncryptionException(string("XMLSecurity exception while encrypting: ") + e.getMsg());
158     }
159 }
160
161 EncryptedData* Encrypter::decorateAndUnmarshall(EncryptionParams& encParams, KeyEncryptionParams* kencParams)
162 {
163     XENCEncryptedData* encData=m_cipher->getEncryptedData();
164     if (!encData)
165         throw EncryptionException("No EncryptedData element found?");
166
167     // Unmarshall a tooling version of EncryptedData around the DOM.
168     EncryptedData* xmlEncData=NULL;
169     auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(encData->getElement()));
170     if (!(xmlObject.get()) || !(xmlEncData=dynamic_cast<EncryptedData*>(xmlObject.get())))
171         throw EncryptionException("Unable to unmarshall into EncryptedData object.");
172     
173     // Unbind from DOM so we can divorce this from the original document.
174     xmlEncData->releaseThisAndChildrenDOM();
175     
176     // KeyInfo?
177     if (encParams.m_keyInfo) {
178         xmlEncData->setKeyInfo(encParams.m_keyInfo);
179         encParams.m_keyInfo=NULL;   // transfer ownership
180     }
181     
182     // Are we doing a key encryption?
183     if (kencParams) {
184         m_cipher->setKEK(kencParams->m_key->clone());
185         // ownership of this belongs to us, for some reason...
186         auto_ptr<XENCEncryptedKey> encKey(
187             m_cipher->encryptKey(encParams.m_keyBuffer, encParams.m_keyBufferSize, ENCRYPT_NONE, kencParams->m_algorithm)
188             );
189         EncryptedKey* xmlEncKey=NULL;
190         auto_ptr<XMLObject> xmlObjectKey(XMLObjectBuilder::buildOneFromElement(encKey->getElement()));
191         if (!(xmlObjectKey.get()) || !(xmlEncKey=dynamic_cast<EncryptedKey*>(xmlObjectKey.get())))
192             throw EncryptionException("Unable to unmarshall into EncryptedKey object.");
193         
194         xmlEncKey->releaseThisAndChildrenDOM();
195         
196         // Recipient?
197         if (kencParams->m_recipient)
198             xmlEncKey->setRecipient(kencParams->m_recipient);
199         
200         // KeyInfo?
201         if (kencParams->m_keyInfo) {
202             xmlEncKey->setKeyInfo(kencParams->m_keyInfo);
203             kencParams->m_keyInfo=NULL;   // transfer ownership
204         }
205         
206         // Add the EncryptedKey.
207         if (!xmlEncData->getKeyInfo())
208             xmlEncData->setKeyInfo(KeyInfoBuilder::buildKeyInfo());
209         xmlEncData->getKeyInfo()->getOthers().push_back(xmlEncKey);
210         xmlObjectKey.release();
211     }
212     
213     xmlObject.release();
214     return xmlEncData;
215 }
216
217 EncryptedKey* Encrypter::encryptKey(const unsigned char* keyBuffer, unsigned int keyBufferSize, KeyEncryptionParams& kencParams)
218 {
219     // Get a fresh cipher object and document.
220
221     if (m_cipher) {
222         XMLToolingInternalConfig::getInternalConfig().m_xsecProvider->releaseCipher(m_cipher);
223         m_cipher=NULL;
224     }
225     
226     DOMDocument* doc=NULL;
227     try {
228         doc=XMLToolingConfig::getConfig().getParser().newDocument();
229         XercesJanitor<DOMDocument> janitor(doc);
230         m_cipher=XMLToolingInternalConfig::getInternalConfig().m_xsecProvider->newCipher(doc);
231         m_cipher->setKEK(kencParams.m_key->clone());
232         auto_ptr<XENCEncryptedKey> encKey(m_cipher->encryptKey(keyBuffer, keyBufferSize, ENCRYPT_NONE, kencParams.m_algorithm));
233         
234         EncryptedKey* xmlEncKey=NULL;
235         auto_ptr<XMLObject> xmlObjectKey(XMLObjectBuilder::buildOneFromElement(encKey->getElement()));
236         if (!(xmlObjectKey.get()) || !(xmlEncKey=dynamic_cast<EncryptedKey*>(xmlObjectKey.get())))
237             throw EncryptionException("Unable to unmarshall into EncryptedKey object.");
238         
239         xmlEncKey->releaseThisAndChildrenDOM();
240         
241         // Recipient?
242         if (kencParams.m_recipient)
243             xmlEncKey->setRecipient(kencParams.m_recipient);
244
245         // KeyInfo?
246         if (kencParams.m_keyInfo) {
247             xmlEncKey->setKeyInfo(kencParams.m_keyInfo);
248             kencParams.m_keyInfo=NULL;   // transfer ownership
249         }
250
251         xmlObjectKey.release();
252         return xmlEncKey;
253     }
254     catch(XSECException& e) {
255         auto_ptr_char temp(e.getMsg());
256         throw EncryptionException(string("XMLSecurity exception while encrypting: ") + temp.get());
257     }
258     catch(XSECCryptoException& e) {
259         throw EncryptionException(string("XMLSecurity exception while encrypting: ") + e.getMsg());
260     }
261 }