Package org.apache.ws.security.message

Examples of org.apache.ws.security.message.WSSecEncrypt


     *             decryption, or verification
     */
    public void testEncryptionSigning() throws Exception {
        SOAPEnvelope unsignedEnvelope = message.getSOAPEnvelope();
        SOAPEnvelope envelope = null;
        WSSecEncrypt encrypt = new WSSecEncrypt();
        WSSecSignature sign = new WSSecSignature();
        encrypt.setUserInfo("16c73ab6-b892-458f-abf5-2f875f74882e");
        sign.setUserInfo("16c73ab6-b892-458f-abf5-2f875f74882e", "security");
        log.info("Before Encryption....");
        Document doc = unsignedEnvelope.getAsDocument();

        WSSecHeader secHeader = new WSSecHeader();
        secHeader.insertSecurityHeader(doc);

        Document encryptedDoc = encrypt.build(doc, crypto, secHeader);
        Document encryptedSignedDoc = sign.build(encryptedDoc, crypto,
                secHeader);
        /*
         * convert the resulting document into a message first. The
         * toSOAPMessage() mehtod performs the necessary c14n call to properly
View Full Code Here


     */
    public void testEMBED_SECURITY_TOKEN_REF() throws Exception {

        SOAPEnvelope unsignedEnvelope = message.getSOAPEnvelope();
        SOAPEnvelope envelope = null;
        WSSecEncrypt wsEncrypt = new WSSecEncrypt();

        // Get the message as document
        log.info("Before Encryption....");
        Document doc = unsignedEnvelope.getAsDocument();

        WSSecHeader secHeader = new WSSecHeader();
        secHeader.insertSecurityHeader(doc);

        /*
         * Step 1 :: Add a UserNameToken. Step 2 :: Add an Id to it. Step 3 ::
         * Create a Reference to the UserNameToken. Step 4 :: Setting necessary
         * parameters in WSEncryptBody. Step 5 :: Encrypt using the using the
         * password of UserNameToken.
         */

        // Step 1
        String username = "Dimthu";
        String password = "Sri Lanka Sri Lanka UOM ";
        byte[] key = password.getBytes();

        WSSecUsernameToken builder = new WSSecUsernameToken();
        builder.setPasswordType(WSConstants.PASSWORD_TEXT);
        builder.setUserInfo(username, password);
        builder.build(doc, secHeader);

        // Step 3 ::
        Reference ref = new Reference(doc);
        ref.setURI("#" + builder.getId());
        ref.setValueType("UsernameToken");
        SecurityTokenReference secRef = new SecurityTokenReference(doc);
        secRef.setReference(ref);

        // adding the namespace
        WSSecurityUtil.setNamespace(secRef.getElement(), WSConstants.WSSE_NS,
                WSConstants.WSSE_PREFIX);

        // Step 4 ::
        wsEncrypt.setKeyIdentifierType(WSConstants.EMBED_SECURITY_TOKEN_REF);
        wsEncrypt.setSecurityTokenReference(secRef);
        wsEncrypt.setKey(key);
        wsEncrypt.setSymmetricEncAlgorithm(WSConstants.TRIPLE_DES);

        // Step 4 :: Encrypting using the key.
        Document encDoc = wsEncrypt.build(doc, crypto, secHeader);

        /*
         * convert the resulting document into a message first. The
         * toSOAPMessage() mehtod performs the necessary c14n call to properly
         * set up the signed document and convert it into a SOAP message. After
View Full Code Here

     * encrypt data to the recipient. This is according to WSP
     * specification. Most of the data is extracted from the
     * WSS4JPolicyData, only the user info (name/alias of the certificate in
     * the keystore) must be provided by some other means.
     */
    WSSecEncrypt recEncrypt = null;
    WSS4JPolicyToken recToken = null;
    if ((recToken = wpd.getRecipientToken()) != null) {
      recEncrypt = new WSSecEncrypt();
      recEncrypt.setUserInfo("wss4jcert");
      recEncrypt.setKeyIdentifierType(recToken.getKeyIdentifier());
      recEncrypt.setSymmetricEncAlgorithm(recToken.getEncAlgorithm());
      recEncrypt.setKeyEnc(recToken.getEncTransportAlgorithm());
      recEncrypt.prepare(doc, cryptoSKI);
    }

    /*
     * Check for an initiator token. If one is avaliable use it as token to
     * sign data. This is according to WSP specification. Most of the data
     * is extracted from the WSS4JPolicyData, only the user info (name/alias
     * of the certificate in the keystore) must be provided by some other
     * means.
     *
     * If SignatureProtection is enabled add the signature to the encrypted
     * parts vector. In any case the signature must be in the internal
     * ReferenceList (this list is a child of the EncryptedKey element).
     *
     * If TokenProtection is enabled add an appropriate signature reference.
     *
     * TODO Check / enable for STRTransform
     */
    WSSecSignature iniSignature = null;
    WSS4JPolicyToken iniToken = null;
    if ((iniToken = wpd.getInitiatorToken()) != null) {
      iniSignature = new WSSecSignature();
      iniSignature.setUserInfo("16c73ab6-b892-458f-abf5-2f875f74882e",
          "security");
      iniSignature.setKeyIdentifierType(iniToken.getKeyIdentifier());
      iniSignature.setSignatureAlgorithm(iniToken.getSigAlgorithm());
      iniSignature.prepare(doc, crypto, secHeader);
      if (wpd.isSignatureProtection()) {
        encPartsInternal.add(new WSEncryptionPart(iniSignature.getId(),
            "Element"));
      }
      if (wpd.isTokenProtection()) {
        sigParts.add(new WSEncryptionPart("Token", null, null));
      }
    }

    Element body = WSSecurityUtil.findBodyElement(doc, soapConstants);
    if (body == null) {
      System.out
          .println("No SOAP Body found - illegal message structure. Processing terminated");
      return;
    }
    WSEncryptionPart bodyPart = new WSEncryptionPart("Body", soapConstants
        .getEnvelopeURI(), "Content");

    /*
     * Check the protection order. If Encrypt before signing then first take
     * all parts and elements to encrypt and encrypt them. Take their ids
     * after encryption and put them to the parts to be signed.
     *
     */
    Element externRefList = null;
    if (Constants.ENCRYPT_BEFORE_SIGNING.equals(wpd.getProtectionOrder())) {
      /*
       * Process Body: it sign and encrypt: first encrypt the body, insert
       * the body to the parts to be signed.
       *
       * If just to be signed: add the plain Body to the parts to be
       * signed
       */
      if (wpd.isSignBody()) {
        if (wpd.isEncryptBody()) {
          Vector parts = new Vector();
          parts.add(bodyPart);
          externRefList = recEncrypt.encryptForExternalRef(
              externRefList, parts);
          sigParts.add(bodyPart);
        } else {
          sigParts.add(bodyPart);
        }
      }
      /*
       * Here we need to handle signed/encrypted parts:
       *
       * Get all parts that need to be encrypted _and_ signed, encrypt
       * them, get ids of thier encrypted data elements and add these ids
       * to the parts to be signed
       *
       * Then encrypt the remaining parts that don't need to be signed.
       *
       * Then add the remaining parts that don't nedd to be encrypted to
       * the parts to be signed.
       *
       * Similar handling for signed/encrypted elements (compare XPath
       * strings?)
       *
       * After all elements are encrypted put the external refernce list
       * to the security header. is at the bottom of the security header)
       */

      recEncrypt.addExternalRefElement(externRefList, secHeader);

      /*
       * Now handle the supporting tokens - according to OASIS WSP
       * supporting tokens are not part of a Binding assertion but a top
       * level assertion similar to Wss11 or SignedParts. If supporting
       * tokens are available their BST elements have to be added later
       * (probably prepended to the initiator token - see below)
       */

      /*
       * Now add the various elements to the header. We do a strict layout
       * here.
       *
       */
      /*
       * Prepend Signature to the supporting tokens that sign the primary
       * signature
       */
      iniSignature.prependToHeader(secHeader);
      /*
       * This prepends a possible initiator token to the security header
       */
      iniSignature.prependBSTElementToHeader(secHeader);
      /*
       * Here prepend BST elements of supporting tokens
       * (EndorsingSupportTokens), then prepend supporting token that do
       * not sign the primary signature but are signed by the primary
       * signature. Take care of the TokenProtection protery!?
       */

      /*
       * Add the encrypted key element and then the associated BST element
       * recipient token)
       */
      recEncrypt.prependToHeader(secHeader);
      recEncrypt.prependBSTElementToHeader(secHeader);

      /*
       * Now we are ready to per Signature processing.
       *
       * First the primary Signature then supporting tokens (Signatures)
       * that sign the primary Signature.
       */
      timestamp.prependToHeader(secHeader);

      iniSignature.addReferencesToSign(sigParts, secHeader);
      iniSignature.computeSignature();
      Element internRef = recEncrypt.encryptForInternalRef(null,
          encPartsInternal);
      recEncrypt.addInternalRefElement(internRef);
    } else {
      System.out.println("SignBeforeEncrypt needs to be implemented");
    }

    log.info("After creating Message asymm....");
View Full Code Here

     * @throws Exception Thrown when there is any problem in signing or verification
     */
     public void testEncryptionDecryptionOAEP() throws Exception {
        SOAPEnvelope unsignedEnvelope = message.getSOAPEnvelope();
        SOAPEnvelope envelope = null;
        WSSecEncrypt builder = new WSSecEncrypt();
        builder.setUserInfo("wss4jcert");
        builder.setKeyIdentifierType(WSConstants.X509_KEY_IDENTIFIER);
        builder.setKeyEnc(WSConstants.KEYTRANSPORT_RSAOEP);
        Document doc = unsignedEnvelope.getAsDocument();
        WSSecHeader secHeader = new WSSecHeader();
        secHeader.insertSecurityHeader(doc);       
        log.info("Before Encryption Triple DES/RSA-OAEP....");
        Document encryptedDoc = builder.build(doc, crypto, secHeader);
        log.info("After Encryption Triple DES/RSA-OAEP....");

        Message encryptedMsg = (Message) SOAPUtil.toSOAPMessage(encryptedDoc);
        if (log.isDebugEnabled()) {
            log.debug("Encrypted message, RSA-OAEP keytransport, 3DES:");
View Full Code Here

     *             verification
     */
    public void testEncryptionEncryption() throws Exception {
        SOAPEnvelope unsignedEnvelope = message.getSOAPEnvelope();
        SOAPEnvelope envelope = null;
        WSSecEncrypt encrypt = new WSSecEncrypt();
        encrypt.setUserInfo("16c73ab6-b892-458f-abf5-2f875f74882e");
        log.info("Before Encryption....");
        Document doc = unsignedEnvelope.getAsDocument();
        WSSecHeader secHeader = new WSSecHeader();
        secHeader.insertSecurityHeader(doc);

        Document encryptedDoc = encrypt.build(doc, crypto, secHeader);
        Document encryptedEncryptedDoc = encrypt.build(encryptedDoc, crypto,
                secHeader);

        /*
         * convert the resulting document into a message first. The
         * toSOAPMessage() mehtod performs the necessary c14n call to properly
View Full Code Here

     * @throws Exception Thrown when there is any problem in signing or verification
     */
    public void testEncryptionDecryptionRSA15() throws Exception {
        SOAPEnvelope unsignedEnvelope = message.getSOAPEnvelope();
        SOAPEnvelope envelope = null;
        WSSecEncrypt builder = new WSSecEncrypt();
        builder.setUserInfo("wss4jcert");
        builder.setKeyIdentifierType(WSConstants.BST_DIRECT_REFERENCE);
        builder.setSymmetricEncAlgorithm(WSConstants.TRIPLE_DES);
        Document doc = unsignedEnvelope.getAsDocument();
        WSSecHeader secHeader = new WSSecHeader();
        secHeader.insertSecurityHeader(doc);
        log.info("Before Encryption Triple DES....");
        Document encryptedDoc = builder.build(doc, crypto, secHeader);
        log.info("After Encryption Triple DES....");

        /*
         * convert the resulting document into a message first. The toSOAPMessage()
         * method performs the necessary c14n call to properly set up the signed
         * document and convert it into a SOAP message. Check that the contents can't
          * be read (cheching if we can find a specific substring). After that we extract it
         * as a document again for further processing.
         */

        Message encryptedMsg = (Message) SOAPUtil.toSOAPMessage(encryptedDoc);
        if (log.isDebugEnabled()) {
            log.debug("Encrypted message, RSA-15 keytransport, 3DES:");
            XMLUtils.PrettyElementToWriter(encryptedMsg.getSOAPEnvelope().getAsDOM(), new PrintWriter(System.out));
        }
        String encryptedString = encryptedMsg.getSOAPPartAsString();
        assertTrue(encryptedString.indexOf("LogTestService2") == -1 ? true : false);
        encryptedDoc = encryptedMsg.getSOAPEnvelope().getAsDocument();
        verify(encryptedDoc);

        /*
         * second run, same Junit set up, but change encryption method,
         * key identification, encryption mode (Element now), and data to encrypt.
         * This tests if several runs of different algorithms on same builder/cipher
         * setup are ok.
         */
        message = getSOAPMessage(); // create fresh message envrionment
        builder.setKeyIdentifierType(WSConstants.ISSUER_SERIAL);
        builder.setSymmetricEncAlgorithm(WSConstants.AES_128);
        Vector parts = new Vector();
        WSEncryptionPart encP =
            new WSEncryptionPart("testMethod", "uri:LogTestService2", "Element");
        parts.add(encP);
        builder.setParts(parts);
        unsignedEnvelope = message.getSOAPEnvelope();
        doc = unsignedEnvelope.getAsDocument();
        secHeader = new WSSecHeader();
        secHeader.insertSecurityHeader(doc);       
        log.info("Before Encryption AES 128/RSA-15....");
        encryptedDoc = builder.build(doc, crypto, secHeader);
        log.info("After Encryption AES 128/RSA-15....");
        encryptedMsg = (Message) SOAPUtil.toSOAPMessage(encryptedDoc);
        if (log.isDebugEnabled()) {
            log.debug("Encrypted message, RSA-15 keytransport, AES 128:");
            XMLUtils.PrettyElementToWriter(encryptedMsg.getSOAPEnvelope().getAsDOM(), new PrintWriter(System.out));
View Full Code Here

     *             Thrown when there is any problem in encryption or
     *             verification
     */
    public void testEncryptionEncryption() throws Exception {
        SOAPEnvelope unsignedEnvelope = message.getSOAPEnvelope();
        WSSecEncrypt encrypt = new WSSecEncrypt();
        encrypt.setUserInfo("16c73ab6-b892-458f-abf5-2f875f74882e");
        LOG.info("Before Encryption....");
        Document doc = unsignedEnvelope.getAsDocument();
        WSSecHeader secHeader = new WSSecHeader();
        secHeader.insertSecurityHeader(doc);

        Document encryptedDoc = encrypt.build(doc, crypto, secHeader);
        Document encryptedEncryptedDoc = encrypt.build(encryptedDoc, crypto,
                secHeader);

        LOG.info("After Encryption....");
        verify(encryptedEncryptedDoc);
    }
View Full Code Here

        encrKey.setKeyIdentifierType(WSConstants.ISSUER_SERIAL);
        encrKey.setUserInfo("16c73ab6-b892-458f-abf5-2f875f74882e", "security");
        encrKey.setKeySize(192);
        encrKey.prepare(doc, crypto);  
       
        WSSecEncrypt encrypt = new WSSecEncrypt();
        encrypt.setEncKeyId(encrKey.getId());
        encrypt.setEphemeralKey(encrKey.getEphemeralKey());
        encrypt.setSymmetricEncAlgorithm(WSConstants.TRIPLE_DES);
        encrypt.setEncryptSymmKey(false);
        encrypt.setEncryptedKeyElement(encrKey.getEncryptedKeyElement());

        WSSecSignature sign = new WSSecSignature();
        sign.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING);
        sign.setCustomTokenId(encrKey.getId());
        sign.setSecretKey(encrKey.getEphemeralKey());
        sign.setSignatureAlgorithm(SignatureMethod.HMAC_SHA1);

        Document signedDoc = sign.build(doc, crypto, secHeader);
        Document encryptedSignedDoc = encrypt.build(signedDoc, crypto, secHeader);

        if (LOG.isDebugEnabled()) {
            LOG.debug("Signed and encrypted message with IssuerSerial key identifier (both), 3DES:");
            String outputString =
                org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(encryptedSignedDoc);
View Full Code Here

            if (encrToken.isDerivedKeys()) {
                return doEncryptionDerived(recToken, encrTok, encrToken,
                                           attached, encrParts, atEnd);
            } else {
                try {
                    WSSecEncrypt encr = new WSSecEncrypt(wssConfig);
                    String encrTokId = encrTok.getId();
                    if (attached) {
                        encrTokId = encrTok.getWsuId();
                        if (encrTokId == null
                            && (encrToken instanceof SecureConversationToken
                                || encrToken instanceof SecurityContextToken)) {
                            encr.setEncKeyIdDirectId(true);
                            encrTokId = encrTok.getId();
                        } else if (encrTokId == null) {
                            encrTokId = encrTok.getId();
                        }
                        if (encrTokId.startsWith("#")) {
                            encrTokId = encrTokId.substring(1);
                        }
                    } else {
                        encr.setEncKeyIdDirectId(true);
                    }
                    if (encrTok.getTokenType() != null) {
                        encr.setCustomReferenceValue(encrTok.getTokenType());
                    }
                    encr.setEncKeyId(encrTokId);
                    encr.setEphemeralKey(encrTok.getSecret());
                    Crypto crypto = getEncryptionCrypto(recToken);
                    if (crypto != null) {
                        this.message.getExchange().put(SecurityConstants.ENCRYPT_CRYPTO, crypto);
                        setEncryptionUser(encr, recToken, false, crypto);
                    }
                   
                    encr.setDocument(saaj.getSOAPPart());
                    encr.setEncryptSymmKey(false);
                    encr.setSymmetricEncAlgorithm(algorithmSuite.getEncryption());
                   
                    if (encrToken instanceof IssuedToken) {
                        //Setting the AttachedReference or the UnattachedReference according to the flag
                        Element ref;
                        if (attached) {
                            ref = encrTok.getAttachedReference();
                        } else {
                            ref = encrTok.getUnattachedReference();
                        }

                        String tokenType = encrTok.getTokenType();
                        if (ref != null) {
                            SecurityTokenReference secRef =
                                new SecurityTokenReference(cloneElement(ref), false);
                            encr.setSecurityTokenReference(secRef);
                        } else if (WSConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType)
                            || WSConstants.SAML_NS.equals(tokenType)) {
                            encr.setCustomReferenceValue(WSConstants.WSS_SAML_KI_VALUE_TYPE);
                            encr.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
                        } else if (WSConstants.WSS_SAML2_TOKEN_TYPE.equals(tokenType)
                            || WSConstants.SAML2_NS.equals(tokenType)) {
                            encr.setCustomReferenceValue(WSConstants.WSS_SAML2_KI_VALUE_TYPE);
                            encr.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
                        } else {
                            encr.setCustomReferenceValue(tokenType);
                            encr.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
                        }
                    } else if (!isRequestor()) {
                        if (encrTok.getSHA1() != null) {
                            encr.setCustomReferenceValue(encrTok.getSHA1());
                            encr.setKeyIdentifierType(WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER);
                        } else {
                            encr.setKeyIdentifierType(WSConstants.EMBED_SECURITY_TOKEN_REF);
                        }
                    }

                    encr.prepare(saaj.getSOAPPart(), crypto);
                  
                    if (encr.getBSTTokenId() != null) {
                        encr.prependBSTElementToHeader(secHeader);
                    }
                  
                  
                    Element refList = encr.encryptForRef(null, encrParts);
                    if (atEnd) {
                        this.insertBeforeBottomUp(refList);
                    } else {
                        this.addDerivedKeyElement(refList);                       
                    }
View Full Code Here

                } catch (Exception e) {
                    policyNotAsserted(recToken, e);
                }
            } else {
                try {
                    WSSecEncrypt encr = new WSSecEncrypt(wssConfig);
                   
                    encr.setDocument(saaj.getSOAPPart());
                    Crypto crypto = getEncryptionCrypto(recToken);
                   
                    SecurityToken securityToken = getSecurityToken();
                    setKeyIdentifierType(encr, recToken, encrToken);
                    //
                    // Using a stored cert is only suitable for the Issued Token case, where
                    // we're extracting the cert from a SAML Assertion on the provider side
                    //
                    if (!isRequestor() && securityToken != null
                        && securityToken.getX509Certificate() != null) {
                        encr.setUseThisCert(securityToken.getX509Certificate());
                    } else {
                        setEncryptionUser(encr, recToken, false, crypto);
                    }
                    encr.setSymmetricEncAlgorithm(algorithmSuite.getEncryption());
                    encr.setKeyEncAlgo(algorithmSuite.getAsymmetricKeyWrap());
                    encr.prepare(saaj.getSOAPPart(), crypto);
                   
                    if (encr.getBSTTokenId() != null) {
                        encr.prependBSTElementToHeader(secHeader);
                    }
                   
                    Element encryptedKeyElement = encr.getEncryptedKeyElement();
                                      
                    //Encrypt, get hold of the ref list and add it
                    if (externalRef) {
                        Element refList = encr.encryptForRef(null, encrParts);
                        insertBeforeBottomUp(refList);
                    } else {
                        Element refList = encr.encryptForRef(null, encrParts);
                   
                        // Add internal refs
                        encryptedKeyElement.appendChild(refList);
                    }
                    this.addEncryptedKeyElement(encryptedKeyElement);
View Full Code Here

TOP

Related Classes of org.apache.ws.security.message.WSSecEncrypt

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.