(Click to open topic with navigation)
At times it is desirable to load and use self-signed certificates, certificates generated from a single trusted certificate authority (CA), or even simple server certificates. It may also be necessary to use client certificates to communicate with external resources. To ease this process, the SSL Service may be utilized. This service provides methods to load client and server certificates from the filesystem. Methods are also present to aid in creating connections which automatically trust all server certificates and connections.
Several points should be noted when using the SSL Service:
Example
To create a socket to a server that requires a client certificate, the following code may be used.
package example import com.adaptc.mws.plugins.* class SSLConnectionPlugin extends AbstractPlugin { ISslService sslService public void poll() { // This certificate is not encrypted and will be the only certificate presented to the // connecting end of the socket. // This file will be loaded from MWS_HOME + mws.certificates.location + my-cert.pem. String clientCert = "my-cert.pem" def socketFactory = sslService.getSocketFactory(clientCert, null, null) def socket = socketFactory.createSocket("hostname.com", 443) // Write and read from the socket as desired… } }
To create a HTTPS URL connection to a server that has a self-signed certificate, the following code may be used. Note that this is very typical of client libraries – they have a method to set the SSL socket factory used when creating connections.
package example import com.adaptc.mws.plugins.* class SSLConnectionPlugin extends AbstractPlugin { ISslService sslService public void poll() { // This certificate represents either the server public certificate or the CA's certificate. // Since the path is absolute it will not be loaded from the MWS_HOME directory. String serverCert = "/etc/ssl/certs/server-cert.pem" def socketFactory = sslService.getSocketFactory(serverCert) // Open connection to URL HttpsURLConnection conn = "https://hostname.com:443/test".toURL().openConnection() conn.setSSLSocketFactory(socketFactory) // Retrieve page content and do with as desired… def pageContent = conn.getInputStream().text } }
Related Topics