View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      https://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.commons.net.pop3;
19  
20  import java.io.IOException;
21  import java.security.InvalidKeyException;
22  import java.security.NoSuchAlgorithmException;
23  import java.util.Base64;
24  
25  import javax.crypto.Mac;
26  import javax.crypto.spec.SecretKeySpec;
27  
28  /**
29   * A POP3 Client class with protocol and authentication extensions support (RFC2449 and RFC2195).
30   *
31   * @see POP3Client
32   * @since 3.0
33   */
34  public class ExtendedPOP3Client extends POP3SClient {
35  
36      /**
37       * The enumeration of currently-supported authentication methods.
38       */
39      public enum AUTH_METHOD {
40  
41          /** The standardized (RFC4616) PLAIN method, which sends the password unencrypted (insecure). */
42          PLAIN("PLAIN"),
43  
44          /** The standardized (RFC2195) CRAM-MD5 method, which doesn't send the password (secure). */
45          CRAM_MD5("CRAM-MD5");
46  
47          private final String methodName;
48  
49          AUTH_METHOD(final String methodName) {
50              this.methodName = methodName;
51          }
52  
53          /**
54           * Gets the name of the given authentication method suitable for the server.
55           *
56           * @return The name of the given authentication method suitable for the server.
57           */
58          public String getAuthName() {
59              return methodName;
60          }
61      }
62  
63      /** {@link Mac} algorithm. */
64      private static final String MAC_ALGORITHM = "HmacMD5";
65  
66      /**
67       * The default ExtendedPOP3Client constructor. Creates a new Extended POP3 Client.
68       *
69       * @throws NoSuchAlgorithmException Never thrown here.
70       */
71      public ExtendedPOP3Client() throws NoSuchAlgorithmException {
72      }
73  
74      /**
75       * Authenticate to the POP3 server by sending the AUTH command with the selected mechanism, using the given user and the given password.
76       *
77       * @param method   the {@link AUTH_METHOD} to use
78       * @param user the user name
79       * @param password the password
80       * @return True if successfully completed, false if not.
81       * @throws IOException              If an I/O error occurs while either sending a command to the server or receiving a reply from the server.
82       * @throws NoSuchAlgorithmException If the CRAM hash algorithm cannot be instantiated by the Java runtime system.
83       * @throws InvalidKeyException      If the CRAM hash algorithm failed to use the given password.
84       */
85      public boolean auth(final AUTH_METHOD method, final String user, final String password)
86              throws IOException, NoSuchAlgorithmException, InvalidKeyException {
87          if (sendCommand(POP3Command.AUTH, method.getAuthName()) != POP3Reply.OK_INT) {
88              return false;
89          }
90  
91          switch (method) {
92          case PLAIN:
93              // the server sends an empty response ("+ "), so we don't have to read it.
94              return sendCommand(
95                      new String(Base64.getEncoder().encode(("\000" + user + "\000" + password).getBytes(getCharset())), getCharset())) == POP3Reply.OK;
96          case CRAM_MD5:
97              // get the CRAM challenge
98              final byte[] serverChallenge = Base64.getDecoder().decode(getReplyString().substring(2).trim());
99              // get the Mac instance
100             final Mac hmacMd5 = Mac.getInstance(MAC_ALGORITHM);
101             hmacMd5.init(new SecretKeySpec(password.getBytes(getCharset()), MAC_ALGORITHM));
102             // compute the result:
103             final byte[] hmacResult = convertToHexString(hmacMd5.doFinal(serverChallenge)).getBytes(getCharset());
104             // join the byte arrays to form the reply
105             final byte[] userNameBytes = user.getBytes(getCharset());
106             final byte[] toEncode = new byte[userNameBytes.length + 1 /* the space */ + hmacResult.length];
107             System.arraycopy(userNameBytes, 0, toEncode, 0, userNameBytes.length);
108             toEncode[userNameBytes.length] = ' ';
109             System.arraycopy(hmacResult, 0, toEncode, userNameBytes.length + 1, hmacResult.length);
110             // send the reply and read the server code:
111             return sendCommand(Base64.getEncoder().encodeToString(toEncode)) == POP3Reply.OK;
112         default:
113             return false;
114         }
115     }
116 
117     /**
118      * Converts the given byte array to a String containing the hexadecimal values of the bytes. For example, the byte 'A' will be converted to '41', because
119      * this is the ASCII code (and the byte value) of the capital letter 'A'.
120      *
121      * @param a The byte array to convert.
122      * @return The resulting String of hexadecimal codes.
123      */
124     private String convertToHexString(final byte[] a) {
125         final StringBuilder result = new StringBuilder(a.length * 2);
126         for (final byte element : a) {
127             if ((element & 0x0FF) <= 15) {
128                 result.append("0");
129             }
130             result.append(Integer.toHexString(element & 0x0FF));
131         }
132         return result.toString();
133     }
134 }