0

尝试使用证书通过 TLS 连接邮件服务器,但即使我输入了错误的证书,连接也成功。我添加了这些属性:

 javaMailProperties.put("mail.smtp.auth",true);
 javaMailProperties.setProperty("mail.smtp.timeout", "8500");
 javaMailProperties.setProperty("mail.smtp.starttls.enable", "true");
 javaMailProperties.put("mail.smtp.socketFactory", sslSocketFactory);
 javaMailProperties.put("mail.smtp.socketFactory.fallback", true);

我创建套接字工厂的方式:(我使用来自服务器的公共证书创建了新的密钥库。并创建了 socketfctory)

private MailSSLSocketFactory getMailSSLSocketFactory(String certificate){
        try {
            logger.debug("Start, getting mail ssl socket factory");
            KeyStore keyStore = getKeyStore(certificate);
            KeyManager[] keyManagers = getKeyManagers(keyStore);
            TrustManager[] trustManagers = getTrustManagers(keyStore);

            MailSSLSocketFactory sslSocketFactory = getMailSSLSocketFactory(keyManagers, trustManagers);
            logger.debug("End, getting mail ssl socket factory");
            return sslSocketFactory;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private KeyStore getKeyStore(String certificate) throws CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        InputStream certificateStream = new ByteArrayInputStream(certificate.getBytes(StandardCharsets.UTF_8));
        X509Certificate x509Certificate = (X509Certificate) certificateFactory.generateCertificate(certificateStream);

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        keyStore.setCertificateEntry("smtp.certificate", x509Certificate);
        return keyStore;
    }

    private KeyManager[] getKeyManagers(KeyStore keyStore) throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, null);
        return keyManagerFactory.getKeyManagers();
    }

    private TrustManager[] getTrustManagers(KeyStore keyStore) throws NoSuchAlgorithmException, KeyStoreException {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);
        return trustManagerFactory.getTrustManagers();
    }

    private MailSSLSocketFactory getMailSSLSocketFactory(KeyManager[] keyManagers, TrustManager[] trustManagers) throws GeneralSecurityException {
        MailSSLSocketFactory sslSocketFactory = new MailSSLSocketFactory();
        sslSocketFactory.setKeyManagers(keyManagers);
        sslSocketFactory.setTrustManagers(trustManagers);
        return sslSocketFactory;
    }

我错过了什么或错了什么?

4

0 回答 0