Tagged: wss4j

WS-Security UsernameToken with Password Derived Key


@Override
public boolean handleMessage(final SOAPMessageContext context) {

    final boolean outbound =
        (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);

    if (outbound) { // out-going

        final SOAPEnvelope envelope;
        try {
            envelope = context.getMessage().getSOAPPart().getEnvelope();
        } catch (SOAPException soape) {
            soape.printStackTrace(System.err);
            return false;
        }

        final Document document = ((Node) envelope).getOwnerDocument();

        final WSSecHeader header = new WSSecHeader();
        try {
            header.insertSecurityHeader(document);
        } catch (WSSecurityException wsse) {
            wsse.printStackTrace(System.err);
            return false;
        }

        final WSSecUsernameToken usernameToken = new WSSecUsernameToken();
        usernameToken.setUserInfo(USERNAME, PASSWORD);
        usernameToken.addDerivedKey(false, null, 8192);
        usernameToken.prepare(document);

        final byte[] derivedKey;
        try {
            derivedKey = usernameToken.getDerivedKey();
        } catch (WSSecurityException wsse) {
            wsse.printStackTrace(System.err);
            return false;
        }

        final WSSecDKEncrypt encrypt = new WSSecDKEncrypt();
        encrypt.setExternalKey(derivedKey, usernameToken.getId());
        encrypt.setSymmetricEncAlgorithm(WSConstants.AES_256);
        encrypt.setCustomValueType(
            WSConstants.WSS_USERNAME_TOKEN_VALUE_TYPE);
        try {
            encrypt.build(document, header);
        } catch (WSSecurityException wsse) {
            wsse.printStackTrace(System.err);
            return true;
        } catch (ConversationException ce) {
            ce.printStackTrace(System.err);
            return false;
        }

        usernameToken.prependToHeader(header);

        return true;

    } else { // in-coming
        return true;
    }
}
Advertisements