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
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                  byte[] hmacResult = _convertToHexString(hmac_md5.doFinal(serverChallenge)).getBytes(getCharsetName()); // Java 1.6 can use getCharset()
91                  // join the byte arrays to form the reply
92                  byte[] usernameBytes = username.getBytes(getCharsetName()); // Java 1.6 can use getCharset()
93                  byte[] toEncode = new byte[usernameBytes.length + 1 /* the space */ + hmacResult.length];
94                  System.arraycopy(usernameBytes, 0, toEncode, 0, usernameBytes.length);
95                  toEncode[usernameBytes.length] = ' ';
96                  System.arraycopy(hmacResult, 0, toEncode, usernameBytes.length + 1, hmacResult.length);
97                  // send the reply and read the server code:
98                  return sendCommand(Base64.encodeBase64StringUnChunked(toEncode)) == POP3Reply.OK;
99              default:
100                 return false;
101         }
102     }
103 
104     /**
105      * Converts the given byte array to a String containing the hex values of the bytes.
106      * For example, the byte 'A' will be converted to '41', because this is the ASCII code
107      * (and the byte value) of the capital letter 'A'.
108      * @param a The byte array to convert.
109      * @return The resulting String of hex codes.
110      */
111     private String _convertToHexString(byte[] a)
112     {
113         StringBuilder result = new StringBuilder(a.length*2);
114         for (byte element : a)
115         {
116             if ( (element & 0x0FF) <= 15 ) {
117                 result.append("0");
118             }
119             result.append(Integer.toHexString(element & 0x0FF));
120         }
121         return result.toString();
122     }
123 
124     /**
125      * The enumeration of currently-supported authentication methods.
126      */
127     public static enum AUTH_METHOD
128     {
129         /** The standarised (RFC4616) PLAIN method, which sends the password unencrypted (insecure). */
130         PLAIN("PLAIN"),
131 
132         /** The standarised (RFC2195) CRAM-MD5 method, which doesn't send the password (secure). */
133         CRAM_MD5("CRAM-MD5");
134 
135         private final String methodName;
136 
137         AUTH_METHOD(String methodName){
138             this.methodName = methodName;
139         }
140         /**
141          * Gets the name of the given authentication method suitable for the server.
142          * @return The name of the given authentication method suitable for the server.
143          */
144         public final String getAuthName()
145         {
146             return this.methodName;
147         }
148     }
149 }