Source Code Cross Referenced for SecurityUtil.java in  » 6.0-JDK-Modules-com.sun » xws-security » com » sun » xml » wss » impl » misc » 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 » xws security » com.sun.xml.wss.impl.misc 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /*
002:         * The contents of this file are subject to the terms
003:         * of the Common Development and Distribution License
004:         * (the License).  You may not use this file except in
005:         * compliance with the License.
006:         *
007:         * You can obtain a copy of the license at
008:         * https://glassfish.dev.java.net/public/CDDLv1.0.html.
009:         * See the License for the specific language governing
010:         * permissions and limitations under the License.
011:         *
012:         * When distributing Covered Code, include this CDDL
013:         * Header Notice in each file and include the License file
014:         * at https://glassfish.dev.java.net/public/CDDLv1.0.html.
015:         * If applicable, add the following below the CDDL Header,
016:         * with the fields enclosed by brackets [] replaced by
017:         * you own identifying information:
018:         * "Portions Copyrighted [year] [name of copyright owner]"
019:         *
020:         * Copyright 2006 Sun Microsystems Inc. All Rights Reserved
021:         */
022:
023:        package com.sun.xml.wss.impl.misc;
024:
025:        import com.sun.xml.ws.security.Token;
026:        import com.sun.xml.ws.security.opt.impl.JAXBFilterProcessingContext;
027:        import com.sun.xml.ws.security.secext10.SecurityTokenReferenceType;
028:        import com.sun.xml.wss.core.reference.SamlKeyIdentifier;
029:        import com.sun.xml.wss.impl.PolicyTypeUtil;
030:        import com.sun.xml.wss.impl.policy.mls.EncryptionPolicy;
031:        import com.sun.xml.wss.impl.policy.mls.WSSPolicy;
032:        import java.security.InvalidKeyException;
033:        import java.security.NoSuchAlgorithmException;
034:        import java.util.List;
035:        import java.util.Map;
036:        import javax.crypto.SecretKey;
037:        import javax.crypto.KeyGenerator;
038:        import javax.crypto.Mac;
039:        import javax.crypto.spec.SecretKeySpec;
040:        import java.security.Key;
041:        import javax.xml.bind.JAXBElement;
042:
043:        import javax.xml.soap.SOAPElement;
044:
045:        import com.sun.xml.wss.XWSSecurityException;
046:        import com.sun.xml.wss.impl.MessageConstants;
047:        import com.sun.xml.wss.logging.LogDomainConstants;
048:
049:        import java.util.Random;
050:        import java.util.Hashtable;
051:        import java.util.Iterator;
052:        import java.util.logging.Level;
053:        import java.util.logging.Logger;
054:        import java.util.HashMap;
055:
056:        import com.sun.xml.wss.impl.FilterProcessingContext;
057:        import com.sun.xml.wss.impl.policy.mls.AuthenticationTokenPolicy;
058:        import com.sun.xml.wss.impl.SecurableSoapMessage;
059:        import com.sun.xml.wss.core.X509SecurityToken;
060:        import com.sun.xml.wss.impl.WSSAssertion;
061:
062:        import com.sun.org.apache.xml.internal.security.algorithms.JCEMapper;
063:
064:        import com.sun.xml.ws.security.impl.IssuedTokenContextImpl;
065:        import com.sun.xml.ws.security.IssuedTokenContext;
066:        import com.sun.xml.wss.core.SecurityContextTokenImpl;
067:        import com.sun.xml.wss.impl.policy.mls.SecureConversationTokenKeyBinding;
068:        import com.sun.xml.wss.impl.policy.mls.IssuedTokenKeyBinding;
069:
070:        import com.sun.xml.ws.security.SecurityTokenReference;
071:
072:        import org.w3c.dom.Node;
073:        import org.w3c.dom.Element;
074:        import org.w3c.dom.NamedNodeMap;
075:        import org.w3c.dom.Document;
076:
077:        import com.sun.xml.ws.security.trust.WSTrustConstants;
078:
079:        import com.sun.xml.ws.security.SecurityContextToken;
080:        import java.net.URL;
081:        import java.security.AccessController;
082:        import java.security.PrivilegedAction;
083:        import java.security.cert.X509Certificate;
084:        import javax.security.auth.Subject;
085:
086:        /**
087:         * Utility class for the Encryption and Signature related methods
088:         * @author Ashutosh Shahi
089:         */
090:        public class SecurityUtil {
091:
092:            protected static final Logger log = Logger.getLogger(
093:                    LogDomainConstants.IMPL_CRYPTO_DOMAIN,
094:                    LogDomainConstants.IMPL_CRYPTO_DOMAIN_BUNDLE);
095:
096:            /** Creates a new instance of SecurityUtil */
097:            public SecurityUtil() {
098:            }
099:
100:            public static SecretKey generateSymmetricKey(String algorithm)
101:                    throws XWSSecurityException {
102:                try {
103:
104:                    //keyGen.init(168);//TODO-Venu
105:                    String jceAlgo = JCEMapper
106:                            .getJCEKeyAlgorithmFromURI(algorithm);
107:                    //JCEMapper.translateURItoJCEID(algorithm);
108:                    //
109:                    if (MessageConstants.debug) {
110:                        log.log(Level.FINEST, "JCE ALGORITHM " + jceAlgo);
111:                    }
112:                    KeyGenerator keyGen = KeyGenerator.getInstance(jceAlgo);
113:                    int length = 0;
114:                    if (jceAlgo.startsWith("DES")) {
115:                        length = 168;
116:                    } else {
117:                        length = JCEMapper.getKeyLengthFromURI(algorithm);
118:                    }
119:                    keyGen.init(length);
120:                    if (MessageConstants.debug) {
121:                        log.log(Level.FINEST, "Algorithm key length " + length);
122:                    }
123:                    return keyGen.generateKey();
124:                } catch (Exception e) {
125:                    log.log(Level.SEVERE,
126:                            "WSS1208.failedto.generate.random.symmetrickey",
127:                            new Object[] { e.getMessage() });
128:                    throw new XWSSecurityException(
129:                            "Unable to Generate Symmetric Key", e);
130:                }
131:            }
132:
133:            /**
134:             * Lookup method to get the Key Length based on algorithm
135:             * TODO: Not complete yet, need to add more algorithms
136:             * NOTE: This method should only be used for DerivedKeyTokenLengths
137:             **/
138:            public static int getLengthFromAlgorithm(String algorithm)
139:                    throws XWSSecurityException {
140:                if (algorithm.equals(MessageConstants.AES_BLOCK_ENCRYPTION_192)) {
141:                    return 24;
142:                } else if (algorithm
143:                        .equals(MessageConstants.AES_BLOCK_ENCRYPTION_256)) {
144:                    return 32;
145:                } else if (algorithm
146:                        .equals(MessageConstants.AES_BLOCK_ENCRYPTION_128)) {
147:                    return 16;
148:                } else if (algorithm
149:                        .equals(MessageConstants.TRIPLE_DES_BLOCK_ENCRYPTION)) {
150:                    return 24;
151:                } else {
152:                    throw new UnsupportedOperationException(
153:                            "TODO: not yet implemented keyLength for"
154:                                    + algorithm);
155:                }
156:            }
157:
158:            public static String generateUUID() {
159:                Random rnd = new Random();
160:                int intRandom = rnd.nextInt();
161:                String id = "XWSSGID-"
162:                        + String.valueOf(System.currentTimeMillis())
163:                        + String.valueOf(intRandom);
164:                return id;
165:            }
166:
167:            public static byte[] P_SHA1(byte[] secret, byte[] seed)
168:                    throws Exception {
169:
170:                byte[] aBytes, result;
171:                aBytes = seed;
172:
173:                Mac hMac = Mac.getInstance("HMACSHA1");
174:                SecretKeySpec sKey = new SecretKeySpec(secret, "HMACSHA1");
175:                hMac.init(sKey);
176:                hMac.update(aBytes);
177:                aBytes = hMac.doFinal();
178:                hMac.reset();
179:                hMac.init(sKey);
180:                hMac.update(aBytes);
181:                hMac.update(seed);
182:                result = hMac.doFinal();
183:
184:                return result;
185:            }
186:
187:            public static byte[] P_SHA1(byte[] secret, byte[] seed,
188:                    int requiredSize) throws NoSuchAlgorithmException,
189:                    InvalidKeyException {
190:                Mac hMac = Mac.getInstance("HMACSHA1");
191:                SecretKeySpec sKey = new SecretKeySpec(secret, "HMACSHA1");
192:
193:                byte[] result = new byte[requiredSize];
194:                int copied = 0;
195:
196:                byte[] aBytes = seed;
197:                hMac.init(sKey);
198:                hMac.update(aBytes);
199:                aBytes = hMac.doFinal();
200:
201:                int rounds = requiredSize / aBytes.length;
202:                if (requiredSize % aBytes.length != 0)
203:                    rounds++;
204:
205:                for (int i = 0; i < rounds; i++) {
206:
207:                    hMac.reset();
208:                    hMac.init(sKey);
209:                    hMac.update(aBytes);
210:                    hMac.update(seed);
211:                    byte[] generated = hMac.doFinal();
212:                    int takeBytes;
213:                    if (i != rounds - 1)
214:                        takeBytes = generated.length;
215:                    else
216:                        takeBytes = requiredSize - (generated.length * i);
217:                    System.arraycopy(generated, 0, result, copied, takeBytes);
218:                    copied += takeBytes;
219:                    hMac.init(sKey);
220:                    hMac.update(aBytes);
221:                    aBytes = hMac.doFinal();
222:                }
223:                return result;
224:            }
225:
226:            public static String getSecretKeyAlgorithm(String encryptionAlgo) {
227:                String encAlgo = JCEMapper.translateURItoJCEID(encryptionAlgo);
228:                if (encAlgo.startsWith("AES")) {
229:                    return "AES";
230:                } else if (encAlgo.startsWith("DESede")) {
231:                    return "DESede";
232:                } else if (encAlgo.startsWith("DES")) {
233:                    return "DES";
234:                }
235:                return encAlgo;
236:            }
237:
238:            public static void checkIncludeTokenPolicy(
239:                    FilterProcessingContext context,
240:                    AuthenticationTokenPolicy.X509CertificateBinding certInfo,
241:                    String x509id) throws XWSSecurityException {
242:
243:                HashMap insertedX509Cache = context.getInsertedX509Cache();
244:                X509SecurityToken x509Token = (X509SecurityToken) insertedX509Cache
245:                        .get(x509id);
246:                //SecurableSoapMessage secureMessage = context.getSecurableSoapMessage();
247:
248:                try {
249:                    if (x509Token == null) {
250:                        /*Token policyToken = certInfo.getPolicyToken();
251:                        if (policyToken == null) {
252:                            return;
253:                        }*/
254:                        // no referencetype adjustment if it is not WS-SecurityPolicy
255:                        if (!certInfo.policyTokenWasSet()) {
256:                            return;
257:                        }
258:
259:                        if (certInfo.INCLUDE_ALWAYS_TO_RECIPIENT
260:                                .equals(certInfo.getIncludeToken())
261:                                || certInfo.INCLUDE_ALWAYS.equals(certInfo
262:                                        .getIncludeToken())) {
263:                            insertCertificate(context, certInfo, x509id);
264:                        } else if (certInfo.INCLUDE_NEVER.equals(certInfo
265:                                .getIncludeToken())) {
266:                            WSSAssertion wssAssertion = context
267:                                    .getWSSAssertion();
268:                            if (MessageConstants.DIRECT_REFERENCE_TYPE
269:                                    .equals(certInfo.getReferenceType())) {
270:                                if (wssAssertion != null) {
271:                                    if (wssAssertion
272:                                            .getRequiredProperties()
273:                                            .contains(
274:                                                    WSSAssertion.MUST_SUPPORT_REF_KEYIDENTIFIER))
275:                                        certInfo
276:                                                .setReferenceType(MessageConstants.KEY_INDETIFIER_TYPE);
277:                                    else if (wssAssertion
278:                                            .getRequiredProperties()
279:                                            .contains(
280:                                                    WSSAssertion.MUSTSUPPORT_REF_THUMBPRINT))
281:                                        certInfo
282:                                                .setReferenceType(MessageConstants.THUMB_PRINT_TYPE);
283:                                } else {
284:                                    // when wssAssertion is not set use KeyIdentifier
285:                                    certInfo
286:                                            .setReferenceType(MessageConstants.KEY_INDETIFIER_TYPE);
287:                                }
288:                            }
289:                        } else if (certInfo.INCLUDE_ONCE.equals(certInfo
290:                                .getIncludeToken())) {
291:                            throw new UnsupportedOperationException(
292:                                    certInfo.INCLUDE_ONCE
293:                                            + " not supported yet as IncludeToken policy");
294:                        }
295:                    }
296:                } catch (Exception e) {
297:                    throw new XWSSecurityException(e);
298:                }
299:            }
300:
301:            public static void checkIncludeTokenPolicyOpt(
302:                    JAXBFilterProcessingContext context,
303:                    AuthenticationTokenPolicy.X509CertificateBinding certInfo,
304:                    String x509id) throws XWSSecurityException {
305:
306:                //SecurityHeaderElement she = context.getSecurityHeader().getChildElement(x509id);
307:
308:                try {
309:                    //if(she != null){
310:                    /*Token policyToken = certInfo.getPolicyToken();
311:                    if (policyToken == null) {
312:                        return;
313:                    }*/
314:                    // no referencetype adjustment if it is not WS-SecurityPolicy
315:                    if (!certInfo.policyTokenWasSet()) {
316:                        return;
317:                    }
318:                    if (certInfo.INCLUDE_ALWAYS_TO_RECIPIENT.equals(certInfo
319:                            .getIncludeToken())
320:                            || certInfo.INCLUDE_ALWAYS.equals(certInfo
321:                                    .getIncludeToken())) {
322:                        certInfo
323:                                .setReferenceType(MessageConstants.DIRECT_REFERENCE_TYPE);
324:                    } else if (certInfo.INCLUDE_NEVER.equals(certInfo
325:                            .getIncludeToken())) {
326:                        WSSAssertion wssAssertion = context.getWSSAssertion();
327:                        if (MessageConstants.DIRECT_REFERENCE_TYPE
328:                                .equals(certInfo.getReferenceType())) {
329:                            if (wssAssertion != null) {
330:                                if (wssAssertion
331:                                        .getRequiredProperties()
332:                                        .contains(
333:                                                WSSAssertion.MUST_SUPPORT_REF_KEYIDENTIFIER))
334:                                    certInfo
335:                                            .setReferenceType(MessageConstants.KEY_INDETIFIER_TYPE);
336:                                else if (wssAssertion
337:                                        .getRequiredProperties()
338:                                        .contains(
339:                                                WSSAssertion.MUSTSUPPORT_REF_THUMBPRINT))
340:                                    certInfo
341:                                            .setReferenceType(MessageConstants.THUMB_PRINT_TYPE);
342:                            } else {
343:                                // when wssAssertion is not set use KeyIdentifier
344:                                certInfo
345:                                        .setReferenceType(MessageConstants.KEY_INDETIFIER_TYPE);
346:                            }
347:                        }
348:                    } else if (certInfo.INCLUDE_ONCE.equals(certInfo
349:                            .getIncludeToken())) {
350:                        throw new UnsupportedOperationException(
351:                                certInfo.INCLUDE_ONCE
352:                                        + " not supported yet as IncludeToken policy");
353:                    }
354:                    //}
355:                } catch (Exception e) {
356:                    throw new XWSSecurityException(e);
357:                }
358:            }
359:
360:            public static String getWsuIdOrId(Element elem)
361:                    throws XWSSecurityException {
362:                NamedNodeMap nmap = elem.getAttributes();
363:                Node attr = nmap.getNamedItem("Id");
364:                if (attr == null) {
365:                    attr = nmap.getNamedItem("AssertionID");
366:                    if (attr == null)
367:                        attr = nmap.getNamedItem("ID");
368:                    if (attr == null) {
369:                        throw new XWSSecurityException(
370:                                "Issued Token Element does not have a Id or AssertionId attribute");
371:                    }
372:                }
373:                return attr.getNodeValue();
374:            }
375:
376:            public static void resolveSCT(FilterProcessingContext context,
377:                    SecureConversationTokenKeyBinding sctBinding)
378:                    throws XWSSecurityException {
379:                // resolve the ProofKey here and set it into ProcessingContext
380:                //String sctPolicyId = sctBinding.getPolicyToken().getTokenId();
381:                String sctPolicyId = sctBinding.getUUID();
382:                // this will work on the client side only
383:                IssuedTokenContext ictx = context
384:                        .getIssuedTokenContext(sctPolicyId);
385:                if (ictx == null) {
386:                    // this will work on the server side
387:                    String sctId = "";
388:                    if (context instanceof  JAXBFilterProcessingContext) {
389:
390:                        Object sctObject = context
391:                                .getExtraneousProperty(MessageConstants.INCOMING_SCT);
392:
393:                        if (sctObject == null) {
394:                            throw new XWSSecurityException(
395:                                    "SecureConversation Session Context not Found");
396:                        }
397:                        if (sctObject instanceof  com.sun.xml.ws.security.opt.impl.incoming.SecurityContextToken) {
398:                            com.sun.xml.ws.security.opt.impl.incoming.SecurityContextToken sct = (com.sun.xml.ws.security.opt.impl.incoming.SecurityContextToken) sctObject;
399:                            sctId = sct.getSCId();
400:                        } else if (sctObject instanceof  SecurityContextToken) {
401:                            SecurityContextToken sct = (SecurityContextToken) sctObject;
402:                            sctId = sct.getIdentifier().toString();
403:                        }
404:
405:                        ictx = context.getIssuedTokenContext(sctId);
406:                    } else {
407:                        SecurityContextTokenImpl sct = (SecurityContextTokenImpl) context
408:                                .getExtraneousProperty(MessageConstants.INCOMING_SCT);
409:                        if (sct == null) {
410:                            throw new XWSSecurityException(
411:                                    "SecureConversation Session Context not Found");
412:                        }
413:                        sctId = sct.getSCId();
414:                        ictx = context.getIssuedTokenContext(sctId);
415:                    }
416:                }
417:
418:                if (ictx == null) {
419:                    throw new XWSSecurityException(
420:                            "SecureConversation Session Context not Found");
421:                } else {
422:                    //System.out.println("SC Session located...");
423:                }
424:                //TODO: assuming only a single secure-conversation context
425:                context.setSecureConversationContext(ictx);
426:            }
427:
428:            public static void resolveIssuedToken(
429:                    FilterProcessingContext context, IssuedTokenKeyBinding itkb)
430:                    throws XWSSecurityException {
431:                //resolve the ProofKey here and set it into ProcessingContext
432:                //String itPolicyId = itkb.getPolicyToken().getTokenId();
433:                String itPolicyId = itkb.getUUID();
434:                // this will work on the client side only
435:                IssuedTokenContext ictx = context
436:                        .getIssuedTokenContext(itPolicyId);
437:                boolean clientSide = true;
438:                if (ictx == null) {
439:                    // on the server we have the TrustCredentialHolder
440:                    ictx = context.getTrustCredentialHolder();
441:                    clientSide = false;
442:                }
443:
444:                if (ictx == null) {
445:                    throw new XWSSecurityException(
446:                            "Trust IssuedToken not Found");
447:                }
448:
449:                context.setTrustContext(ictx);
450:                if (ictx.getProofKey() == null) {
451:                    //handle asymmetric issued key
452:                    if (clientSide) {
453:                        //TODO: change this later to use the Cert Alias
454:                        X509Certificate cert = context.getSecurityEnvironment()
455:                                .getDefaultCertificate(
456:                                        context.getExtraneousProperties());
457:                        ictx.setRequestorCertificate(cert);
458:                    } else {
459:                        //nothing todo on server side
460:                    }
461:                }
462:            }
463:
464:            public static void initInferredIssuedTokenContext(
465:                    FilterProcessingContext wssContext, Token str, Key returnKey)
466:                    throws XWSSecurityException {
467:                // new code which fixes issues with Brokered Trust.
468:                IssuedTokenContextImpl ictx = (IssuedTokenContextImpl) wssContext
469:                        .getTrustCredentialHolder();
470:                if (ictx == null) {
471:                    ictx = new IssuedTokenContextImpl();
472:                }
473:
474:                ictx.setProofKey(returnKey.getEncoded());
475:                ictx.setUnAttachedSecurityTokenReference(str);
476:                wssContext.setTrustCredentialHolder(ictx);
477:            }
478:
479:            public static boolean isEncryptedKey(SOAPElement elem) {
480:
481:                if (MessageConstants.XENC_ENCRYPTED_KEY_LNAME.equals(elem
482:                        .getLocalName())
483:                        && MessageConstants.XENC_NS.equals(elem
484:                                .getNamespaceURI())) {
485:                    return true;
486:                }
487:                return false;
488:            }
489:
490:            public static boolean isBinarySecret(SOAPElement elem) {
491:                if (MessageConstants.BINARY_SECRET_LNAME.equals(elem
492:                        .getLocalName())
493:                        && WSTrustConstants.WST_NAMESPACE.equals(elem
494:                                .getNamespaceURI())) {
495:                    return true;
496:                }
497:                return false;
498:            }
499:
500:            public static SecurityContextTokenImpl locateBySCTId(
501:                    FilterProcessingContext context, String sctId)
502:                    throws XWSSecurityException {
503:
504:                Hashtable contextMap = context.getIssuedTokenContextMap();
505:
506:                if (contextMap == null) {
507:                    // print a warning here
508:                    //System.out.println("context.getIssuedTokenContextMap was null.........");
509:                    return null;
510:                }
511:
512:                Iterator<Map.Entry> it = contextMap.entrySet().iterator();
513:
514:                while (it.hasNext()) {
515:                    Map.Entry entry = it.next();
516:                    String tokenId = (String) entry.getKey();
517:                    Object token = entry.getValue();
518:                    if (token instanceof  IssuedTokenContext) {
519:                        Object securityToken = ((IssuedTokenContext) token)
520:                                .getSecurityToken();
521:                        if (securityToken instanceof  SecurityContextToken) {
522:                            SecurityContextToken ret = (SecurityContextToken) securityToken;
523:                            if (sctId.equals(ret.getIdentifier().toString())) {
524:                                return new SecurityContextTokenImpl(context
525:                                        .getSOAPMessage().getSOAPPart(), ret
526:                                        .getIdentifier().toString(), ret
527:                                        .getInstance(), ret.getWsuId(), ret
528:                                        .getExtElements());
529:                            }
530:                        }
531:                    }
532:                }
533:                return null;
534:            }
535:
536:            public static void updateSamlVsKeyCache(SecurityTokenReference str,
537:                    FilterProcessingContext ctx, Key symKey) {
538:                com.sun.xml.wss.core.ReferenceElement ref = ((com.sun.xml.wss.core.SecurityTokenReference) str)
539:                        .getReference();
540:                if (ref instanceof  com.sun.xml.wss.core.reference.KeyIdentifier) {
541:                    String assertionId = ((com.sun.xml.wss.core.reference.KeyIdentifier) ref)
542:                            .getReferenceValue();
543:                    if (ctx.getSamlIdVSKeyCache().get(assertionId) == null) {
544:                        ctx.getSamlIdVSKeyCache().put(assertionId, symKey);
545:                    }
546:                }
547:            }
548:
549:            public static void updateSamlVsKeyCache(
550:                    SecurityTokenReferenceType str,
551:                    FilterProcessingContext ctx, Key symKey) {
552:                List<Object> list = str.getAny();
553:                for (int i = 0; i < list.size(); i++) {
554:                    Object item = list.get(i);
555:                    if (item instanceof  JAXBElement) {
556:                        item = ((JAXBElement) item).getValue();
557:                    }
558:                    if (item instanceof  com.sun.xml.ws.security.secext10.KeyIdentifierType) {
559:                        String assertionId = ((com.sun.xml.ws.security.secext10.KeyIdentifierType) item)
560:                                .getValue();
561:                        if (ctx.getSamlIdVSKeyCache().get(assertionId) == null) {
562:                            ctx.getSamlIdVSKeyCache().put(assertionId, symKey);
563:                        }
564:                        HashMap sentSamlKeys = (HashMap) ctx
565:                                .getExtraneousProperty(MessageConstants.STORED_SAML_KEYS);
566:                        if (sentSamlKeys != null) {
567:                            if (sentSamlKeys.get(assertionId) == null) {
568:                                sentSamlKeys.put(assertionId, symKey);
569:                            }
570:                        }
571:                    }
572:                }
573:            }
574:
575:            public static void insertCertificate(
576:                    FilterProcessingContext context,
577:                    AuthenticationTokenPolicy.X509CertificateBinding certInfo,
578:                    String x509id) throws XWSSecurityException {
579:                HashMap insertedX509Cache = context.getInsertedX509Cache();
580:                try {
581:                    /*if(context instanceof JAXBFilterProcessingContext){
582:                        WSSElementFactory elementFactory = new WSSElementFactory();
583:                        JAXBFilterProcessingContext opContext = (JAXBFilterProcessingContext)context;
584:                        SecurityHeader secHeader = opContext.getSecurityHeader();
585:                        byte[] cert = certInfo.getX509Certificate().getEncoded();
586:                        BinarySecurityToken token = elementFactory.createBinarySecurityToken(x509id, cert);
587:                        secHeader.add(token);
588:                        insertedX509Cache.put(x509id, token);
589:                        certInfo.setReferenceType(MessageConstants.DIRECT_REFERENCE_TYPE);
590:                    } else{*/
591:                    String valueType = certInfo.getValueType();
592:                    if (valueType == null || valueType.equals("")) {
593:                        //default valueType for X509 as v3
594:                        valueType = MessageConstants.X509v3_NS;
595:                    }
596:                    SecurableSoapMessage secureMessage = context
597:                            .getSecurableSoapMessage();
598:                    X509SecurityToken x509Token = new X509SecurityToken(
599:                            secureMessage.getSOAPPart(), certInfo
600:                                    .getX509Certificate(), x509id, valueType);
601:                    secureMessage.findOrCreateSecurityHeader()
602:                            .insertHeaderBlock(x509Token);
603:                    insertedX509Cache.put(x509id, x509Token);
604:                    certInfo
605:                            .setReferenceType(MessageConstants.DIRECT_REFERENCE_TYPE);
606:                    //}
607:                } catch (Exception e) {
608:                    throw new XWSSecurityException(e);
609:                }
610:            }
611:
612:            public static String getDataEncryptionAlgo(
613:                    JAXBFilterProcessingContext context) {
614:                WSSPolicy policy = (WSSPolicy) context.getSecurityPolicy();
615:                String tmp = "";
616:                if (PolicyTypeUtil.encryptionPolicy(policy)) {
617:                    EncryptionPolicy.FeatureBinding featureBinding = (EncryptionPolicy.FeatureBinding) policy
618:                            .getFeatureBinding();
619:                    tmp = featureBinding.getDataEncryptionAlgorithm();
620:                }
621:                if (tmp == null || "".equals(tmp)) {
622:                    if (context.getAlgorithmSuite() != null) {
623:                        tmp = context.getAlgorithmSuite()
624:                                .getEncryptionAlgorithm();
625:                    } else {
626:                        // warn that no dataEncAlgo was set
627:                    }
628:                }
629:                return tmp;
630:            }
631:
632:            /**
633:             * Returns a URL pointing to the given config file. The file name is
634:             * looked up as a resource from a ServletContext.
635:             *
636:             * May return null if the file can not be found.
637:             *
638:             * @param configFileName The name of the file resource
639:             * @param context A ServletContext object. May not be null.
640:             */
641:            public static URL loadFromContext(final String configFileName,
642:                    final Object context) {
643:                return ReflectionUtil.invoke(context, "getResource", URL.class,
644:                        configFileName);
645:            }
646:
647:            /**
648:             * Returns a URL pointing to the given config file. The file is looked up as
649:             * a resource on the classpath.
650:             *
651:             * May return null if the file can not be found.
652:             *
653:             * @param configFileName the name of the file resource. May not be {@code null}.
654:             */
655:            public static URL loadFromClasspath(final String configFileName) {
656:                final ClassLoader cl = Thread.currentThread()
657:                        .getContextClassLoader();
658:                if (cl == null) {
659:                    return ClassLoader.getSystemResource(configFileName);
660:                } else {
661:                    return cl.getResource(configFileName);
662:                }
663:            }
664:
665:            public static Element convertSTRToElement(Object strElem,
666:                    Document doc) throws XWSSecurityException {
667:
668:                if (strElem == null || strElem instanceof  Element) {
669:                    return (Element) strElem;
670:                }
671:
672:                com.sun.xml.wss.core.SecurityTokenReference stRef = null;
673:                if (strElem instanceof  com.sun.xml.ws.security.opt.impl.reference.KeyIdentifier) {
674:                    com.sun.xml.ws.security.opt.impl.reference.KeyIdentifier keyIdStrElem = (com.sun.xml.ws.security.opt.impl.reference.KeyIdentifier) strElem;
675:                    if (MessageConstants.WSSE_SAML_KEY_IDENTIFIER_VALUE_TYPE
676:                            .equals(keyIdStrElem.getValueType())) {
677:                        stRef = new com.sun.xml.wss.core.SecurityTokenReference(
678:                                doc);
679:                        SamlKeyIdentifier keyId = new SamlKeyIdentifier(doc);
680:                        keyId.setReferenceValue(keyIdStrElem
681:                                .getReferenceValue());
682:                        keyId.setValueType(keyIdStrElem.getValueType());
683:                        stRef.setReference(keyId);
684:                    } else {
685:                        throw new XWSSecurityException(
686:                                "Unsupported reference type encountered");
687:                    }
688:                }
689:                return stRef;
690:            }
691:
692:            public static void copySubject(final Subject to, final Subject from) {
693:                AccessController.doPrivileged(new PrivilegedAction() {
694:                    public Object run() {
695:                        to.getPrincipals().addAll(from.getPrincipals());
696:                        to.getPublicCredentials().addAll(
697:                                from.getPublicCredentials());
698:                        to.getPrivateCredentials().addAll(
699:                                from.getPrivateCredentials());
700:                        return null;
701:                    }
702:                });
703:            }
704:
705:            public static Subject getSubject(final Map context) {
706:                Subject otherPartySubject = (Subject) context
707:                        .get(MessageConstants.AUTH_SUBJECT);
708:                if (otherPartySubject != null) {
709:                    return otherPartySubject;
710:                }
711:                otherPartySubject = (Subject) AccessController
712:                        .doPrivileged(new PrivilegedAction() {
713:                            public Object run() {
714:                                Subject otherPartySubj = new Subject();
715:                                context.put(MessageConstants.AUTH_SUBJECT,
716:                                        otherPartySubj);
717:                                return otherPartySubj;
718:                            }
719:                        });
720:                return otherPartySubject;
721:            }
722:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.