HTTP digest authentication with HttpUrlConnection
<p>I am trying to connect to the Tomcat Web Server on my machine using a digest authentication. I am using the memory realm of tomcat. Here is how the server is configured:</p>

<p>1) In server.xml:</p>

<pre><code>&lt;Realm className="org.apache.catalina.realm.MemoryRealm" digest="MD5" /&gt;
</code></pre>

<p>2) In tomcat-users.xml</p>

<pre><code>&lt;user username="testuser" password="81dc9bdb52d04dc20036dbd8313ed055" roles="test"/&gt;
</code></pre>

<p>3) In web.xml of my web project:</p>

<pre><code>&lt;auth-method&gt;DIGEST&lt;/auth-method&gt;
</code></pre>

<p>As you can see I have specified as a digest method "MD5" and I have encryped the password using the digest.sh of Tomcat.</p>

<p>Here is my code on the client side:</p>

<pre><code>private static void testGet() throws IOException {

    // Create a URL
    URL test = new URL("http://localhost:8080/TestWebProject/TestServlet");

    // Open a connection to the URL
    HttpURLConnection conn = (HttpURLConnection) test.openConnection();

    MessageDigest md5 = null;
    try {
      md5 = MessageDigest.getInstance("MD5");
    } catch(NoSuchAlgorithmException e) {
      e.printStackTrace();
    }

    // Digest password using the MD5 algorithm
    String password = "1234";
    md5.update(password.getBytes());
    String digestedPass = digest2HexString(md5.digest());

    // Set header "Authorization"
    String credentials = "testuser:" + digestedPass;
    conn.setRequestProperty("Authorization", "Digest " + credentials);

    // Print status code and message
    System.out.println("Test HTTP GET method:");
    System.out.println("Status code: " + conn.getResponseCode());
    System.out.println("Message: " + conn.getResponseMessage());
    System.out.println();

}

private static String digest2HexString(byte[] digest)
{
   String digestString="";
   int low, hi ;

   for(int i=0; i &lt; digest.length; i++)
   {
      low =  ( digest[i] &amp; 0x0f ) ;
      hi  =  ( (digest[i] &amp; 0xf0)&gt;&gt;4 ) ;
      digestString += Integer.toHexString(hi);
      digestString += Integer.toHexString(low);
   }
   return digestString ;
}
</code></pre>

<p>I think that my client side code is ok and the configuration of the server, too. Though the server keeps sending me the status code 401 with message "Unauthorized". As I am not an experienced java developer, I want to ask if anyone has idea or sees an error in my implementation.</p>

<p>Thank you in advance!</p>
