Update copyright.
[shibboleth/cpp-xmltooling.git] / xmltooling / signature / impl / SignatureValidator.cpp
1 /*
2  *  Copyright 2001-2007 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  * SignatureValidator.cpp
19  * 
20  * Validator for signatures based on an externally-supplied key 
21  */
22  
23 #include "internal.h"
24 #include "signature/SignatureValidator.h"
25
26 #include <xsec/enc/XSECCryptoException.hpp>
27 #include <xsec/framework/XSECException.hpp>
28
29 using namespace xmlsignature;
30 using namespace xmltooling;
31 using namespace std;
32
33 void SignatureValidator::validate(const XMLObject* xmlObject) const
34 {
35     const Signature* sigObj=dynamic_cast<const Signature*>(xmlObject);
36     if (!sigObj)
37         throw ValidationException("Validator only applies to Signature objects.");
38     validate(sigObj);
39 }
40
41 void SignatureValidator::validate(const Signature* sigObj) const
42 {
43     DSIGSignature* sig=sigObj->getXMLSignature();
44     if (!sig)
45         throw ValidationException("Signature does not exist yet.");
46     else if (!m_key && !m_resolver)
47         throw ValidationException("No KeyResolver or signing key set on Validator.");
48
49     try {
50         XSECCryptoKey* key = m_key ? m_key->clone() : m_resolver->resolveKey(sig->getKeyInfoList());
51         if (!key)
52             throw ValidationException("Unable to resolve signing key.");
53         sig->setSigningKey(key);
54         if (!sig->verify())
55             throw ValidationException("Digital signature does not validate with the given key.");
56     }
57     catch(XSECException& e) {
58         auto_ptr_char temp(e.getMsg());
59         throw ValidationException(string("Caught an XMLSecurity exception verifying signature: ") + temp.get());
60     }
61     catch(XSECCryptoException& e) {
62         throw ValidationException(string("Caught an XMLSecurity exception verifying signature: ") + e.getMsg());
63     }
64 }