View Javadoc
1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  package org.apache.hc.client5.http.impl.auth;
28  
29  import java.io.ByteArrayInputStream;
30  import java.io.ByteArrayOutputStream;
31  import java.io.IOException;
32  import java.io.ObjectInputStream;
33  import java.io.ObjectOutputStream;
34  import java.nio.charset.StandardCharsets;
35  import java.security.MessageDigest;
36  import java.util.HashMap;
37  import java.util.List;
38  import java.util.Map;
39  
40  import org.apache.hc.client5.http.auth.AuthChallenge;
41  import org.apache.hc.client5.http.auth.AuthScheme;
42  import org.apache.hc.client5.http.auth.AuthScope;
43  import org.apache.hc.client5.http.auth.AuthenticationException;
44  import org.apache.hc.client5.http.auth.ChallengeType;
45  import org.apache.hc.client5.http.auth.CredentialsProvider;
46  import org.apache.hc.client5.http.auth.MalformedChallengeException;
47  import org.apache.hc.client5.http.auth.StandardAuthScheme;
48  import org.apache.hc.core5.http.ClassicHttpRequest;
49  import org.apache.hc.core5.http.ContentType;
50  import org.apache.hc.core5.http.HeaderElement;
51  import org.apache.hc.core5.http.HttpHost;
52  import org.apache.hc.core5.http.HttpRequest;
53  import org.apache.hc.core5.http.ParseException;
54  import org.apache.hc.core5.http.io.entity.InputStreamEntity;
55  import org.apache.hc.core5.http.io.entity.StringEntity;
56  import org.apache.hc.core5.http.message.BasicClassicHttpRequest;
57  import org.apache.hc.core5.http.message.BasicHeaderValueParser;
58  import org.apache.hc.core5.http.message.BasicHttpRequest;
59  import org.apache.hc.core5.http.message.ParserCursor;
60  import org.apache.hc.core5.util.CharArrayBuffer;
61  import org.junit.jupiter.api.Assertions;
62  import org.junit.jupiter.api.Test;
63  
64  /**
65   * Test Methods for DigestScheme Authentication.
66   */
67  public class TestDigestScheme {
68  
69      private static AuthChallenge parse(final String s) throws ParseException {
70          final CharArrayBuffer buffer = new CharArrayBuffer(s.length());
71          buffer.append(s);
72          final ParserCursor cursor = new ParserCursor(0, buffer.length());
73          final List<AuthChallenge> authChallenges = AuthChallengeParser.INSTANCE.parse(ChallengeType.TARGET, buffer, cursor);
74          Assertions.assertEquals(1, authChallenges.size());
75          return authChallenges.get(0);
76      }
77  
78      @Test
79      public void testDigestAuthenticationEmptyChallenge1() throws Exception {
80          final AuthChallenge authChallenge = parse(StandardAuthScheme.DIGEST);
81          final AuthScheme authscheme = new DigestScheme();
82          Assertions.assertThrows(MalformedChallengeException.class, () ->
83                  authscheme.processChallenge(authChallenge, null));
84      }
85  
86      @Test
87      public void testDigestAuthenticationEmptyChallenge2() throws Exception {
88          final AuthChallenge authChallenge = parse(StandardAuthScheme.DIGEST + " ");
89          final AuthScheme authscheme = new DigestScheme();
90          Assertions.assertThrows(MalformedChallengeException.class, () ->
91                  authscheme.processChallenge(authChallenge, null));
92      }
93  
94      @Test
95      public void testDigestAuthenticationWithDefaultCreds() throws Exception {
96          final HttpRequest request = new BasicHttpRequest("Simple", "/");
97          final HttpHost host = new HttpHost("somehost", 80);
98          final CredentialsProvider credentialsProvider = CredentialsProviderBuilder.create()
99                  .add(new AuthScope(host, "realm1", null), "username", "password".toCharArray())
100                 .build();
101 
102         final String challenge = StandardAuthScheme.DIGEST + " realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\"";
103         final AuthChallenge authChallenge = parse(challenge);
104         final DigestScheme authscheme = new DigestScheme();
105         authscheme.processChallenge(authChallenge, null);
106 
107         Assertions.assertTrue(authscheme.isResponseReady(host, credentialsProvider, null));
108         final String authResponse = authscheme.generateAuthResponse(host, request, null);
109         Assertions.assertTrue(authscheme.isChallengeComplete());
110         Assertions.assertFalse(authscheme.isConnectionBased());
111 
112         final Map<String, String> table = parseAuthResponse(authResponse);
113         Assertions.assertEquals("username", table.get("username"));
114         Assertions.assertEquals("realm1", table.get("realm"));
115         Assertions.assertEquals("/", table.get("uri"));
116         Assertions.assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce"));
117         Assertions.assertEquals("e95a7ddf37c2eab009568b1ed134f89a", table.get("response"));
118     }
119 
120     @Test
121     public void testDigestAuthentication() throws Exception {
122         final HttpRequest request = new BasicHttpRequest("Simple", "/");
123         final HttpHost host = new HttpHost("somehost", 80);
124         final CredentialsProvider credentialsProvider = CredentialsProviderBuilder.create()
125                 .add(new AuthScope(host, "realm1", null), "username", "password".toCharArray())
126                 .build();
127 
128         final String challenge = StandardAuthScheme.DIGEST + " realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\"";
129         final AuthChallenge authChallenge = parse(challenge);
130         final DigestScheme authscheme = new DigestScheme();
131         authscheme.processChallenge(authChallenge, null);
132 
133         Assertions.assertTrue(authscheme.isResponseReady(host, credentialsProvider, null));
134         final String authResponse = authscheme.generateAuthResponse(host, request, null);
135 
136         final Map<String, String> table = parseAuthResponse(authResponse);
137         Assertions.assertEquals("username", table.get("username"));
138         Assertions.assertEquals("realm1", table.get("realm"));
139         Assertions.assertEquals("/", table.get("uri"));
140         Assertions.assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce"));
141         Assertions.assertEquals("e95a7ddf37c2eab009568b1ed134f89a", table.get("response"));
142     }
143 
144     @Test
145     public void testDigestAuthenticationInvalidInput() throws Exception {
146         final HttpHost host = new HttpHost("somehost", 80);
147         final CredentialsProvider credentialsProvider = CredentialsProviderBuilder.create()
148                 .add(new AuthScope(host, "realm1", null), "username", "password".toCharArray())
149                 .build();
150 
151         final String challenge = StandardAuthScheme.DIGEST + " realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\"";
152         final AuthChallenge authChallenge = parse(challenge);
153         final DigestScheme authscheme = new DigestScheme();
154         authscheme.processChallenge(authChallenge, null);
155 
156         Assertions.assertThrows(NullPointerException.class, () ->
157                 authscheme.isResponseReady(null, credentialsProvider, null));
158         Assertions.assertThrows(NullPointerException.class, () ->
159                 authscheme.isResponseReady(host, null, null));
160         Assertions.assertThrows(NullPointerException.class, () ->
161                 authscheme.generateAuthResponse(host, null, null));
162     }
163 
164     @Test
165     public void testDigestAuthenticationWithSHA() throws Exception {
166         final HttpRequest request = new BasicHttpRequest("Simple", "/");
167         final HttpHost host = new HttpHost("somehost", 80);
168         final CredentialsProvider credentialsProvider = CredentialsProviderBuilder.create()
169                 .add(new AuthScope(host, "realm1", null), "username", "password".toCharArray())
170                 .build();
171 
172         final String challenge = StandardAuthScheme.DIGEST + " realm=\"realm1\", " +
173                 "nonce=\"f2a3f18799759d4f1a1c068b92b573cb\", " +
174                 "algorithm=SHA";
175         final AuthChallenge authChallenge = parse(challenge);
176         final DigestScheme authscheme = new DigestScheme();
177         authscheme.processChallenge(authChallenge, null);
178 
179         Assertions.assertTrue(authscheme.isResponseReady(host, credentialsProvider, null));
180         final String authResponse = authscheme.generateAuthResponse(host, request, null);
181 
182         final Map<String, String> table = parseAuthResponse(authResponse);
183         Assertions.assertEquals("username", table.get("username"));
184         Assertions.assertEquals("realm1", table.get("realm"));
185         Assertions.assertEquals("/", table.get("uri"));
186         Assertions.assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce"));
187         Assertions.assertEquals("8769e82e4e28ecc040b969562b9050580c6d186d", table.get("response"));
188     }
189 
190     @Test
191     public void testDigestAuthenticationWithQueryStringInDigestURI() throws Exception {
192         final HttpRequest request = new BasicHttpRequest("Simple", "/?param=value");
193         final HttpHost host = new HttpHost("somehost", 80);
194         final CredentialsProvider credentialsProvider = CredentialsProviderBuilder.create()
195                 .add(new AuthScope(host, "realm1", null), "username", "password".toCharArray())
196                 .build();
197 
198         final String challenge = StandardAuthScheme.DIGEST + " realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\"";
199         final AuthChallenge authChallenge = parse(challenge);
200         final DigestScheme authscheme = new DigestScheme();
201         authscheme.processChallenge(authChallenge, null);
202 
203         Assertions.assertTrue(authscheme.isResponseReady(host, credentialsProvider, null));
204         final String authResponse = authscheme.generateAuthResponse(host, request, null);
205 
206         final Map<String, String> table = parseAuthResponse(authResponse);
207         Assertions.assertEquals("username", table.get("username"));
208         Assertions.assertEquals("realm1", table.get("realm"));
209         Assertions.assertEquals("/?param=value", table.get("uri"));
210         Assertions.assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce"));
211         Assertions.assertEquals("a847f58f5fef0bc087bcb9c3eb30e042", table.get("response"));
212     }
213 
214     @Test
215     public void testDigestAuthenticationNoRealm() throws Exception {
216         final HttpRequest request = new BasicHttpRequest("Simple", "/");
217         final HttpHost host = new HttpHost("somehost", 80);
218         final CredentialsProvider credentialsProvider = CredentialsProviderBuilder.create()
219                 .add(new AuthScope(host, "realm1", null), "username", "password".toCharArray())
220                 .build();
221 
222         final String challenge = StandardAuthScheme.DIGEST + " no-realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\"";
223         final AuthChallenge authChallenge = parse(challenge);
224         final DigestScheme authscheme = new DigestScheme();
225         authscheme.processChallenge(authChallenge, null);
226 
227         Assertions.assertTrue(authscheme.isResponseReady(host, credentialsProvider, null));
228         Assertions.assertThrows(AuthenticationException.class, () ->
229                 authscheme.generateAuthResponse(host, request, null));
230     }
231 
232     @Test
233     public void testDigestAuthenticationNoNonce() throws Exception {
234         final HttpRequest request = new BasicHttpRequest("Simple", "/");
235         final HttpHost host = new HttpHost("somehost", 80);
236         final CredentialsProvider credentialsProvider = CredentialsProviderBuilder.create()
237                 .add(new AuthScope(host, "realm1", null), "username", "password".toCharArray())
238                 .build();
239 
240         final String challenge = StandardAuthScheme.DIGEST + " realm=\"realm1\", no-nonce=\"f2a3f18799759d4f1a1c068b92b573cb\"";
241         final AuthChallenge authChallenge = parse(challenge);
242         final DigestScheme authscheme = new DigestScheme();
243         authscheme.processChallenge(authChallenge, null);
244 
245         Assertions.assertTrue(authscheme.isResponseReady(host, credentialsProvider, null));
246         Assertions.assertThrows(AuthenticationException.class, () ->
247                 authscheme.generateAuthResponse(host, request, null));
248     }
249 
250     /**
251      * Test digest authentication using the MD5-sess algorithm.
252      */
253     @Test
254     public void testDigestAuthenticationMD5Sess() throws Exception {
255         // Example using Digest auth with MD5-sess
256 
257         final String realm="realm";
258         final String username="username";
259         final String password="password";
260         final String nonce="e273f1776275974f1a120d8b92c5b3cb";
261 
262         final HttpRequest request = new BasicHttpRequest("Simple", "/");
263         final HttpHost host = new HttpHost("somehost", 80);
264         final CredentialsProvider credentialsProvider = CredentialsProviderBuilder.create()
265                 .add(new AuthScope(host, realm, null), username, password.toCharArray())
266                 .build();
267 
268         final String challenge=StandardAuthScheme.DIGEST + " realm=\"" + realm + "\", "
269             + "nonce=\"" + nonce + "\", "
270             + "opaque=\"SomeString\", "
271             + "stale=false, "
272             + "algorithm=MD5-sess, "
273             + "qop=\"auth,auth-int\""; // we pass both but expect auth to be used
274 
275         final AuthChallenge authChallenge = parse(challenge);
276 
277         final DigestScheme authscheme = new DigestScheme();
278         authscheme.processChallenge(authChallenge, null);
279 
280         Assertions.assertTrue(authscheme.isResponseReady(host, credentialsProvider, null));
281         final String authResponse = authscheme.generateAuthResponse(host, request, null);
282 
283         Assertions.assertTrue(authResponse.indexOf("nc=00000001") > 0); // test for quotes
284         Assertions.assertTrue(authResponse.indexOf("qop=auth") > 0); // test for quotes
285 
286         final Map<String, String> table = parseAuthResponse(authResponse);
287         Assertions.assertEquals(username, table.get("username"));
288         Assertions.assertEquals(realm, table.get("realm"));
289         Assertions.assertEquals("MD5-sess", table.get("algorithm"));
290         Assertions.assertEquals("/", table.get("uri"));
291         Assertions.assertEquals(nonce, table.get("nonce"));
292         Assertions.assertEquals(1, Integer.parseInt(table.get("nc"),16));
293         Assertions.assertNotNull(table.get("cnonce"));
294         Assertions.assertEquals("SomeString", table.get("opaque"));
295         Assertions.assertEquals("auth", table.get("qop"));
296         //@TODO: add better check
297         Assertions.assertNotNull(table.get("response"));
298     }
299 
300     /**
301      * Test digest authentication using the MD5-sess algorithm.
302      */
303     @Test
304     public void testDigestAuthenticationMD5SessNoQop() throws Exception {
305         // Example using Digest auth with MD5-sess
306 
307         final String realm="realm";
308         final String username="username";
309         final String password="password";
310         final String nonce="e273f1776275974f1a120d8b92c5b3cb";
311 
312         final HttpRequest request = new BasicHttpRequest("Simple", "/");
313         final HttpHost host = new HttpHost("somehost", 80);
314         final CredentialsProvider credentialsProvider = CredentialsProviderBuilder.create()
315                 .add(new AuthScope(host, realm, null), username, password.toCharArray())
316                 .build();
317 
318         final String challenge=StandardAuthScheme.DIGEST + " realm=\"" + realm + "\", "
319             + "nonce=\"" + nonce + "\", "
320             + "opaque=\"SomeString\", "
321             + "stale=false, "
322             + "algorithm=MD5-sess";
323 
324         final AuthChallenge authChallenge = parse(challenge);
325 
326         final DigestScheme authscheme = new DigestScheme();
327         authscheme.processChallenge(authChallenge, null);
328         Assertions.assertTrue(authscheme.isResponseReady(host, credentialsProvider, null));
329         final String authResponse = authscheme.generateAuthResponse(host, request, null);
330 
331         final Map<String, String> table = parseAuthResponse(authResponse);
332         Assertions.assertEquals(username, table.get("username"));
333         Assertions.assertEquals(realm, table.get("realm"));
334         Assertions.assertEquals("MD5-sess", table.get("algorithm"));
335         Assertions.assertEquals("/", table.get("uri"));
336         Assertions.assertEquals(nonce, table.get("nonce"));
337         Assertions.assertNull(table.get("nc"));
338         Assertions.assertEquals("SomeString", table.get("opaque"));
339         Assertions.assertNull(table.get("qop"));
340         //@TODO: add better check
341         Assertions.assertNotNull(table.get("response"));
342     }
343 
344     /**
345      * Test digest authentication with unknown qop value
346      */
347     @Test
348     public void testDigestAuthenticationMD5SessUnknownQop() throws Exception {
349         // Example using Digest auth with MD5-sess
350 
351         final String realm="realm";
352         final String username="username";
353         final String password="password";
354         final String nonce="e273f1776275974f1a120d8b92c5b3cb";
355 
356         final HttpRequest request = new BasicHttpRequest("Simple", "/");
357         final HttpHost host = new HttpHost("somehost", 80);
358         final CredentialsProvider credentialsProvider = CredentialsProviderBuilder.create()
359                 .add(new AuthScope(host, realm, null), username, password.toCharArray())
360                 .build();
361 
362         final String challenge=StandardAuthScheme.DIGEST + " realm=\"" + realm + "\", "
363             + "nonce=\"" + nonce + "\", "
364             + "opaque=\"SomeString\", "
365             + "stale=false, "
366             + "algorithm=MD5-sess, "
367             + "qop=\"stuff\"";
368 
369         final AuthChallenge authChallenge = parse(challenge);
370 
371         final DigestScheme authscheme = new DigestScheme();
372         authscheme.processChallenge(authChallenge, null);
373 
374         Assertions.assertTrue(authscheme.isResponseReady(host, credentialsProvider, null));
375         Assertions.assertThrows(AuthenticationException.class, () ->
376                 authscheme.generateAuthResponse(host, request, null));
377     }
378 
379     /**
380      * Test digest authentication with unknown qop value
381      */
382     @Test
383     public void testDigestAuthenticationUnknownAlgo() throws Exception {
384         // Example using Digest auth with MD5-sess
385 
386         final String realm="realm";
387         final String username="username";
388         final String password="password";
389         final String nonce="e273f1776275974f1a120d8b92c5b3cb";
390 
391         final HttpRequest request = new BasicHttpRequest("Simple", "/");
392         final HttpHost host = new HttpHost("somehost", 80);
393         final CredentialsProvider credentialsProvider = CredentialsProviderBuilder.create()
394                 .add(new AuthScope(host, realm, null), username, password.toCharArray())
395                 .build();
396 
397         final String challenge=StandardAuthScheme.DIGEST + " realm=\"" + realm + "\", "
398             + "nonce=\"" + nonce + "\", "
399             + "opaque=\"SomeString\", "
400             + "stale=false, "
401             + "algorithm=stuff, "
402             + "qop=\"auth\"";
403 
404         final AuthChallenge authChallenge = parse(challenge);
405 
406         final DigestScheme authscheme = new DigestScheme();
407         authscheme.processChallenge(authChallenge, null);
408 
409         Assertions.assertTrue(authscheme.isResponseReady(host, credentialsProvider, null));
410         Assertions.assertThrows(AuthenticationException.class, () ->
411                 authscheme.generateAuthResponse(host, request, null));
412     }
413 
414     @Test
415     public void testDigestAuthenticationWithStaleNonce() throws Exception {
416         final String challenge = StandardAuthScheme.DIGEST + " realm=\"realm1\", " +
417                 "nonce=\"f2a3f18799759d4f1a1c068b92b573cb\", stale=\"true\"";
418         final AuthChallenge authChallenge = parse(challenge);
419         final AuthScheme authscheme = new DigestScheme();
420         authscheme.processChallenge(authChallenge, null);
421 
422         Assertions.assertFalse(authscheme.isChallengeComplete());
423     }
424 
425     private static Map<String, String> parseAuthResponse(final String authResponse) {
426         if (!authResponse.startsWith(StandardAuthScheme.DIGEST + " ")) {
427             return null;
428         }
429         final String s = authResponse.substring(7);
430         final ParserCursor cursor = new ParserCursor(0, s.length());
431         final HeaderElement[] elements = BasicHeaderValueParser.INSTANCE.parseElements(s, cursor);
432         final Map<String, String> map = new HashMap<>(elements.length);
433         for (final HeaderElement element : elements) {
434             map.put(element.getName(), element.getValue());
435         }
436         return map;
437     }
438 
439     @Test
440     public void testDigestNouceCount() throws Exception {
441         final HttpRequest request = new BasicHttpRequest("GET", "/");
442         final HttpHost host = new HttpHost("somehost", 80);
443         final CredentialsProvider credentialsProvider = CredentialsProviderBuilder.create()
444                 .add(new AuthScope(host, "realm1", null), "username", "password".toCharArray())
445                 .build();
446 
447         final String challenge1 = StandardAuthScheme.DIGEST + " realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\", qop=auth";
448         final AuthChallenge authChallenge1 = parse(challenge1);
449 
450         final DigestScheme authscheme = new DigestScheme();
451         authscheme.processChallenge(authChallenge1, null);
452         Assertions.assertTrue(authscheme.isResponseReady(host, credentialsProvider, null));
453         final String authResponse1 = authscheme.generateAuthResponse(host, request, null);
454 
455         final Map<String, String> table1 = parseAuthResponse(authResponse1);
456         Assertions.assertEquals("00000001", table1.get("nc"));
457 
458         Assertions.assertTrue(authscheme.isResponseReady(host, credentialsProvider, null));
459         final String authResponse2 = authscheme.generateAuthResponse(host, request, null);
460 
461         final Map<String, String> table2 = parseAuthResponse(authResponse2);
462         Assertions.assertEquals("00000002", table2.get("nc"));
463         final String challenge2 = StandardAuthScheme.DIGEST + " realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\", qop=auth";
464         final AuthChallenge authChallenge2 = parse(challenge2);
465         authscheme.processChallenge(authChallenge2, null);
466 
467         Assertions.assertTrue(authscheme.isResponseReady(host, credentialsProvider, null));
468         final String authResponse3 = authscheme.generateAuthResponse(host, request, null);
469 
470         final Map<String, String> table3 = parseAuthResponse(authResponse3);
471         Assertions.assertEquals("00000003", table3.get("nc"));
472         final String challenge3 = StandardAuthScheme.DIGEST + " realm=\"realm1\", nonce=\"e273f1776275974f1a120d8b92c5b3cb\", qop=auth";
473         final AuthChallenge authChallenge3 = parse(challenge3);
474         authscheme.processChallenge(authChallenge3, null);
475 
476         Assertions.assertTrue(authscheme.isResponseReady(host, credentialsProvider, null));
477         final String authResponse4 = authscheme.generateAuthResponse(host, request, null);
478 
479         final Map<String, String> table4 = parseAuthResponse(authResponse4);
480         Assertions.assertEquals("00000001", table4.get("nc"));
481     }
482 
483     @Test
484     public void testDigestMD5SessA1AndCnonceConsistency() throws Exception {
485         final HttpHost host = new HttpHost("somehost", 80);
486         final HttpRequest request = new BasicHttpRequest("GET", "/");
487         final CredentialsProvider credentialsProvider = CredentialsProviderBuilder.create()
488                 .add(new AuthScope(host, "subnet.domain.com", null), "username", "password".toCharArray())
489                 .build();
490 
491         final String challenge1 = StandardAuthScheme.DIGEST + " qop=\"auth\", algorithm=MD5-sess, nonce=\"1234567890abcdef\", " +
492                 "charset=utf-8, realm=\"subnet.domain.com\"";
493         final AuthChallenge authChallenge1 = parse(challenge1);
494         final DigestScheme authscheme = new DigestScheme();
495         authscheme.processChallenge(authChallenge1, null);
496         Assertions.assertTrue(authscheme.isResponseReady(host, credentialsProvider, null));
497         final String authResponse1 = authscheme.generateAuthResponse(host, request, null);
498 
499         final Map<String, String> table1 = parseAuthResponse(authResponse1);
500         Assertions.assertEquals("00000001", table1.get("nc"));
501         final String cnonce1 = authscheme.getCnonce();
502         final String sessionKey1 = authscheme.getA1();
503 
504         Assertions.assertTrue(authscheme.isResponseReady(host, credentialsProvider, null));
505         final String authResponse2 = authscheme.generateAuthResponse(host, request, null);
506         final Map<String, String> table2 = parseAuthResponse(authResponse2);
507         Assertions.assertEquals("00000002", table2.get("nc"));
508         final String cnonce2 = authscheme.getCnonce();
509         final String sessionKey2 = authscheme.getA1();
510 
511         Assertions.assertEquals(cnonce1, cnonce2);
512         Assertions.assertEquals(sessionKey1, sessionKey2);
513 
514         final String challenge2 = StandardAuthScheme.DIGEST + " qop=\"auth\", algorithm=MD5-sess, nonce=\"1234567890abcdef\", " +
515             "charset=utf-8, realm=\"subnet.domain.com\"";
516         final AuthChallenge authChallenge2 = parse(challenge2);
517         authscheme.processChallenge(authChallenge2, null);
518         Assertions.assertTrue(authscheme.isResponseReady(host, credentialsProvider, null));
519         final String authResponse3 = authscheme.generateAuthResponse(host, request, null);
520         final Map<String, String> table3 = parseAuthResponse(authResponse3);
521         Assertions.assertEquals("00000003", table3.get("nc"));
522 
523         final String cnonce3 = authscheme.getCnonce();
524         final String sessionKey3 = authscheme.getA1();
525 
526         Assertions.assertEquals(cnonce1, cnonce3);
527         Assertions.assertEquals(sessionKey1, sessionKey3);
528 
529         final String challenge3 = StandardAuthScheme.DIGEST + " qop=\"auth\", algorithm=MD5-sess, nonce=\"fedcba0987654321\", " +
530             "charset=utf-8, realm=\"subnet.domain.com\"";
531         final AuthChallenge authChallenge3 = parse(challenge3);
532         authscheme.processChallenge(authChallenge3, null);
533         Assertions.assertTrue(authscheme.isResponseReady(host, credentialsProvider, null));
534         final String authResponse4 = authscheme.generateAuthResponse(host, request, null);
535         final Map<String, String> table4 = parseAuthResponse(authResponse4);
536         Assertions.assertEquals("00000001", table4.get("nc"));
537 
538         final String cnonce4 = authscheme.getCnonce();
539         final String sessionKey4 = authscheme.getA1();
540 
541         Assertions.assertNotEquals(cnonce1, cnonce4);
542         Assertions.assertNotEquals(sessionKey1, sessionKey4);
543     }
544 
545     @Test
546     public void testHttpEntityDigest() throws Exception {
547         final HttpEntityDigester digester = new HttpEntityDigester(MessageDigest.getInstance("MD5"));
548         Assertions.assertNull(digester.getDigest());
549         digester.write('a');
550         digester.write('b');
551         digester.write('c');
552         digester.write(0xe4);
553         digester.write(0xf6);
554         digester.write(0xfc);
555         digester.write(new byte[] { 'a', 'b', 'c'});
556         Assertions.assertNull(digester.getDigest());
557         digester.close();
558         Assertions.assertEquals("acd2b59cd01c7737d8069015584c6cac", DigestScheme.formatHex(digester.getDigest()));
559         Assertions.assertThrows(IOException.class, () -> digester.write('a'));
560         Assertions.assertThrows(IOException.class, () -> digester.write(new byte[] { 'a', 'b', 'c'}));
561     }
562 
563     @Test
564     public void testDigestAuthenticationQopAuthInt() throws Exception {
565         final ClassicHttpRequest request = new BasicClassicHttpRequest("Post", "/");
566         request.setEntity(new StringEntity("abc\u00e4\u00f6\u00fcabc", StandardCharsets.ISO_8859_1));
567         final HttpHost host = new HttpHost("somehost", 80);
568         final CredentialsProvider credentialsProvider = CredentialsProviderBuilder.create()
569                 .add(new AuthScope(host, "realm1", null), "username", "password".toCharArray())
570                 .build();
571 
572         final String challenge = StandardAuthScheme.DIGEST + " realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\", " +
573                 "qop=\"auth,auth-int\"";
574         final AuthChallenge authChallenge = parse(challenge);
575         final DigestScheme authscheme = new DigestScheme();
576         authscheme.processChallenge(authChallenge, null);
577         Assertions.assertTrue(authscheme.isResponseReady(host, credentialsProvider, null));
578         final String authResponse = authscheme.generateAuthResponse(host, request, null);
579 
580         Assertions.assertEquals("Post:/:acd2b59cd01c7737d8069015584c6cac", authscheme.getA2());
581 
582         final Map<String, String> table = parseAuthResponse(authResponse);
583         Assertions.assertEquals("username", table.get("username"));
584         Assertions.assertEquals("realm1", table.get("realm"));
585         Assertions.assertEquals("/", table.get("uri"));
586         Assertions.assertEquals("auth-int", table.get("qop"));
587         Assertions.assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce"));
588     }
589 
590     @Test
591     public void testDigestAuthenticationQopAuthIntNullEntity() throws Exception {
592         final HttpRequest request = new BasicHttpRequest("Post", "/");
593         final HttpHost host = new HttpHost("somehost", 80);
594         final CredentialsProvider credentialsProvider = CredentialsProviderBuilder.create()
595                 .add(new AuthScope(host, "realm1", null), "username", "password".toCharArray())
596                 .build();
597 
598         final String challenge = StandardAuthScheme.DIGEST + " realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\", " +
599                 "qop=\"auth-int\"";
600         final AuthChallenge authChallenge = parse(challenge);
601         final DigestScheme authscheme = new DigestScheme();
602         authscheme.processChallenge(authChallenge, null);
603         Assertions.assertTrue(authscheme.isResponseReady(host, credentialsProvider, null));
604         final String authResponse = authscheme.generateAuthResponse(host, request, null);
605 
606         Assertions.assertEquals("Post:/:d41d8cd98f00b204e9800998ecf8427e", authscheme.getA2());
607 
608         final Map<String, String> table = parseAuthResponse(authResponse);
609         Assertions.assertEquals("username", table.get("username"));
610         Assertions.assertEquals("realm1", table.get("realm"));
611         Assertions.assertEquals("/", table.get("uri"));
612         Assertions.assertEquals("auth-int", table.get("qop"));
613         Assertions.assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce"));
614     }
615 
616     @Test
617     public void testDigestAuthenticationQopAuthOrAuthIntNonRepeatableEntity() throws Exception {
618         final ClassicHttpRequest request = new BasicClassicHttpRequest("Post", "/");
619         request.setEntity(new InputStreamEntity(new ByteArrayInputStream(new byte[] {'a'}), -1, ContentType.DEFAULT_TEXT));
620         final HttpHost host = new HttpHost("somehost", 80);
621         final CredentialsProvider credentialsProvider = CredentialsProviderBuilder.create()
622                 .add(new AuthScope(host, "realm1", null), "username", "password".toCharArray())
623                 .build();
624 
625         final String challenge = StandardAuthScheme.DIGEST + " realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\", " +
626                 "qop=\"auth,auth-int\"";
627         final AuthChallenge authChallenge = parse(challenge);
628         final DigestScheme authscheme = new DigestScheme();
629         authscheme.processChallenge(authChallenge, null);
630         Assertions.assertTrue(authscheme.isResponseReady(host, credentialsProvider, null));
631         final String authResponse = authscheme.generateAuthResponse(host, request, null);
632 
633         Assertions.assertEquals("Post:/", authscheme.getA2());
634 
635         final Map<String, String> table = parseAuthResponse(authResponse);
636         Assertions.assertEquals("username", table.get("username"));
637         Assertions.assertEquals("realm1", table.get("realm"));
638         Assertions.assertEquals("/", table.get("uri"));
639         Assertions.assertEquals("auth", table.get("qop"));
640         Assertions.assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce"));
641     }
642 
643     @Test
644     public void testParameterCaseSensitivity() throws Exception {
645         final HttpRequest request = new BasicHttpRequest("GET", "/");
646         final HttpHost host = new HttpHost("somehost", 80);
647         final CredentialsProvider credentialsProvider = CredentialsProviderBuilder.create()
648                 .add(new AuthScope(host, "-", null), "username", "password".toCharArray())
649                 .build();
650 
651         final String challenge = StandardAuthScheme.DIGEST + " Realm=\"-\", " +
652                 "nonce=\"YjYuNGYyYmJhMzUuY2I5ZDhlZDE5M2ZlZDM 1Mjk3NGJkNTIyYjgyNTcwMjQ=\", " +
653                 "opaque=\"98700A3D9CE17065E2246B41035C6609\", qop=\"auth\"";
654         final AuthChallenge authChallenge = parse(challenge);
655         final DigestScheme authscheme = new DigestScheme();
656         authscheme.processChallenge(authChallenge, null);
657         Assertions.assertEquals("-", authscheme.getRealm());
658 
659         Assertions.assertTrue(authscheme.isResponseReady(host, credentialsProvider, null));
660         authscheme.generateAuthResponse(host, request, null);
661     }
662 
663     @Test
664     public void testDigestAuthenticationQopIntOnlyNonRepeatableEntity() throws Exception {
665         final ClassicHttpRequest request = new BasicClassicHttpRequest("Post", "/");
666         request.setEntity(new InputStreamEntity(new ByteArrayInputStream(new byte[] {'a'}), -1, ContentType.DEFAULT_TEXT));
667         final HttpHost host = new HttpHost("somehost", 80);
668         final CredentialsProvider credentialsProvider = CredentialsProviderBuilder.create()
669                 .add(new AuthScope(host, "realm1", null), "username", "password".toCharArray())
670                 .build();
671 
672         final String challenge = StandardAuthScheme.DIGEST + " realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\", " +
673                 "qop=\"auth-int\"";
674         final AuthChallenge authChallenge = parse(challenge);
675         final DigestScheme authscheme = new DigestScheme();
676         authscheme.processChallenge(authChallenge, null);
677 
678         Assertions.assertTrue(authscheme.isResponseReady(host, credentialsProvider, null));
679         Assertions.assertThrows(AuthenticationException.class, () ->
680                 authscheme.generateAuthResponse(host, request, null));
681     }
682 
683     @Test
684     public void testSerialization() throws Exception {
685         final String challenge = StandardAuthScheme.DIGEST + " realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\", " +
686                 "qop=\"auth,auth-int\"";
687         final AuthChallenge authChallenge = parse(challenge);
688         final DigestScheme digestScheme = new DigestScheme();
689         digestScheme.processChallenge(authChallenge, null);
690 
691         final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
692         final ObjectOutputStream out = new ObjectOutputStream(buffer);
693         out.writeObject(digestScheme);
694         out.flush();
695         final byte[] raw = buffer.toByteArray();
696         final ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(raw));
697         final DigestScheme authScheme = (DigestScheme) in.readObject();
698 
699         Assertions.assertEquals(digestScheme.getName(), authScheme.getName());
700         Assertions.assertEquals(digestScheme.getRealm(), authScheme.getRealm());
701         Assertions.assertEquals(digestScheme.isChallengeComplete(), authScheme.isChallengeComplete());
702         Assertions.assertEquals(digestScheme.getA1(), authScheme.getA1());
703         Assertions.assertEquals(digestScheme.getA2(), authScheme.getA2());
704         Assertions.assertEquals(digestScheme.getCnonce(), authScheme.getCnonce());
705     }
706 
707 }