Source Code Cross Referenced for SBIssuedSamlTokenContractImpl.java in  » 6.0-JDK-Modules-com.sun » wsit » com » sun » xml » ws » security » trust » impl » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » 6.0 JDK Modules com.sun » wsit » com.sun.xml.ws.security.trust.impl 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /*
002:         * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
003:         * 
004:         * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
005:         * 
006:         * The contents of this file are subject to the terms of either the GNU
007:         * General Public License Version 2 only ("GPL") or the Common Development
008:         * and Distribution License("CDDL") (collectively, the "License").  You
009:         * may not use this file except in compliance with the License. You can obtain
010:         * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
011:         * or glassfish/bootstrap/legal/LICENSE.txt.  See the License for the specific
012:         * language governing permissions and limitations under the License.
013:         * 
014:         * When distributing the software, include this License Header Notice in each
015:         * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
016:         * Sun designates this particular file as subject to the "Classpath" exception
017:         * as provided by Sun in the GPL Version 2 section of the License file that
018:         * accompanied this code.  If applicable, add the following below the License
019:         * Header, with the fields enclosed by brackets [] replaced by your own
020:         * identifying information: "Portions Copyrighted [year]
021:         * [name of copyright owner]"
022:         * 
023:         * Contributor(s):
024:         * 
025:         * If you wish your version of this file to be governed by only the CDDL or
026:         * only the GPL Version 2, indicate your decision by adding "[Contributor]
027:         * elects to include this software in this distribution under the [CDDL or GPL
028:         * Version 2] license."  If you don't indicate a single choice of license, a
029:         * recipient has the option to distribute your version of this file under
030:         * either the CDDL, the GPL Version 2 or to extend the choice of license to
031:         * its licensees as provided above.  However, if you add GPL Version 2 code
032:         * and therefore, elected the GPL Version 2 license, then the option applies
033:         * only if the new code is made subject to such option by the copyright
034:         * holder.
035:         */
036:
037:        package com.sun.xml.ws.security.trust.impl;
038:
039:        import com.sun.xml.ws.api.security.trust.STSAttributeProvider;
040:
041:        import com.sun.xml.security.core.dsig.ObjectFactory;
042:        import com.sun.xml.security.core.xenc.CipherDataType;
043:        import com.sun.xml.security.core.xenc.EncryptedDataType;
044:        import com.sun.xml.security.core.xenc.EncryptionMethodType;
045:        import com.sun.xml.ws.api.SOAPVersion;
046:        import com.sun.xml.ws.security.IssuedTokenContext;
047:        import com.sun.xml.ws.security.opt.api.SecurityElement;
048:        import com.sun.xml.ws.security.opt.api.SecurityHeaderElement;
049:        import com.sun.xml.ws.security.opt.api.keyinfo.SecurityTokenReference;
050:        import com.sun.xml.ws.security.opt.crypto.dsig.Signature;
051:        import com.sun.xml.ws.security.opt.crypto.dsig.keyinfo.DSAKeyValue;
052:        import com.sun.xml.ws.security.opt.crypto.dsig.keyinfo.KeyInfo;
053:        import com.sun.xml.ws.security.opt.crypto.dsig.keyinfo.RSAKeyValue;
054:        import com.sun.xml.ws.security.opt.crypto.dsig.keyinfo.X509Data;
055:        import com.sun.xml.ws.security.opt.crypto.jaxb.JAXBSignContext;
056:        import com.sun.xml.ws.security.opt.crypto.jaxb.JAXBSignatureFactory;
057:        import com.sun.xml.ws.security.opt.impl.crypto.SSEData;
058:        import com.sun.xml.ws.security.opt.impl.dsig.DSigResolver;
059:        import com.sun.xml.ws.security.opt.impl.dsig.EnvelopedSignedMessageHeader;
060:        import com.sun.xml.ws.security.opt.impl.dsig.JAXBSignatureHeaderElement;
061:        import com.sun.xml.ws.security.opt.impl.enc.JAXBEncryptedData;
062:        import com.sun.xml.ws.security.opt.impl.keyinfo.SAMLToken;
063:        import com.sun.xml.ws.security.opt.impl.reference.KeyIdentifier;
064:        import com.sun.xml.ws.security.opt.impl.util.NamespaceContextEx;
065:        import com.sun.xml.ws.security.opt.impl.util.WSSElementFactory;
066:        import com.sun.xml.wss.impl.MessageConstants;
067:        import com.sun.xml.wss.saml.NameID;
068:        import com.sun.xml.wss.saml.util.SAMLJAXBUtil;
069:
070:        import java.io.IOException;
071:        import java.security.InvalidAlgorithmParameterException;
072:        import java.security.Key;
073:        import java.security.NoSuchAlgorithmException;
074:        import java.security.Principal;
075:        import java.security.PrivateKey;
076:        import java.security.PublicKey;
077:        import java.security.cert.CertificateEncodingException;
078:        import java.security.cert.X509Certificate;
079:        import java.security.interfaces.DSAPublicKey;
080:        import java.security.interfaces.RSAPublicKey;
081:        import java.util.ArrayList;
082:        import java.util.Calendar;
083:        import java.util.Collections;
084:        import java.util.GregorianCalendar;
085:        import java.util.HashMap;
086:        import java.util.Iterator;
087:        import java.util.List;
088:        import java.util.Map;
089:        import java.util.Set;
090:        import java.util.UUID;
091:        import com.sun.xml.ws.security.opt.api.EncryptedKey;
092:
093:        import javax.crypto.spec.SecretKeySpec;
094:        import javax.security.auth.callback.Callback;
095:        import javax.security.auth.callback.CallbackHandler;
096:        import javax.xml.crypto.Data;
097:        import javax.xml.crypto.URIDereferencer;
098:        import javax.xml.crypto.URIReference;
099:        import javax.xml.crypto.URIReferenceException;
100:        import javax.xml.crypto.XMLCryptoContext;
101:        import javax.xml.crypto.dsig.CanonicalizationMethod;
102:        import javax.xml.crypto.dsig.DigestMethod;
103:        import javax.xml.crypto.dsig.Reference;
104:        import javax.xml.crypto.dsig.SignatureMethod;
105:        import javax.xml.crypto.dsig.SignedInfo;
106:        import javax.xml.crypto.dsig.Transform;
107:        import javax.xml.crypto.dsig.XMLSignContext;
108:        import javax.xml.crypto.dsig.keyinfo.KeyValue;
109:        import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;
110:        import javax.xml.crypto.dsig.spec.TransformParameterSpec;
111:
112:        import com.sun.xml.ws.api.security.trust.WSTrustException;
113:        import com.sun.xml.ws.api.security.trust.config.TrustSPMetadata;
114:        import com.sun.xml.ws.security.Token;
115:        import com.sun.xml.ws.security.trust.GenericToken;
116:        import com.sun.xml.ws.security.trust.WSTrustConstants;
117:        import com.sun.xml.ws.security.trust.util.WSTrustUtil;
118:        import com.sun.xml.ws.security.trust.elements.BinarySecret;
119:
120:        import com.sun.xml.wss.impl.callback.EncryptionKeyCallback;
121:        import com.sun.xml.wss.impl.callback.SignatureKeyCallback;
122:        import com.sun.xml.wss.XWSSecurityException;
123:        import com.sun.xml.wss.saml.Advice;
124:        import com.sun.xml.wss.saml.Assertion;
125:        import com.sun.xml.wss.saml.Attribute;
126:        import com.sun.xml.wss.saml.AttributeStatement;
127:        import com.sun.xml.wss.saml.Conditions;
128:        import com.sun.xml.wss.saml.NameIdentifier;
129:        import com.sun.xml.wss.saml.SAMLAssertionFactory;
130:        import com.sun.xml.wss.saml.SAMLException;
131:        import com.sun.xml.wss.saml.SubjectConfirmation;
132:        import com.sun.xml.wss.saml.SubjectConfirmationData;
133:
134:        import javax.security.auth.Subject;
135:        import javax.security.auth.callback.UnsupportedCallbackException;
136:
137:        import javax.xml.bind.JAXBElement;
138:        import javax.xml.namespace.QName;
139:
140:        import java.util.logging.Level;
141:        import java.util.logging.Logger;
142:        import com.sun.xml.ws.security.trust.logging.LogDomainConstants;
143:        import com.sun.xml.ws.security.trust.logging.LogStringsMessages;
144:
145:        /**
146:         *
147:         * @author
148:         */
149:        public class SBIssuedSamlTokenContractImpl extends
150:                IssueSamlTokenContract {
151:
152:            //move to base class
153:            private static final String SAML_HOLDER_OF_KEY = "urn:oasis:names:tc:SAML:1.0:cm:holder-of-key";
154:            protected static final String PRINCIPAL = "principal";
155:            private SOAPVersion soapVersion = SOAPVersion.SOAP_11;
156:            WSSElementFactory wef = new WSSElementFactory(SOAPVersion.SOAP_11);//TODO:: Pick up proper SOAPVersion.
157:
158:            private static final Logger log = Logger.getLogger(
159:                    LogDomainConstants.TRUST_IMPL_DOMAIN,
160:                    LogDomainConstants.TRUST_IMPL_DOMAIN_BUNDLE);
161:
162:            /** Creates a new instance of SBIssuedSamlTokenContractImpl */
163:            public SBIssuedSamlTokenContractImpl(SOAPVersion soapVersion) {
164:                this .soapVersion = soapVersion;
165:            }
166:
167:            public SBIssuedSamlTokenContractImpl() {
168:                //constructor
169:            }
170:
171:            public Token createSAMLAssertion(final String appliesTo,
172:                    final String tokenType, final String keyType,
173:                    final String assertionId, final String issuer,
174:                    final Map<QName, List<String>> claimedAttrs,
175:                    final IssuedTokenContext context) throws WSTrustException {
176:                Token token = null;
177:
178:                final CallbackHandler callbackHandler = stsConfig
179:                        .getCallbackHandler();
180:
181:                try {
182:                    NamespaceContextEx nsContext = null;
183:                    if (soapVersion == soapVersion.SOAP_11) {
184:                        nsContext = new NamespaceContextEx();
185:                    } else {
186:                        nsContext = new NamespaceContextEx(true);
187:                    }
188:                    nsContext.addEncryptionNS();
189:                    nsContext.addExc14NS();
190:                    nsContext.addSAMLNS();
191:                    nsContext.addSignatureNS();
192:                    nsContext.addWSSNS();
193:                    // Get the service certificate
194:                    final X509Certificate serCert = getServiceCertificate(
195:                            callbackHandler, stsConfig
196:                                    .getTrustSPMetadata(appliesTo), appliesTo);
197:
198:                    // Create the KeyInfo for SubjectConfirmation
199:                    final KeyInfo keyInfo = createKeyInfo(keyType, serCert,
200:                            context);
201:
202:                    // Create SAML assertion
203:                    Assertion assertion = null;
204:                    SAMLToken samlToken = null;
205:                    if (WSTrustConstants.SAML10_ASSERTION_TOKEN_TYPE
206:                            .equals(tokenType)
207:                            || WSTrustConstants.SAML11_ASSERTION_TOKEN_TYPE
208:                                    .equals(tokenType)) {
209:                        assertion = createSAML11Assertion(assertionId, issuer,
210:                                appliesTo, keyInfo, claimedAttrs);
211:                        samlToken = new SAMLToken(assertion, SAMLJAXBUtil
212:                                .getJAXBContext(), soapVersion);
213:
214:                    } else if (WSTrustConstants.SAML20_ASSERTION_TOKEN_TYPE
215:                            .equals(tokenType)) {
216:                        assertion = createSAML20Assertion(assertionId, issuer,
217:                                appliesTo, keyInfo, claimedAttrs);
218:                        samlToken = new SAMLToken(assertion, SAMLJAXBUtil
219:                                .getJAXBContext(), soapVersion);
220:                    } else {
221:                        log.log(Level.SEVERE, LogStringsMessages
222:                                .WST_0031_UNSUPPORTED_TOKEN_TYPE(tokenType,
223:                                        appliesTo));
224:                        throw new WSTrustException(LogStringsMessages
225:                                .WST_0031_UNSUPPORTED_TOKEN_TYPE(tokenType,
226:                                        appliesTo));
227:                    }
228:
229:                    // Get the STS's public and private key
230:                    final SignatureKeyCallback.DefaultPrivKeyCertRequest request = new SignatureKeyCallback.DefaultPrivKeyCertRequest();
231:                    final Callback skc = new SignatureKeyCallback(request);
232:                    final Callback[] callbacks = { skc };
233:                    callbackHandler.handle(callbacks);
234:                    final PrivateKey stsPrivKey = request.getPrivateKey();
235:
236:                    // Sign the assertion with STS's private key
237:                    //Element signedAssertion = assertion.sign(request.getX509Certificate(), stsPrivKey);
238:                    final SecurityHeaderElement signedAssertion = createSignature(
239:                            request.getX509Certificate().getPublicKey(),
240:                            stsPrivKey, samlToken, nsContext);
241:
242:                    //javax.xml.bind.Unmarshaller u = eleFac.getContext().createUnmarshaller();
243:                    //JAXBElement<AssertionType> aType = u.unmarshal(signedAssertion, AssertionType.class);
244:                    //assertion =  new com.sun.xml.wss.saml.assertion.saml11.jaxb20.Assertion(aType.getValue());
245:                    token = new GenericToken(signedAssertion);
246:
247:                    if (stsConfig.getEncryptIssuedToken()) {
248:                        final String id = "uuid-"
249:                                + UUID.randomUUID().toString();
250:                        final int keysizeInBytes = 32;
251:                        final byte[] skey = WSTrustUtil
252:                                .generateRandomSecret(keysizeInBytes);
253:                        final Key key = new SecretKeySpec(skey, "AES");
254:
255:                        final KeyInfo encKeyInfo = new KeyInfo();
256:                        final EncryptedKey encKey = encryptKey(key, serCert);
257:                        encKeyInfo.getContent().add(encKey);
258:                        final EncryptedDataType edt = createEncryptedData(id,
259:                                MessageConstants.AES_BLOCK_ENCRYPTION_256,
260:                                encKeyInfo, false);
261:
262:                        final JAXBEncryptedData jed = new JAXBEncryptedData(
263:                                edt, new SSEData(
264:                                        (SecurityElement) signedAssertion,
265:                                        false, nsContext), soapVersion);
266:                        token = new GenericToken(jed);
267:                    } else {
268:                        token = new GenericToken(signedAssertion);
269:                    }
270:                } catch (XWSSecurityException ex) {
271:                    log.log(Level.SEVERE, LogStringsMessages
272:                            .WST_0032_ERROR_CREATING_SAML_ASSERTION(), ex);
273:                    throw new WSTrustException(LogStringsMessages
274:                            .WST_0032_ERROR_CREATING_SAML_ASSERTION(), ex);
275:                } catch (Exception ex) {
276:                    log.log(Level.SEVERE, LogStringsMessages
277:                            .WST_0032_ERROR_CREATING_SAML_ASSERTION(), ex);
278:                    throw new WSTrustException(LogStringsMessages
279:                            .WST_0032_ERROR_CREATING_SAML_ASSERTION(), ex);
280:                }
281:                return token;
282:            }
283:
284:            private Assertion createSAML11Assertion(final String assertionId,
285:                    final String issuer, final String appliesTo,
286:                    final KeyInfo keyInfo,
287:                    final Map<QName, List<String>> claimedAttrs)
288:                    throws WSTrustException {
289:                Assertion assertion = null;
290:                try {
291:                    final SAMLAssertionFactory samlFac = SAMLAssertionFactory
292:                            .newInstance(SAMLAssertionFactory.SAML1_1);
293:
294:                    final GregorianCalendar issuerInst = new GregorianCalendar();
295:                    final GregorianCalendar notOnOrAfter = new GregorianCalendar();
296:                    notOnOrAfter.add(Calendar.MILLISECOND, (int) stsConfig
297:                            .getIssuedTokenTimeout());
298:
299:                    final Conditions conditions = samlFac.createConditions(
300:                            issuerInst, notOnOrAfter, null, null, null);
301:                    final Advice advice = samlFac
302:                            .createAdvice(null, null, null);
303:
304:                    final List<String> confirmMethods = new ArrayList<String>();
305:                    confirmMethods.add(SAML_HOLDER_OF_KEY);
306:
307:                    final SubjectConfirmation subjectConfirm = samlFac
308:                            .createSubjectConfirmation(confirmMethods, null,
309:                                    keyInfo);
310:
311:                    com.sun.xml.wss.saml.Subject subj = null;
312:                    final List<Attribute> attrs = new ArrayList<Attribute>();
313:                    final Set<Map.Entry<QName, List<String>>> entries = claimedAttrs
314:                            .entrySet();
315:                    for (Map.Entry<QName, List<String>> entry : entries) {
316:                        final QName attrKey = (QName) entry.getKey();
317:                        final List<String> values = (List<String>) entry
318:                                .getValue();
319:                        if (values != null && values.size() > 0) {
320:                            if (STSAttributeProvider.NAME_IDENTIFIER
321:                                    .equals(attrKey.getLocalPart())
322:                                    && subj == null) {
323:                                final NameIdentifier nameId = samlFac
324:                                        .createNameIdentifier(values.get(0),
325:                                                attrKey.getNamespaceURI(), null);
326:                                subj = samlFac.createSubject(nameId,
327:                                        subjectConfirm);
328:                            } else {
329:                                final Attribute attr = samlFac.createAttribute(
330:                                        attrKey.getLocalPart(), attrKey
331:                                                .getNamespaceURI(), values);
332:                                attrs.add(attr);
333:                            }
334:                        }
335:                    }
336:                    final AttributeStatement statement = samlFac
337:                            .createAttributeStatement(subj, attrs);
338:                    final List<AttributeStatement> statements = new ArrayList<AttributeStatement>();
339:                    statements.add(statement);
340:                    assertion = samlFac.createAssertion(assertionId, issuer,
341:                            issuerInst, conditions, advice, statements);
342:                } catch (SAMLException ex) {
343:                    log.log(Level.SEVERE, LogStringsMessages
344:                            .WST_0032_ERROR_CREATING_SAML_ASSERTION(), ex);
345:                    throw new WSTrustException(LogStringsMessages
346:                            .WST_0032_ERROR_CREATING_SAML_ASSERTION(), ex);
347:                } catch (XWSSecurityException ex) {
348:                    log.log(Level.SEVERE, LogStringsMessages
349:                            .WST_0032_ERROR_CREATING_SAML_ASSERTION(), ex);
350:                    throw new WSTrustException(LogStringsMessages
351:                            .WST_0032_ERROR_CREATING_SAML_ASSERTION(), ex);
352:                }
353:
354:                return assertion;
355:            }
356:
357:            private Assertion createSAML20Assertion(final String assertionId,
358:                    final String issuer, final String appliesTo,
359:                    final KeyInfo keyInfo,
360:                    final Map<QName, List<String>> claimedAttrs)
361:                    throws WSTrustException {
362:                Assertion assertion = null;
363:                try {
364:                    final SAMLAssertionFactory samlFac = SAMLAssertionFactory
365:                            .newInstance(SAMLAssertionFactory.SAML2_0);
366:
367:                    // Create Conditions
368:                    final GregorianCalendar issueInst = new GregorianCalendar();
369:                    final GregorianCalendar notOnOrAfter = new GregorianCalendar();
370:                    notOnOrAfter.add(Calendar.MILLISECOND, (int) stsConfig
371:                            .getIssuedTokenTimeout());
372:
373:                    final Conditions conditions = samlFac.createConditions(
374:                            issueInst, notOnOrAfter, null, null, null, null);
375:
376:                    // Create Subject
377:
378:                    final SubjectConfirmationData subjComfData = samlFac
379:                            .createSubjectConfirmationData(null, null,
380:                                    issueInst, notOnOrAfter, appliesTo, keyInfo);
381:
382:                    final SubjectConfirmation subConfirmation = samlFac
383:                            .createSubjectConfirmation(null, subjComfData,
384:                                    SAML_HOLDER_OF_KEY);
385:
386:                    com.sun.xml.wss.saml.Subject subj = null;
387:                    final List<Attribute> attrs = new ArrayList<Attribute>();
388:                    final Set<Map.Entry<QName, List<String>>> entries = claimedAttrs
389:                            .entrySet();
390:                    for (Map.Entry<QName, List<String>> entry : entries) {
391:                        final QName attrKey = (QName) entry.getKey();
392:                        final List<String> values = (List<String>) entry
393:                                .getValue();
394:                        if (values != null && values.size() > 0) {
395:                            if (STSAttributeProvider.NAME_IDENTIFIER
396:                                    .equals(attrKey.getLocalPart())
397:                                    && subj == null) {
398:                                final NameIdentifier nameId = samlFac
399:                                        .createNameIdentifier(values.get(0),
400:                                                attrKey.getNamespaceURI(), null);
401:                                subj = samlFac.createSubject(nameId,
402:                                        subConfirmation);
403:                            } else {
404:                                final Attribute attr = samlFac.createAttribute(
405:                                        attrKey.getLocalPart(), values);
406:                                attrs.add(attr);
407:                            }
408:                        }
409:                    }
410:                    final AttributeStatement statement = samlFac
411:                            .createAttributeStatement(attrs);
412:                    final List<AttributeStatement> statements = new ArrayList<AttributeStatement>();
413:                    statements.add(statement);
414:
415:                    final NameID issuerID = samlFac.createNameID(issuer, null,
416:                            null);
417:
418:                    // Create Assertion
419:                    assertion = samlFac.createAssertion(assertionId, issuerID,
420:                            issueInst, conditions, null, subj, statements);
421:                } catch (SAMLException ex) {
422:                    log.log(Level.SEVERE, LogStringsMessages
423:                            .WST_0032_ERROR_CREATING_SAML_ASSERTION(), ex);
424:                    throw new WSTrustException(LogStringsMessages
425:                            .WST_0032_ERROR_CREATING_SAML_ASSERTION(), ex);
426:                } catch (XWSSecurityException ex) {
427:                    log.log(Level.SEVERE, LogStringsMessages
428:                            .WST_0032_ERROR_CREATING_SAML_ASSERTION(), ex);
429:                    throw new WSTrustException(LogStringsMessages
430:                            .WST_0032_ERROR_CREATING_SAML_ASSERTION(), ex);
431:                }
432:
433:                return assertion;
434:            }
435:
436:            private KeyInfo createKeyInfo(final String keyType,
437:                    final X509Certificate serCert, final IssuedTokenContext ctx)
438:                    throws WSTrustException {
439:                final KeyInfo keyInfo = new KeyInfo();
440:                if (WSTrustConstants.SYMMETRIC_KEY.equals(keyType)) {
441:                    final byte[] key = ctx.getProofKey();
442:                    if (!stsConfig.getEncryptIssuedToken()
443:                            && stsConfig.getEncryptIssuedKey()) {
444:                        try {
445:                            final Key secKey = new SecretKeySpec(key, "AES");
446:                            final EncryptedKey encKey = encryptKey(secKey,
447:                                    serCert);
448:                            keyInfo.getContent().add(encKey);
449:                        } catch (Exception ex) {
450:                            throw new WSTrustException(ex.getMessage(), ex);
451:                        }
452:                    } else {
453:                        final BinarySecret secret = eleFac.createBinarySecret(
454:                                key, BinarySecret.SYMMETRIC_KEY_TYPE);
455:                        keyInfo.getContent().add(secret);
456:                    }
457:                } else if (WSTrustConstants.PUBLIC_KEY.equals(keyType)) {
458:
459:                    final X509Data x509Data = new X509Data();
460:                    final Set certs = ctx.getRequestorSubject()
461:                            .getPublicCredentials();
462:                    if (certs == null) {
463:                        log.log(Level.SEVERE, LogStringsMessages
464:                                .WST_0034_UNABLE_GET_CLIENT_CERT());
465:                        throw new WSTrustException(LogStringsMessages
466:                                .WST_0034_UNABLE_GET_CLIENT_CERT());
467:                    }
468:                    boolean addedClientCert = false;
469:                    final ObjectFactory dsigOF = new ObjectFactory();
470:                    for (Object o : certs) {
471:                        if (o instanceof  X509Certificate) {
472:                            final X509Certificate clientCert = (X509Certificate) o;
473:
474:                            JAXBElement<byte[]> certElement;
475:                            try {
476:                                certElement = dsigOF
477:                                        .createX509DataTypeX509Certificate(clientCert
478:                                                .getEncoded());
479:                            } catch (CertificateEncodingException ex) {
480:                                //ex.printStackTrace();
481:                                throw new WSTrustException(
482:                                        "Unable to create KeyInfo", ex);
483:                            }
484:                            x509Data.getContent().add(certElement);
485:                            addedClientCert = true;
486:
487:                        }
488:                    }
489:                    if (!addedClientCert) {
490:                        log.log(Level.SEVERE, LogStringsMessages
491:                                .WST_0034_UNABLE_GET_CLIENT_CERT());
492:                        throw new WSTrustException(LogStringsMessages
493:                                .WST_0034_UNABLE_GET_CLIENT_CERT());
494:                    }
495:                    keyInfo.getContent().add(x509Data);
496:                }
497:
498:                return keyInfo;
499:            }
500:
501:            private EncryptedKey encryptKey(final Key key,
502:                    final X509Certificate cert) throws XWSSecurityException {
503:                KeyInfo keyInfo = null;
504:                final KeyIdentifier keyIdentifier = wef.createKeyIdentifier();
505:                keyIdentifier
506:                        .setValueType(MessageConstants.X509SubjectKeyIdentifier_NS);
507:                keyIdentifier.updateReferenceValue(cert);
508:                keyIdentifier
509:                        .setEncodingType(MessageConstants.BASE64_ENCODING_NS);
510:                final SecurityTokenReference str = wef
511:                        .createSecurityTokenReference(keyIdentifier);
512:                keyInfo = wef
513:                        .createKeyInfo((com.sun.xml.ws.security.opt.impl.keyinfo.SecurityTokenReference) str);
514:
515:                return wef.createEncryptedKey(null,
516:                        MessageConstants.RSA_OAEP_KEY_TRANSPORT, keyInfo, cert
517:                                .getPublicKey(), key);
518:            }
519:
520:            //common method to be moved to Base Class
521:            private X509Certificate getServiceCertificate(
522:                    final CallbackHandler callbackHandler,
523:                    TrustSPMetadata spMd, String appliesTo)
524:                    throws WSTrustException {
525:                // Get the service certificate
526:                final EncryptionKeyCallback.AliasX509CertificateRequest req = new EncryptionKeyCallback.AliasX509CertificateRequest(
527:                        spMd.getCertAlias());
528:                final EncryptionKeyCallback callback = new EncryptionKeyCallback(
529:                        req);
530:                final Callback[] callbacks = { callback };
531:                try {
532:                    callbackHandler.handle(callbacks);
533:                } catch (IOException ex) {
534:                    log.log(Level.SEVERE, LogStringsMessages
535:                            .WST_0033_UNABLE_GET_SERVICE_CERT(appliesTo), ex);
536:                    throw new WSTrustException(LogStringsMessages
537:                            .WST_0033_UNABLE_GET_SERVICE_CERT(appliesTo), ex);
538:                } catch (UnsupportedCallbackException ex) {
539:                    log.log(Level.SEVERE, LogStringsMessages
540:                            .WST_0033_UNABLE_GET_SERVICE_CERT(appliesTo), ex);
541:                    throw new WSTrustException(LogStringsMessages
542:                            .WST_0033_UNABLE_GET_SERVICE_CERT(appliesTo), ex);
543:                }
544:
545:                return req.getX509Certificate();
546:            }
547:
548:            public EncryptedDataType createEncryptedData(final String id,
549:                    final String dataEncAlgo, final KeyInfo keyInfo,
550:                    final boolean contentOnly) {
551:                final EncryptedDataType edt = new EncryptedDataType();
552:                if (contentOnly) {
553:                    edt.setType(MessageConstants.ENCRYPT_ELEMENT_CONTENT);
554:                } else {
555:                    edt.setType(MessageConstants.ENCRYPT_ELEMENT);
556:                }
557:                final EncryptionMethodType emt = new EncryptionMethodType();
558:                emt.setAlgorithm(dataEncAlgo);
559:                edt.setEncryptionMethod(emt);
560:                final CipherDataType cipherType = new CipherDataType();
561:                cipherType.setCipherValue("ed".getBytes());
562:                edt.setCipherData(cipherType);
563:                edt.setId(id);
564:                if (keyInfo != null) {
565:                    edt.setKeyInfo(keyInfo);
566:                }
567:                return edt;
568:            }
569:
570:            private SecurityHeaderElement createSignature(
571:                    final PublicKey pubKey, final Key signingKey,
572:                    final SAMLToken samlToken,
573:                    final NamespaceContextEx nsContext) throws WSTrustException {
574:                try {
575:                    final JAXBSignatureFactory signatureFactory = JAXBSignatureFactory
576:                            .newInstance();
577:                    final C14NMethodParameterSpec spec = null;
578:                    final CanonicalizationMethod canonicalMethod = signatureFactory
579:                            .newCanonicalizationMethod(
580:                                    CanonicalizationMethod.EXCLUSIVE, spec);
581:                    DigestMethod digestMethod;
582:                    digestMethod = signatureFactory.newDigestMethod(
583:                            DigestMethod.SHA1, null);
584:                    SignatureMethod signatureMethod;
585:                    signatureMethod = signatureFactory.newSignatureMethod(
586:                            SignatureMethod.RSA_SHA1, null);
587:
588:                    //Note : Signature algorithm parameters null for now , fix me.
589:
590:                    final ArrayList<Transform> transformList = new ArrayList<Transform>();
591:                    Transform tr1;
592:
593:                    tr1 = signatureFactory.newTransform(Transform.ENVELOPED,
594:                            (TransformParameterSpec) null);
595:
596:                    Transform tr2;
597:
598:                    tr2 = signatureFactory.newTransform(
599:                            CanonicalizationMethod.EXCLUSIVE,
600:                            (TransformParameterSpec) null);
601:
602:                    transformList.add(tr1);
603:                    transformList.add(tr2);
604:
605:                    final String uri = "#" + "uuid-"
606:                            + UUID.randomUUID().toString();
607:                    final Reference ref = signatureFactory.newReference(uri,
608:                            digestMethod, transformList, null, null);
609:
610:                    // Create the SignedInfo
611:                    final SignedInfo signedInfo = signatureFactory
612:                            .newSignedInfo(canonicalMethod, signatureMethod,
613:                                    Collections.singletonList(ref));
614:
615:                    KeyValue keyValue;
616:
617:                    //kv = kif.newKeyValue(pubKey);
618:                    if (pubKey instanceof  java.security.interfaces.DSAPublicKey) {
619:                        DSAKeyValue dsa = null;
620:                        final DSAPublicKey key = (DSAPublicKey) pubKey;
621:
622:                        final byte[] paramP = key.getParams().getP()
623:                                .toByteArray();
624:                        final byte[] paramQ = key.getParams().getQ()
625:                                .toByteArray();
626:                        final byte[] paramG = key.getParams().getG()
627:                                .toByteArray();
628:                        final byte[] paramY = key.getY().toByteArray();
629:                        dsa = signatureFactory.newDSAKeyValue(paramP, paramQ,
630:                                paramG, paramY, null, null, null);
631:                        keyValue = signatureFactory.newKeyValue(Collections
632:                                .singletonList(dsa));
633:
634:                    } else if (pubKey instanceof  java.security.interfaces.RSAPublicKey) {
635:                        RSAKeyValue rsa = null;
636:                        final RSAPublicKey key = (RSAPublicKey) pubKey;
637:                        rsa = signatureFactory.newRSAKeyValue(key.getModulus()
638:                                .toByteArray(), key.getPublicExponent()
639:                                .toByteArray());
640:                        keyValue = signatureFactory.newKeyValue(Collections
641:                                .singletonList(rsa));
642:                    } else {
643:                        throw new WSTrustException("Unsupported PublicKey");
644:                    }
645:
646:                    // Create a KeyInfo and add the KeyValue to it
647:                    final javax.xml.crypto.dsig.keyinfo.KeyInfo keyInfo = signatureFactory
648:                            .newKeyInfo(Collections.singletonList(keyValue));
649:                    final JAXBSignContext signContext = new JAXBSignContext(
650:                            signingKey);
651:
652:                    final SSEData data = null;
653:                    signContext.setURIDereferencer(new DSigResolver(data));
654:                    final com.sun.xml.ws.security.opt.crypto.dsig.Signature signature = (Signature) signatureFactory
655:                            .newXMLSignature(signedInfo, keyInfo);
656:                    final JAXBSignatureHeaderElement jhe = new JAXBSignatureHeaderElement(
657:                            signature, soapVersion,
658:                            (XMLSignContext) signContext);
659:                    return new EnvelopedSignedMessageHeader(
660:                            samlToken,
661:                            (com.sun.xml.ws.security.opt.crypto.dsig.Reference) ref,
662:                            jhe, nsContext);
663:                    //        } catch (KeyException ex) {
664:                    //            ex.printStackTrace();
665:                    //            throw new WSTrustException("Unable to create sign SAML Assertion",ex);
666:                    //        }
667:                } catch (NoSuchAlgorithmException ex) {
668:                    log.log(Level.SEVERE, LogStringsMessages
669:                            .WST_0035_UNABLE_CREATE_SIGN_SAML_ASSERTION(), ex);
670:                    throw new WSTrustException(LogStringsMessages
671:                            .WST_0035_UNABLE_CREATE_SIGN_SAML_ASSERTION(), ex);
672:                } catch (InvalidAlgorithmParameterException ex) {
673:                    log.log(Level.SEVERE, LogStringsMessages
674:                            .WST_0035_UNABLE_CREATE_SIGN_SAML_ASSERTION(), ex);
675:                    throw new WSTrustException(LogStringsMessages
676:                            .WST_0035_UNABLE_CREATE_SIGN_SAML_ASSERTION(), ex);
677:                }
678:            }
679:
680:            private static class DSigResolver implements  URIDereferencer {
681:                public Data data = null;
682:
683:                DSigResolver(Data data) {
684:                    this .data = data;
685:                }
686:
687:                public Data dereference(final URIReference uRIReference,
688:                        final XMLCryptoContext xMLCryptoContext)
689:                        throws URIReferenceException {
690:                    return data;
691:                }
692:
693:            }
694:        }
w___w__w__.__j_a__va_2__s_.com_ | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.