Need help creating a valid nonce

Amy picture Amy · Sep 4, 2015 · Viewed 13.4k times · Source

I am trying to consume a web service that uses Password Digest mode, and I have these functions in my Java application to generate a random nonce, creation date and password digest. I can't get past the Authentication Failed error, and the documentation isn't overly clear on whether they want SHA-1 or MD5, as it mentions both in passing. I've tried MD5 instead of SHA-1 and I am getting the same result. I managed to get the requests to work via a test on SoapUI, but I have no idea how that application is generating the digest / nonce. Any help is appreciated.

Here's the code I am using to generate the nonce and the password digest:

    private static SOAPMessage createSOAPRequest() throws Exception 
    {
        String password = "FakePassword";

        String nonce = generateNonce(); 
        System.out.println("Nonce = " + nonce);

        DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date today = Calendar.getInstance().getTime();
        String created = dateFormatter.format(today);
        System.out.println("Created = " + created);

        String passwordDigest = buildPasswordDigest(nonce, created, password);
        System.out.println("Password Digest = " + passwordDigest);
    }

    private static String buildPasswordDigest(String nonce, String created, String password) throws NoSuchAlgorithmException, UnsupportedEncodingException
    {
        MessageDigest sha1;
        String passwordDigest = null;

        try
        {
            sha1 = MessageDigest.getInstance("SHA-1");
            sha1.update(Base64.decodeBase64(nonce));
            sha1.update(created.getBytes("UTF-8"));
            passwordDigest = new String(Base64.encodeBase64(sha1.digest(password.getBytes("UTF-8"))));
            sha1.reset();
        }
        catch (NoSuchAlgorithmException e) 
        {
            e.printStackTrace();
        }

        return passwordDigest;
    }

    private static String generateNonce() throws NoSuchAlgorithmException, NoSuchProviderException, UnsupportedEncodingException
    {
        String dateTimeString = Long.toString(new Date().getTime());
        byte[] nonceByte = dateTimeString.getBytes();
        return Base64.encodeBase64String(nonceByte);
    }

Answer

F. Stephen Q picture F. Stephen Q · Sep 4, 2015

The solution was to replace the line sha1.update(nonce.getBytes("UTF-8")); with sha1.update(Base64.decodeBase64(nonce));