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    *      http://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.security.spec.InvalidKeySpecException;
24  import javax.crypto.Mac;
25  import javax.crypto.spec.SecretKeySpec;
26  
27  import org.apache.commons.net.util.Base64;
28  
29  
30  /**
31   * A POP3 Cilent class with protocol and authentication extensions support
32   * (RFC2449 and RFC2195).
33   * @see POP3Client
34   * @since 3.0
35   */
36  public class ExtendedPOP3Client extends POP3SClient
37  {
38      /**
39       * The default ExtendedPOP3Client constructor.
40       * Creates a new Extended POP3 Client.
41       * @throws NoSuchAlgorithmException on error
42       */
43      public ExtendedPOP3Client() throws NoSuchAlgorithmException
44      {
45          super();
46      }
47  
48      /***
49       * Authenticate to the POP3 server by sending the AUTH command with the
50       * selected mechanism, using the given username and the given password.
51       * <p>
52       * @param method the {@link AUTH_METHOD} to use
53       * @param username the user name
54       * @param password the password
55       * @return True if successfully completed, false if not.
56       * @exception IOException  If an I/O error occurs while either sending a
57       *      command to the server or receiving a reply from the server.
58       * @exception NoSuchAlgorithmException If the CRAM hash algorithm
59       *      cannot be instantiated by the Java runtime system.
60       * @exception InvalidKeyException If the CRAM hash algorithm
61       *      failed to use the given password.
62       * @exception InvalidKeySpecException If the CRAM hash algorithm
63       *      failed to use the given password.
64       ***/
65      public boolean auth(AUTH_METHOD method,
66                          String username, String password)
67                          throws IOException, NoSuchAlgorithmException,
68                          InvalidKeyException, InvalidKeySpecException
69      {
70          if (sendCommand(POP3Command.AUTH, method.getAuthName())
71          != POP3Reply.OK_INT) {
72              return false;
73          }
74  
75          switch(method) {
76              case PLAIN:
77                  // the server sends an empty response ("+ "), so we don't have to read it.
78                  return sendCommand(
79                      new String(
80                          Base64.encodeBase64(("\000" + username + "\000" + password).getBytes(getCharsetName())),
81                          getCharsetName()) // Java 1.6 can use getCharset()
82                      ) == POP3Reply.OK;
83              case CRAM_MD5:
84                  // get the CRAM challenge
85                  byte[] serverChallenge = Base64.decodeBase64(getReplyString().substring(2).trim());
86                  // get the Mac instance
87                  Mac hmac_md5 = Mac.getInstance("HmacMD5");
88                  hmac_md5.init(new SecretKeySpec(password.getBytes(getCharsetName()), "HmacMD5")); // Java 1.6 can use getCharset()
89                  // compute the result:
90                  // Java 1.6 can use getCharset()
91                  byte[] hmacResult = _convertToHexString(hmac_md5.doFinal(serverChallenge)).getBytes(getCharsetName());
92                  // join the byte arrays to form the reply
93                  byte[] usernameBytes = username.getBytes(getCharsetName()); // Java 1.6 can use getCharset()
94                  byte[] toEncode = new byte[usernameBytes.length + 1 /* the space */ + hmacResult.length];
95                  System.arraycopy(usernameBytes, 0, toEncode, 0, usernameBytes.length);
96                  toEncode[usernameBytes.length] = ' ';
97                  System.arraycopy(hmacResult, 0, toEncode, usernameBytes.length + 1, hmacResult.length);
98                  // send the reply and read the server code:
99                  return sendCommand(Base64.encodeBase64StringUnChunked(toEncode)) == POP3Reply.OK;
100             default:
101                 return false;
102         }
103     }
104 
105     /**
106      * Converts the given byte array to a String containing the hex values of the bytes.
107      * For example, the byte 'A' will be converted to '41', because this is the ASCII code
108      * (and the byte value) of the capital letter 'A'.
109      * @param a The byte array to convert.
110      * @return The resulting String of hex codes.
111      */
112     private String _convertToHexString(byte[] a)
113     {
114         StringBuilder result = new StringBuilder(a.length*2);
115         for (byte element : a)
116         {
117             if ( (element & 0x0FF) <= 15 ) {
118                 result.append("0");
119             }
120             result.append(Integer.toHexString(element & 0x0FF));
121         }
122         return result.toString();
123     }
124 
125     /**
126      * The enumeration of currently-supported authentication methods.
127      */
128     public static enum AUTH_METHOD
129     {
130         /** The standarised (RFC4616) PLAIN method, which sends the password unencrypted (insecure). */
131         PLAIN("PLAIN"),
132 
133         /** The standarised (RFC2195) CRAM-MD5 method, which doesn't send the password (secure). */
134         CRAM_MD5("CRAM-MD5");
135 
136         private final String methodName;
137 
138         AUTH_METHOD(String methodName){
139             this.methodName = methodName;
140         }
141         /**
142          * Gets the name of the given authentication method suitable for the server.
143          * @return The name of the given authentication method suitable for the server.
144          */
145         public final String getAuthName()
146         {
147             return this.methodName;
148         }
149     }
150 }