【Java】JavaでEmail ~ SMTP認証 / DIGEST-MD5 ~

■ はじめに

JavaMail を使って
SMTP-AUTH の方式「DIGEST-MD5」でメール送信する方法を考える

■ 用語

SASL(サスル)

* SASL : Simple Authentication and Security Layer
* 認証や暗号化などのセキュリティに関する処理を行う層

CRAM-MD5

* CRAM : Challenge-Response Authentication Mechanism
* MD5形式でハッシュ化した認証情報を送って認証を行う

DIGEST-MD5

* CRAM-MD5の弱点をカバーしてセキュリティをさらに向上させた形式

具体的には

* CRAM-MD5の欠点である辞書攻撃や総当たり攻撃に対する対処
* Realm(ログイン領域)や
 URLの指定(これらはHTTPなどへの応用を想定している)や
   HMAC(Hash-based Message Authentication Code)
 による暗号化をサポート
 => HMAC に関する詳細は、以下の関連記事を参照のこと。

https://dk521123.hatenablog.com/entry/2022/10/05/095506

Realm (レルム)

* 日本語で、「領域、範囲、部門」
 * SMTP認証のドメイン名

参考文献
http://www.atmarkit.co.jp/ait/articles/0105/18/news002.html
http://www.wdic.org/w/WDIC/SASL
http://oxynotes.com/?p=4428

■ JavaMailのサポート範囲

DIGEST-MD5

* DIGEST-MD5はサポート内

https://javamail.java.net/nonav/docs/api/com/sun/mail/smtp/package-summary.html

より抜粋

It can optionally use SMTP Authentication (RFC 2554)
 using the LOGIN, PLAIN, DIGEST-MD5, << ★ DIGEST-MD5はサポート ★
 and NTLM mechanisms (RFC 2595 and RFC 2831).

When using DIGEST-MD5 authentication, you'll also need to supply an appropriate realm;
 your mail server administrator can supply this information.
 You can set this
 using the mail.smtp.sasl.realm property, << ★ "mail.smtp.sasl.realm"を指定 ★
 or the setSASLRealm method on SMTPTransport. << ★ setSASLRealm()を指定 ★

CRAM-MD5

* CRAM-MD5は???
* 以下の参考文献の情報によると、GNU JavaMail(https://www.gnu.org/software/classpathx/javamail/javamail.html)
   はサポートしているらしい

http://it-mn-us.blogspot.jp/2009/02/javamail-mechanism.html
http://qa.atmarkit.co.jp/q/7147
http://frmmpgit.blog.fc2.com/blog-entry-129.html

■ ソース抜粋

Properties props = new Properties();
props.put("mail.smtp.auth", "true");
Authenticator authenticator = new javax.mail.Authenticator() {
  protected PasswordAuthentication getPasswordAuthentication() {
     return new PasswordAuthentication("SMTP_USERNAME", "SMTP_PASSWORD");
  }
};
Session session = Session.getInstance(props, authenticator);
// ★ここ★(setSASLRealm()でもできるらしいが試していない)
props.put("mail.smtp.sasl.realm", "REALM_VALUE");

関連記事

ハッシュ / Hash
https://dk521123.hatenablog.com/entry/2022/09/14/000000
メッセージ認証コード ~ MAC / HMAC ~
https://dk521123.hatenablog.com/entry/2022/10/05/095506