FileDocCategorySizeDatePackage
TrustDKTTest.javaAPI DocExample24984Tue May 29 16:57:46 BST 2007com.sun.xml.wss.impl

TrustDKTTest

public class TrustDKTTest extends TestCase

Fields Summary
public static final String
holderOfKeyConfirmation
public static final String
senderVouchesConfirmation
private static Hashtable
map
private static com.sun.xml.wss.impl.AlgorithmSuite
alg
Constructors Summary
public TrustDKTTest(String testName)

    
         
        super(testName);
    
Methods Summary
public static javax.xml.soap.SOAPMessageconstructMessage(java.lang.String mimeHdrsFile, java.lang.String msgFile)

        SOAPMessage message;
                                                                                                                                                 
        MimeHeaders mimeHeaders = new MimeHeaders();
        FileInputStream fis = new FileInputStream(msgFile);
                                                                                                                                                 
        ObjectInputStream ois = new ObjectInputStream(
        new FileInputStream(mimeHdrsFile));
        Hashtable hashTable = (Hashtable) ois.readObject();
        ois.close();
                                                                                                                                                 
        if(hashTable.isEmpty()) {
          //  System.out.println("MimeHeaders Hashtable is empty");
        } else {
            for(int i=0; i < hashTable.size(); i++) {
                Enumeration keys = hashTable.keys();
                Enumeration values = hashTable.elements();
                while (keys.hasMoreElements() && values.hasMoreElements()) {
                    String name = (String) keys.nextElement();
                    String value = (String) values.nextElement();
                    mimeHeaders.addHeader(name, value);
                }
            }
        }
                                                                                                                                                 
        MessageFactory messageFactory = MessageFactory.newInstance();
        message = messageFactory.createMessage(mimeHeaders, fis);
                                                                                                                                                 
        message.saveChanges();
                                                                                                                                                 
        return message;
    
private static AssertioncreateHOKAssertion(byte[] keyBytes, org.w3c.dom.Document doc)

        
        Assertion assertion = null;
        try {
                             
            SAMLAssertionFactory factory = SAMLAssertionFactory.newInstance(SAMLAssertionFactory.SAML1_1);
                                                                                                
            // create the assertion id
            String assertionID = String.valueOf(System.currentTimeMillis());
            String issuer = "CN=Assertion Issuer,OU=AI,O=Assertion Issuer,L=Waltham,ST=MA,C=US";
                                                                                                                             
                                                                                                                             
            GregorianCalendar c = new GregorianCalendar();
            long beforeTime = c.getTimeInMillis();
            // roll the time by one hour
            long offsetHours = 60*60*1000;
                                                                                                                             
            c.setTimeInMillis(beforeTime - offsetHours);
            GregorianCalendar before= (GregorianCalendar)c.clone();
                                                                                                                             
            c = new GregorianCalendar();
            long afterTime = c.getTimeInMillis();
            c.setTimeInMillis(afterTime + offsetHours);
            GregorianCalendar after = (GregorianCalendar)c.clone();
                                                                                                                             
            GregorianCalendar issueInstant = new GregorianCalendar();
            // statements
            List statements = new LinkedList();
            NameIdentifier nmId =
            factory.createNameIdentifier(
            "CN=SAML User,OU=SU,O=SAML User,L=Los Angeles,ST=CA,C=US",
            null, // not sure abt this value
            "urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName");           

            //default priv key cert req
            SOAPElement elem = (SOAPElement)doc.createElementNS(WSTrustConstants.WST_NAMESPACE, "wst:BinarySecret");
            elem.addTextNode(Base64.encode(keyBytes));

            KeyInfoHeaderBlock kiHB = new KeyInfoHeaderBlock(doc);

            SOAPElement binSecret = null;
            kiHB.addBinarySecret(elem);

            List subConfirmation = new ArrayList();
            subConfirmation.add(senderVouchesConfirmation);

            SubjectConfirmation scf =
            factory.createSubjectConfirmation(subConfirmation, null, kiHB.getAsSoapElement());
                                                                                                                             
                                                                                                                             
            Subject subj = factory.createSubject(nmId, scf);
                                                                                                                             
            List attributes = new LinkedList();
            List attributeValues = new LinkedList();
            attributeValues.add("ATTRIBUTE1");
            attributes.add( factory.createAttribute(
                "attribute1",
                "urn:com:sun:xml:wss:attribute",
                attributeValues));
                                                                                                                             
            statements.add(
            factory.createAttributeStatement(subj, attributes));
                                                                                                                             
            Conditions conditions = factory.createConditions(before, after, null, null, null);
                                                                                                                             
            assertion = factory.createAssertion(assertionID, issuer, issueInstant,
            conditions, null, statements);
            assertion.setMajorVersion(BigInteger.ONE);
            assertion.setMinorVersion(BigInteger.ONE);
 
            return assertion;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        
    
public static voidsaveMimeHeaders(javax.xml.soap.SOAPMessage msg, java.lang.String fileName)

                                                                                                                                                 
        FileOutputStream fos = new FileOutputStream(fileName);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
                                                                                                                                                 
        Hashtable<String, Object> hashTable = new Hashtable<String, Object>();
        MimeHeaders mimeHeaders = msg.getMimeHeaders();
        Iterator iterator = mimeHeaders.getAllHeaders();
                                                                                                                                                 
        while(iterator.hasNext()) {
            MimeHeader mimeHeader = (MimeHeader) iterator.next();
            hashTable.put(mimeHeader.getName(), mimeHeader.getValue());
        }
                                                                                                                                                 
        oos.writeObject(hashTable);
        oos.flush();
        oos.close();
                                                                                                                                                 
        fos.flush();
        fos.close();
    
protected voidsetUp()

    	
    
public static junit.framework.Testsuite()

        TestSuite suite = new TestSuite(TrustDKTTest.class);
                                                                                                                                                             
        return suite;
    
protected voidtearDown()

    
private static javax.xml.soap.SOAPMessagetestResponse(com.sun.xml.wss.impl.ProcessingContextImpl context)

    	        SignaturePolicy signaturePolicy = new SignaturePolicy();
        	SignatureTarget st = new SignatureTarget();
	        st.setType("qname");
    	        st.setDigestAlgorithm(DigestMethod.SHA1);
        	SignatureTarget.Transform trans = new SignatureTarget.Transform();
	        trans.setTransform(MessageConstants.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
    	        st.addTransform(trans);

        	((SignaturePolicy.FeatureBinding)signaturePolicy.getFeatureBinding()).
            	        addTargetBinding(st);
	        ((SignaturePolicy.FeatureBinding)signaturePolicy.getFeatureBinding()).
    	                setCanonicalizationAlgorithm(MessageConstants.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);

        	IssuedTokenKeyBinding isKB = 
            	(IssuedTokenKeyBinding)signaturePolicy.newIssuedTokenKeyBinding();
                isKB.setIncludeToken(Token.INCLUDE_NEVER);

                 DerivedTokenKeyBinding dktSigKB = (DerivedTokenKeyBinding)signaturePolicy.newDerivedTokenKeyBinding();
                dktSigKB.setOriginalKeyBinding(isKB);


	        EncryptionPolicy encryptPolicy = new EncryptionPolicy();
    	        EncryptionTarget et = new EncryptionTarget();
        	et.setType("qname");
	        ((EncryptionPolicy.FeatureBinding)encryptPolicy.getFeatureBinding()).
    	                addTargetBinding(st);
        	((EncryptionPolicy.FeatureBinding)encryptPolicy.getFeatureBinding()).setDataEncryptionAlgorithm(MessageConstants.AES_BLOCK_ENCRYPTION_128);
	        IssuedTokenKeyBinding ieKB = 
    	        (IssuedTokenKeyBinding)encryptPolicy.newIssuedTokenKeyBinding();
                ieKB.setIncludeToken(Token.INCLUDE_NEVER);
                DerivedTokenKeyBinding dktEncKB = (DerivedTokenKeyBinding)encryptPolicy.newDerivedTokenKeyBinding();
                 dktEncKB.setOriginalKeyBinding(ieKB);

        	QName name = new QName("IssuedToken");
	        Token tok = new Token(name);
    	        //isKB.setPolicyToken(tok);
        	//ieKB.setPolicyToken(tok);
                isKB.setUUID(new String("11016"));
                ieKB.setUUID(new String("11016"));
    	        MessagePolicy pol = new MessagePolicy();
                //pol.dumpMessages(true);
        	signaturePolicy.setUUID("22222");
	        pol.append(encryptPolicy);
    	        pol.append(signaturePolicy);
 
                context.setSecurityPolicy(pol);

    	        SecurityAnnotator.secureMessage(context);

                return context.getSOAPMessage();
    
public static voidtestTrustIntegrationTest()

        
                //System.setProperty("com.sun.xml.wss.saml.binding.jaxb", "true");
	       // alg.setType(AlgorithmSuiteValue.Basic128);
                alg = new AlgorithmSuite(AlgorithmSuiteValue.Basic128.getDigAlgorithm(), AlgorithmSuiteValue.Basic128.getEncAlgorithm(), AlgorithmSuiteValue.Basic128.getSymKWAlgorithm(), AlgorithmSuiteValue.Basic128.getAsymKWAlgorithm());
    	        SignaturePolicy signaturePolicy = new SignaturePolicy();
        	SignatureTarget st = new SignatureTarget();
	        st.setType("qname");
    	        st.setDigestAlgorithm(DigestMethod.SHA1);
        	SignatureTarget.Transform trans = new SignatureTarget.Transform();
	        trans.setTransform(MessageConstants.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
    	        st.addTransform(trans);

        	((SignaturePolicy.FeatureBinding)signaturePolicy.getFeatureBinding()).
            	        addTargetBinding(st);
	        ((SignaturePolicy.FeatureBinding)signaturePolicy.getFeatureBinding()).
    	                setCanonicalizationAlgorithm(MessageConstants.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);

        	IssuedTokenKeyBinding isKB = 
            	(IssuedTokenKeyBinding)signaturePolicy.newIssuedTokenKeyBinding();

                DerivedTokenKeyBinding dktSigKB = (DerivedTokenKeyBinding)signaturePolicy.newDerivedTokenKeyBinding();
                dktSigKB.setOriginalKeyBinding(isKB);

	        EncryptionPolicy encryptPolicy = new EncryptionPolicy();
    	        EncryptionTarget et = new EncryptionTarget();
        	et.setType("qname");
	        ((EncryptionPolicy.FeatureBinding)encryptPolicy.getFeatureBinding()).
    	                addTargetBinding(st);
        	((EncryptionPolicy.FeatureBinding)encryptPolicy.getFeatureBinding()).setDataEncryptionAlgorithm(MessageConstants.AES_BLOCK_ENCRYPTION_128);
	        IssuedTokenKeyBinding ieKB = 
    	        (IssuedTokenKeyBinding)encryptPolicy.newIssuedTokenKeyBinding();

                 DerivedTokenKeyBinding dktEncKB = (DerivedTokenKeyBinding)encryptPolicy.newDerivedTokenKeyBinding();
                 dktEncKB.setOriginalKeyBinding(ieKB);

        	QName name = new QName("IssuedToken");
	        Token tok = new Token(name);
    	        //isKB.setPolicyToken(tok);
        	//ieKB.setPolicyToken(tok);
                isKB.setUUID(new String("12015"));
                ieKB.setUUID(new String("12015"));
    	        MessagePolicy pol = new MessagePolicy();
                //pol.dumpMessages(true);
        	signaturePolicy.setUUID("22222");
	        pol.append(encryptPolicy);
    	        pol.append(signaturePolicy);
        
	        SOAPMessage msg = MessageFactory.newInstance().createMessage();
    	        SOAPBody body = msg.getSOAPBody();
        	SOAPBodyElement sbe = body.addBodyElement(
	                    SOAPFactory.newInstance().createName(
    	                "StockSymbol",
        	            "tru",
            	        "http://fabrikam123.com/payloads"));
	        sbe.addTextNode("QQQ");

	        //Create processing context and set the soap
    	        //message to be processed.
        	ProcessingContextImpl context = new ProcessingContextImpl();
	        context.setSOAPMessage(msg);
                context.hasIssuedToken(true);
    	        // create a new IssuedTokenContext
        	IssuedTokenContextImpl impl = new IssuedTokenContextImpl();
        
    	        SecureRandom rnd = SecureRandom.getInstance("SHA1PRNG");
        	byte[] keyBytes = new byte[16];
	        rnd.nextBytes(keyBytes);
    	        impl.setProofKey(keyBytes);

	        // create a SAML Token and set it here
                Assertion assertion = createHOKAssertion(keyBytes, msg.getSOAPPart());
                
                // Get the client's public and private key to sign SAML Assertion
                                                                                                                                                             
                SignatureKeyCallback.DefaultPrivKeyCertRequest request =
                    new SignatureKeyCallback.DefaultPrivKeyCertRequest();
                Callback skc = new SignatureKeyCallback(request);
                Callback[] callbacks = {skc};
                CallbackHandler handler = new PolicyCallbackHandler1("client");
                handler.handle(callbacks);
                PrivateKey stsPrivKey = request.getPrivateKey();
                                                                                                                                                             
                // Sign the assertion with Client's private key
                Element signedSamlElem = assertion.sign(request.getX509Certificate(), stsPrivKey);
                                                                                                                                                             
                impl.setSecurityToken(new GenericToken(signedSamlElem));
	        
                SecurityTokenReference str = new SecurityTokenReference(msg.getSOAPPart());
                KeyIdentifier samlRef = new SamlKeyIdentifier(msg.getSOAPPart());
                samlRef.setReferenceValue(assertion.getAssertionID());
                str.setReference(samlRef);           
                impl.setAttachedSecurityTokenReference(str);
                impl.setUnAttachedSecurityTokenReference(str);
                
                map.put(new String("12015"), impl);
	        //map.put(tok.getTokenId(), impl);
    	        context.setIssuedTokenContextMap(map);
        	context.setAlgorithmSuite(alg);
	        context.setSecurityPolicy(pol);
    	        //CallbackHandler handler = new PolicyCallbackHandler1("client");
        	SecurityEnvironment env = new DefaultSecurityEnvironmentImpl(handler);
	        context.setSecurityEnvironment(env);

    	        SecurityAnnotator.secureMessage(context);

        	SOAPMessage secMsg = context.getSOAPMessage();

    	        // now persist the message and read-back
        	FileOutputStream sentFile = new FileOutputStream("golden.msg");
	        secMsg.saveChanges();
    	        saveMimeHeaders(secMsg, "golden.mh");
	        msg.writeTo(sentFile);
    	        sentFile.close();

        	// now create the message
	        SOAPMessage recMsg = constructMessage("golden.mh", "golden.msg");
        
	        // verify
    	        ProcessingContextImpl ctxImpl = verify(recMsg);
                SOAPMessage vMsg = ctxImpl.getSOAPMessage();
                vMsg.saveChanges();
                ctxImpl.setSOAPMessage(vMsg);
 
                SOAPMessage newMsg = testResponse(ctxImpl);
                newMsg.saveChanges();
                context.setSOAPMessage(newMsg);

    
public static com.sun.xml.wss.impl.ProcessingContextImplverify(javax.xml.soap.SOAPMessage msg)

       //Create processing context and set the soap
       //message to be processed.
       ProcessingContextImpl context = new ProcessingContextImpl();
       context.setSOAPMessage(msg);
       context.hasIssuedToken(true);                                                                                                        
        MessagePolicy pol = new MessagePolicy();
        //pol.dumpMessages(true);
        //pol.append(signaturePolicy);
        context.setAlgorithmSuite(alg);
                                                                                                           
        context.setSecurityPolicy(pol);
        CallbackHandler handler = new PolicyCallbackHandler1("server");
        SecurityEnvironment env = new DefaultSecurityEnvironmentImpl(handler);
        context.setSecurityEnvironment(env);

        SecurityRecipient.validateMessage(context);

        //context.getSOAPMessage().writeTo(System.out);

        return context;