SMTP認証

メモ:  Category:vb

SMTP認証のPLAIN,LOGIN,CRAM-MD5が利用できるよう作成してみました。

SmtpClientを自前で実装する」の続編になります。

SMTP認証については、「SMTP認証」にまとめてみました。

実装例

Dim strParam As String = String.Empty
Dim strRes As String = String.Empty
Try
    Select Case m_intSmtpAuth
        Case SmtpAuthType.PLAIN
            ' PLAIN
            SendCommand("AUTH PLAIN")
            If Not CheckResponse(ReceiveData()) Then
                Return False
            End If
            ' ユーザーおよびパスワードの編集
            strParam = UserID & ControlChars.NullChar & UserID & ControlChars.NullChar & Password
            strParam = Convert.ToBase64String(Encoding.ASCII.GetBytes(strParam))

            SendCommand(strParam)
            If Not CheckResponse(ReceiveData()) Then
                Return False
            End If
        Case SmtpAuthType.LOGIN
            ' LOGIN
            SendCommand("AUTH LOGIN")
            If Not CheckResponse(ReceiveData()) Then
                Return False
            End If

            strParam = Convert.ToBase64String(Encoding.ASCII.GetBytes(UserID))
            SendCommand(strParam)
            If Not CheckResponse(ReceiveData(), strRes) Then
                Return False
            End If

            strParam = Convert.ToBase64String(Encoding.ASCII.GetBytes(Password))
            SendCommand(strParam)
            If Not CheckResponse(ReceiveData(), strRes) Then
                Return False
            End If
        Case SmtpAuthType.CRAM_MD5
            ' CRAM-MD5
            SendCommand("AUTH CRAM-MD5")
            If Not CheckResponse(ReceiveData(), strRes) Then
                Return False
            End If

            Dim objMD5 As HMACMD5
            Dim strChallenge As String
            Dim bytHush As Byte()
            Dim stbBuff As New StringBuilder

            ' タイムスタンプをBase64デコードし、チャレンジコードに対してパスワードを
            ' キーとしてHMAC-MD5ハッシュ値を計算する
            ' タイムスタンプの取得
            strChallenge = strRes.Substring(5)
            ' パスワードをキーにする
            objMD5 = New HMACMD5(Encoding.ASCII.GetBytes(Password))
            bytHush = objMD5.ComputeHash(Convert.FromBase64String(strChallenge))
            ' 16進表記の文字列へ変換
            For i As Integer = 0 To bytHush.Length - 1
                stbBuff.Append(bytHush(i).ToString("x02"))
            Next
            ' ユーザー名と算出した値を連結しBase64でエンコードして返します。
            strParam = Convert.ToBase64String(Encoding.ASCII.GetBytes(UserID & stbBuff.ToString))

            SendCommand(strParam)
            If Not CheckResponse(ReceiveData(), strRes) Then
                Return False
            End If
    End Select
    Return True
Catch ex As Exception
    Throw (ex)
End Try

bluenote by BBB