spring邮件发送需要ssl证书

Easter79
• 阅读 806

需要将下列代码编译运行:

  1 import java.io.BufferedReader;
  2 import java.io.File;
  3 import java.io.FileInputStream;
  4 import java.io.FileOutputStream;
  5 import java.io.InputStream;
  6 import java.io.InputStreamReader;
  7 import java.io.OutputStream;
  8 import java.security.KeyStore;
  9 import java.security.MessageDigest;
 10 import java.security.cert.CertificateException;
 11 import java.security.cert.X509Certificate;
 12 
 13 import javax.net.ssl.SSLContext;
 14 import javax.net.ssl.SSLException;
 15 import javax.net.ssl.SSLSocket;
 16 import javax.net.ssl.SSLSocketFactory;
 17 import javax.net.ssl.TrustManager;
 18 import javax.net.ssl.TrustManagerFactory;
 19 import javax.net.ssl.X509TrustManager;
 20 
 21 public class InstallCert {
 22 
 23     public static void main(String[] args) throws Exception {
 24         String host;
 25         int port;
 26         char[] passphrase;
 27         if ((args.length == 1) || (args.length == 2)) {
 28             String[] c = args[0].split(":");
 29             host = c[0];
 30             port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
 31             String p = (args.length == 1) ? "changeit" : args[1];
 32             passphrase = p.toCharArray();
 33         } else {
 34             System.out
 35                     .println("Usage: java InstallCert <host>[:port] [passphrase]");
 36             return;
 37         }
 38 
 39         File file = new File("jssecacerts");
 40         if (file.isFile() == false) {
 41             char SEP = File.separatorChar;
 42             File dir = new File(System.getProperty("java.home") + SEP + "lib"
 43                     + SEP + "security");
 44             file = new File(dir, "jssecacerts");
 45             if (file.isFile() == false) {
 46                 file = new File(dir, "cacerts");
 47             }
 48         }
 49         System.out.println("Loading KeyStore " + file + "...");
 50         InputStream in = new FileInputStream(file);
 51         KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
 52         ks.load(in, passphrase);
 53         in.close();
 54 
 55         SSLContext context = SSLContext.getInstance("TLS");
 56         TrustManagerFactory tmf = TrustManagerFactory
 57                 .getInstance(TrustManagerFactory.getDefaultAlgorithm());
 58         tmf.init(ks);
 59         X509TrustManager defaultTrustManager = (X509TrustManager) tmf
 60                 .getTrustManagers()[0];
 61         SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
 62         context.init(null, new TrustManager[] { tm }, null);
 63         SSLSocketFactory factory = context.getSocketFactory();
 64 
 65         System.out
 66                 .println("Opening connection to " + host + ":" + port + "...");
 67         SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
 68         socket.setSoTimeout(10000);
 69         try {
 70             System.out.println("Starting SSL handshake...");
 71             socket.startHandshake();
 72             socket.close();
 73             System.out.println();
 74             System.out.println("No errors, certificate is already trusted");
 75         } catch (SSLException e) {
 76             System.out.println();
 77             e.printStackTrace(System.out);
 78         }
 79 
 80         X509Certificate[] chain = tm.chain;
 81         if (chain == null) {
 82             System.out.println("Could not obtain server certificate chain");
 83             return;
 84         }
 85 
 86         BufferedReader reader = new BufferedReader(new InputStreamReader(
 87                 System.in));
 88 
 89         System.out.println();
 90         System.out.println("Server sent " + chain.length + " certificate(s):");
 91         System.out.println();
 92         MessageDigest sha1 = MessageDigest.getInstance("SHA1");
 93         MessageDigest md5 = MessageDigest.getInstance("MD5");
 94         for (int i = 0; i < chain.length; i++) {
 95             X509Certificate cert = chain[i];
 96             System.out.println(" " + (i + 1) + " Subject "
 97                     + cert.getSubjectDN());
 98             System.out.println("   Issuer  " + cert.getIssuerDN());
 99             sha1.update(cert.getEncoded());
100             System.out.println("   sha1    " + toHexString(sha1.digest()));
101             md5.update(cert.getEncoded());
102             System.out.println("   md5     " + toHexString(md5.digest()));
103             System.out.println();
104         }
105 
106         System.out
107                 .println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");
108         String line = reader.readLine().trim();
109         int k;
110         try {
111             k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
112         } catch (NumberFormatException e) {
113             System.out.println("KeyStore not changed");
114             return;
115         }
116 
117         X509Certificate cert = chain[k];
118         String alias = host + "-" + (k + 1);
119         ks.setCertificateEntry(alias, cert);
120 
121         OutputStream out = new FileOutputStream("jssecacerts");
122         ks.store(out, passphrase);
123         out.close();
124 
125         System.out.println();
126         System.out.println(cert);
127         System.out.println();
128         System.out
129                 .println("Added certificate to keystore 'jssecacerts' using alias '"
130                         + alias + "'");
131     }
132 
133     private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();
134 
135     private static String toHexString(byte[] bytes) {
136         StringBuilder sb = new StringBuilder(bytes.length * 3);
137         for (int b : bytes) {
138             b &= 0xff;
139             sb.append(HEXDIGITS[b >> 4]);
140             sb.append(HEXDIGITS[b & 15]);
141             sb.append(' ');
142         }
143         return sb.toString();
144     }
145 
146     private static class SavingTrustManager implements X509TrustManager {
147 
148         private final X509TrustManager tm;
149         private X509Certificate[] chain;
150 
151         SavingTrustManager(X509TrustManager tm) {
152             this.tm = tm;
153         }
154 
155         @Override
156         public X509Certificate[] getAcceptedIssuers() {
157             return new X509Certificate[0];
158             //throw new UnsupportedOperationException();  
159         }
160 
161         public void checkClientTrusted(X509Certificate[] chain, String authType)
162                 throws CertificateException {
163             throw new UnsupportedOperationException();
164         }
165 
166         public void checkServerTrusted(X509Certificate[] chain, String authType)
167                 throws CertificateException {
168             this.chain = chain;
169             tm.checkServerTrusted(chain, authType);
170         }
171     }
172 
173 }

javac InstallCert.java

java InstallCert www.***.com:xx

                                网址       端口

xml配置:

<!-- 发送邮件 -->
    <bean id="javaMailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="${mail.host}"/>
        <property name="javaMailProperties">
            <props>
                <prop key="mail.smtp.auth">${mail.smtp.auth}</prop>
                <prop key="mail.smtp.timeout">${mail.smtp.timeout}</prop>
                <prop key="mail.smtp.starttls.enable">${mail.smtp.starttls.enable}</prop>
                <prop key="mail.smtp.socketFactory.port">${mail.smtp.socketFactory.port}</prop>
                <prop key="mail.smtp.socketFactory.class">${mail.smtp.socketFactory.class}</prop>
                <prop key="mail.smtp.socketFactory.fallback">${mail.smtp.socketFactory.fallback}</prop>
                <!--<prop key="javax.net.ssl.trustStore">${javax.net.ssl.trustStore}</prop>-->
            </props>
        </property>
        <property name="username" value="${mail.username}"/>
        <property name="password" value="${mail.password}"/>
        <property name="port" value="${mail.port}"/>
        <property name="protocol" value="${mail.protocol}"/>
        <property name="defaultEncoding" value="UTF-8"/>
    </bean>

然后将生成的jssecacerts文件放在%JAVA_HOME%\jre\lib\security目录下,重启web服务即可

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
5个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Wesley13 Wesley13
3年前
Java获得今日零时零分零秒的时间(Date型)
publicDatezeroTime()throwsParseException{    DatetimenewDate();    SimpleDateFormatsimpnewSimpleDateFormat("yyyyMMdd00:00:00");    SimpleDateFormatsimp2newS
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
11个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这
Easter79
Easter79
Lv1
今生可爱与温柔,每一样都不能少。
文章
2.8k
粉丝
5
获赞
1.2k