Java Webservice Client UsernameToken equivalent to PHP

巧了我就是萌 提交于 2019-11-30 01:01:27

I found a solution. My problem was that I forgot to add hex encode to the NONCE Value and to the concated string. Here is my solution, maybe some need this.

The functions to create pass etc.:

private String calculatePasswordDigest(String nonce, String created, String password) {
        String encoded = null;
        try {
            String pass = hexEncode(nonce) + created + password;
            MessageDigest md = MessageDigest.getInstance( "SHA1" );
            md.update( pass.getBytes() );
            byte[] encodedPassword = md.digest();
            encoded = Base64.encodeBytes(encodedPassword);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(HeaderHandler.class.getName()).log(Level.SEVERE, null, ex);
        }

        return encoded;
    }

    private String hexEncode(String in) {
        StringBuilder sb = new StringBuilder("");
        for (int i = 0; i < (in.length() - 2) + 1; i = i + 2) {
            int c = Integer.parseInt(in.substring(i, i + 2), 16);
            char chr = (char) c;
            sb.append(chr);
        }
        return sb.toString();
    }

Code to build the soap message:

String timestamp = HeaderHandler.localToGmtTimestamp();
String pass = "password";
String user = "username";
String nonceString = getNonce();


String dig=calculatePasswordDigest(nonceString, timestamp, pass);


SOAPEnvelope envelope = smc.getMessage().getSOAPPart().getEnvelope();
SOAPHeader header = envelope.addHeader();

SOAPElement security =
header.addChildElement("Security", "wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");


SOAPElement usernameToken =
security.addChildElement("UsernameToken", "wsse");


SOAPElement username =
usernameToken.addChildElement("Username", "wsse");
username.addTextNode(user);

SOAPElement password =
usernameToken.addChildElement("Password", "wsse");
password.setAttribute("Type", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest");
password.addTextNode(dig);

SOAPElement nonce =
usernameToken.addChildElement("Nonce", "wsse");
nonce.addTextNode(Base64.encodeBytes(hexEncode(nonceString).getBytes()));

SOAPElement created = usernameToken.addChildElement("Created", "wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
created.addTextNode(timestamp);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!