Reputation: 1
I would be obliged if someone could provide me with sample code in groovy or java that will clearly demonstrate how I can use a pks12 certificate file to make a https call to a given url and how to get and interpret the response code given. Thanks in advance for any contributions
For purpose of this question lets assume that the pfx file is called TEST.pfx and the pwd is Alpha123
So far I have assembled this code. The 1st part I use to load the certificate and look at its contents. In the 2nd part I want to use the loaded certificate to access the url provided, but nothing happens.
package myGroovyProject
import java.security.KeyStore
import java.security.Principal
import java.security.cert.X509Certificate
import javax.net.ssl.HttpsURLConnection
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManagerFactory
import java.io.FileInputStream;
import java.security.Key;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
//1st part
//========
KeyStore myKeyStore = KeyStore.getInstance("pkcs12");
myKeyStore.load(new FileInputStream("TEST.pfx"), "Alpha123".toCharArray());
Enumeration<String> e = myKeyStore.aliases();
while (e.hasMoreElements())
{
String alias = e.nextElement();
X509Certificate c = (X509Certificate) myKeyStore.getCertificate(alias);
Principal subject = c.getSubjectDN();
System.out.println(c);
String[] subjectArray = subject.toString().split(",");
for (String s : subjectArray)
{
String[] str = s.trim().split("=");
String key = str[0];
String value = str[1];
System.out.println("Details Are : " + key + " - " + value);
}
}
//2nd part
//========
def TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(myKeyStore);
def SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
def HttpsURLConnection connection = (HttpsURLConnection) new URL("https://certauth.idrix.fr").openConnection();
connection.setSSLSocketFactory(sslContext.getSocketFactory());
System.out.println("==== Finished ====")
Upvotes: 0
Views: 801