javax.mail - 强制 IMAP 使用 TLS1.2+ - "Received fatal alert: protocol_version"

javax.mail - force IMAP to use TLS1.2+ - "Received fatal alert: protocol_version"

我的应用程序无法通过 IMAP 阅读邮件。

应用程序读取多个 imap 帐户。应用程序可以连接到所有服务器,但需要使用 TLS1.2 或 TLS1.3 的服务器除外。

我有这个代码:

System.out.println("SSLContext getProtocols(): " + String.join(" ", SSLContext.getDefault().getSupportedSSLParameters().getProtocols()));

Properties props = new Properties();
props.put("mail.imap.auth", "true");        
props.put("mail.imap.ssl.enable", "true");          
props.put("mail.imap.starttls.enable", "false");
props.put("jdk.tls.client.protocols", "TLSv1.2 TLSv1.3");
props.put("mail.imap.ssl.protocols", "TLSv1.2 TLSv1.3");

Session session = Session.getDefaultInstance(props);
Store store = session.getStore("imaps");
store.connect(mailConf.getImapServer(), mailConf.getImapServerPort(), mailConf.getImapUser(), mailConf.getImapPass());
Folder inbox = store.getFolder(mailConf.getImapMailFolder());
inbox.open(Folder.READ_ONLY);

和 运行 应用使用:

java -Djdk.tls.client.protocols="TLSv1.2,TLSv1.3" \
-Ddeployment.security.SSLv2Hello=false \
-Ddeployment.security.SSLv3=false \
-Ddeployment.security.TLSv1=false \
-Ddeployment.security.TLSv1.1=false \
-Ddeployment.security.TLSv1.2=true \
-Ddeployment.security.TLSv1.3=true \
-jar myApp.jar

对于需要 TLS1.2+ 的 IMAP 服务器,我看到了这个输出:

SSLContext getProtocols(): TLSv1.3 TLSv1.2 TLSv1.1 TLSv1 SSLv3 SSLv2Hello
Jan 29 11:41:19 myhost myapp[22101]: 2020-01-29 11:41:19 ERROR e.v.MyAppApplication$$EnhancerBySpringCGLIB$bb5321c:68 - Imap readMail() error: Received fatal alert: protocol_version

我正在使用 Java 11:

# java --version
openjdk 11.0.4 2019-07-16
OpenJDK Runtime Environment (build 11.0.4+11-post-Debian-1deb10u1)
OpenJDK 64-Bit Server VM (build 11.0.4+11-post-Debian-1deb10u1, mixed mode, sharing)

我做的不好吗?如何为 imap 连接强制使用 TLS1.2+?

谢谢。

您可以从 JavaMail 属性中删除 jdk.tls.client.protocols 属性,因为 JavaMail 绝对不会解释 属性。在命令行上将其设置为系统 属性 很好,因为 JDK 会解释它。

我没有看到任何关于 deployment.security.* 属性的文档,但我所看到的表明它们仅在您使用 Java 插件或 Java WebStart,你不是。所以你可能不需要设置这些属性。

您收到的错误消息表明您的应用正在使用 Spring,尽管我在您发布的 Java 邮件代码中没有看到它。也许 Spring 以某种方式插入套接字设置代码并控制安全配置?

您可以尝试独立的 JavaMail msgshow.java 示例程序来证明您可以使用 JDK 版本建立连接而无需特殊的安全配置。如果失败,问题出在 JDK 安全配置中。

我找到了解决方案:将 Spring 引导从 2.1.1.RELEASE 升级到 2.2.4.RELEASE.

对于 SMTP: mail.smtps.ssl.protocols=TLSv1.2

对于 IMAP: mail.imaps.ssl.protocols=TLSv1.2

对于 POP3: 邮件.pop3s.ssl.protocols=TLSv1.2