public boolean auth()

in src/main/java/org/apache/commons/net/smtp/AuthenticatingSMTPClient.java [158:198]


    public boolean auth(final AuthenticatingSMTPClient.AUTH_METHOD method, final String username, final String password)
            throws IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException {
        if (!SMTPReply.isPositiveIntermediate(sendCommand(SMTPCommand.AUTH, AUTH_METHOD.getAuthName(method)))) {
            return false;
        }

        if (method.equals(AUTH_METHOD.PLAIN)) {
            // the server sends an empty response ("334 "), so we don't have to read it.
            return SMTPReply
                    .isPositiveCompletion(sendCommand(Base64.encodeBase64StringUnChunked(("\000" + username + "\000" + password).getBytes(getCharset()))));
        }
        if (method.equals(AUTH_METHOD.CRAM_MD5)) {
            // get the CRAM challenge
            final byte[] serverChallenge = Base64.decodeBase64(getReplyString().substring(4).trim());
            // get the Mac instance
            final Mac hmacMd5 = Mac.getInstance("HmacMD5");
            hmacMd5.init(new SecretKeySpec(password.getBytes(getCharset()), "HmacMD5"));
            // compute the result:
            final byte[] hmacResult = convertToHexString(hmacMd5.doFinal(serverChallenge)).getBytes(getCharset());
            // join the byte arrays to form the reply
            final byte[] usernameBytes = username.getBytes(getCharset());
            final byte[] toEncode = new byte[usernameBytes.length + 1 /* the space */ + hmacResult.length];
            System.arraycopy(usernameBytes, 0, toEncode, 0, usernameBytes.length);
            toEncode[usernameBytes.length] = ' ';
            System.arraycopy(hmacResult, 0, toEncode, usernameBytes.length + 1, hmacResult.length);
            // send the reply and read the server code:
            return SMTPReply.isPositiveCompletion(sendCommand(Base64.encodeBase64StringUnChunked(toEncode)));
        }
        if (method.equals(AUTH_METHOD.LOGIN)) {
            // the server sends fixed responses (base64("Username") and
            // base64("Password")), so we don't have to read them.
            if (!SMTPReply.isPositiveIntermediate(sendCommand(Base64.encodeBase64StringUnChunked(username.getBytes(getCharset()))))) {
                return false;
            }
            return SMTPReply.isPositiveCompletion(sendCommand(Base64.encodeBase64StringUnChunked(password.getBytes(getCharset()))));
        }
        if (method.equals(AUTH_METHOD.XOAUTH) || method.equals(AUTH_METHOD.XOAUTH2)) {
            return SMTPReply.isPositiveIntermediate(sendCommand(Base64.encodeBase64StringUnChunked(username.getBytes(getCharset()))));
        }
        return false; // safety check
    }