Java read certificate file

How to read information from SSL certificate file [duplicate]

enter image description here

I’m newbie to SSL certificate, i need to read validation date and expiration date from a local .crt file not a URL as shown in the following print screen: So is there a JAVA Api that helps to do it.

2 Answers 2

You can get the certificate to and from dates like so:

CertificateFactory fac = CertificateFactory.getInstance("X509"); FileInputStream is = new FileInputStream("\\path\\to\\file\\cert.crt"); X509Certificate cert = (X509Certificate) fac.generateCertificate(is); System.out.println("From: " + cert.getNotBefore()); System.out.println("Until: " + cert.getNotAfter()); 

It seems you can create a certificate from an input stream using a CertificateFactory

FileInputStream fis = new FileInputStream(filename); CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate cert = cf.generateCertificate(fis); 

Then you can query information from the specific certificate type, eg X509Certificate.

Linked

Hot Network Questions

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43548

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

How can I read the content of a .pfx file in Java?

I have file.pfx file and also have a private key. How can I read the certificate in file.pfx in Java? I have used this code:

import java.security.*; import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.security.cert.CertificateException; import javax.crypto.SecretKey; import javax.security.auth.callback.*; //These packages I have used. public String readFile(String fn) < String thisLine, ret = ""; KeyStore ks = KeyStore.getInstance("pkcs12", "SunJSSE"); ks.load(new FileInputStream(fn),"password".toCharArray()); try < Key key = ks.getKey("1", "password".toCharArray()); Certificate[] cc = ks.getCertificateChain("1"); X509Certificate certificate1 = (X509Certificate) cc[0];//Here it throws java.lang.NullPointerException ret += certificate1.getNotAfter(); ret += certificate1.getNotBefore(); >catch(Exception e) < ret = "Cannot load, exception!"; >return ret; > 

What does «line by line» mean? Are you wanting to read certificates from the PFX file? What have you tried so far?

Читайте также:  Python разработчиком что делает

In future, please edit your question to include that information. It’s useless and unreadable as a comment.

Thank you for your suggestion. It shows worning «X509Certificate» can not find symbol. I have import tha pachage import java.security.*;

java.security.cert.X509Certificate is a part of the core Java libraries. If you are programming in an IDE, this should have been imported automatically.

3 Answers 3

Try This Code for Reading .pfx file:-

 public void checkExpire() < try < KeyManagerFactory kmf = javax.net.ssl.KeyManagerFactory.getInstance("SunX509"); KeyStore keystore = KeyStore.getInstance("PKCS12"); char[] password= "yourfilepassword".toCharArray(); keystore.load(new FileInputStream("filepath\filename.pfx"),password); //keystore.load(new FileInputStream(certificate), password); kmf.init(keystore, psswd); Enumerationaliases = keystore.aliases(); while(aliases.hasMoreElements()) < String alias = aliases.nextElement(); if(keystore.getCertificate(alias).getType().equals("X.509"))< Date expDate = ((X509Certificate) keystore.getCertificate(alias)).getNotAfter(); Date fromDate= ((X509Certificate) keystore.getCertificate(alias)).getNotBefore(); System.out.println("Expiray Date:-"+expDate ); System.out.println("From Date:-"+fromDate); >> > catch (Exception e) < e.printStackTrace(); >> 

You are getting an exception because your keystore (i.e. the PKCS #12 file) does not contain a certificate chain with the alias you have provided.

Key key = ks.getKey("1", "shalimar1234".toCharArray()); Certificate[] cc = ks.getCertificateChain("1"); // this is returning null 

It’s quite plausible your key object is null too, but you don’t appear to use the object at all.

To understand what aliases are available in your file, trying looking at the strings returned from KeyStore.aliases() .

Thanks it works. I use alises. I use the code like: String alias = ks.aliases().nextElement(); Key key = ks.getKey(alias, «shalimar1234».toCharArray()); Certificate[] cc = ks.getCertificateChain(alias); Then it works fine. Can you please tell me how can I read the whole content of the certificate.

@Banshi It sounds like we’ve solved this particular problem. If you have further problems, please try and research a solution yourself. If you cannot find one, then please post a new question.

ok. Thanks. I am also searching for these problem. Actually I am fresher in java. I am PHP developer and iPhone developer. I have a recent project in php which have a requirement that there will a .pfx file in a removable drive and if the file exist in the removable drive the login panel will open. For these reason I have to use applet I have solve these problem with a file.txt file but I never work on file.pfx file system. That is why I post these question. And you accompany me for a long time. If I have to post a question for every query these will be a laborious task. Thanks a lot. lol.:)

Читайте также:  Python split for lists

Here’s a link to a forum question on the subject of opening and reading a .PFX file using Java code.

To summarize what’s in the link, you should be able to open the Key-store as you would with a normal JKS, but with a slight difference, pass the Key-store type as pcks12 and the provider as SunJSSE .

try (FileInputStream stream = new FileInputStream("C:/store.pfx")) < KeyStore store = KeyStore.getInstance("pkcs12", "SunJSSE"); store.load(stream, "password".toCharArray()); Enumerationaliases = store.aliases(); while (aliases.hasMoreElements()) < System.err.println(aliases.nextElement()); >X509Certificate certificate = (X509Certificate)store.getCertificate("alias"); System.err.println(certificate.getNotAfter()); System.err.println(certificate.getNotBefore()); System.err.println(certificate.toString()); > 

Another helpful note is that you might wanna consider using and referring to the BouncyCastle Provider, it is the most complete implementation out there in my humble opinion.

Источник

How to load SSL Certificate in Java

I am creating a Java program to get information from a server but I have to perform a ssl handshake with the server from the Java program. I have myfilercert.cer file certificate for authentication purpose but I have no idea how I can load that certificate in java so that the java program can perform ‘handshake’ with the server where I want to get information from. Where to begin?

2 Answers 2

What you need is the java keystore. The keystore is a repository of security certificates used in SSL encryption. You can read here about the Server Authentication During SSL Handshake. This is a keystore tutorial.

As an alternative to keytool, i would suggest a tool with a Graphical User Interface called Portecle. You can use it to browse the contents of your .cer file and see what’s in it.

It can be useful to know about the various certificate encodings. Also read about the X.509 standard.

Читайте также:  Ieee 754 converter python

This is an article on java keytool essentials (which is the oracle tool that works with the java keystore).

You can google and find a lot of resources that instruct you how to generate. I think you will want to keep the certificate at the application level.

Some SO questions that helped me along the way:

  • Trust Store vs Key Store — creating with keytool — important to know the difference between the trust manager and keymanager
  • Java HTTPS client certificate authentication
  • How to export private key from a keystore of self-signed certificate
  • What is difference between cacerts and keystore
  • How to connect to a secure website using SSL in Java with a pkcs12 file?
  • Received fatal alert: handshake_failure through SSLHandshakeException
  • How to configure trustStore for javax.net.ssl.trustStore on windows?

You can use Apache HttpClient (or just use the required classes from it to use SslContextBuilder , really), and then it’d be like so:

 SSLContextBuilder sslContextBuilder = SSLContextBuilder.create(); sslContextBuilder.loadTrustMaterial(new File("yourTrustStore.jks"), "thePassWord"); SSLContext sslContext = sslContextBuilder.build(); HttpsURLConnection httpsURLConnection = (HttpsURLConnection) (new URL("https://thesite.com").openConnection()); httpsURLConnection.setSSLSocketFactory(sslContext.getSocketFactory()); 

But you need to create a keystore for your certificate, which can be done with keytool. If you need this for android, you’ll need SpongyCastle library, and use that as a provider for KeyTool to create a BKS keystore instead of a JKS keystore; and you will need to explicitly open the KeyStore in Java.

 KeyStore keyStore = KeyStore.getInstance("BKS", BouncyCastleProvider.PROVIDER_NAME); byteArrayInputStream = new ByteArrayInputStream(keyStoreBytes); keyStore.load(byteArrayInputStream, keyStorePassword); Certificate[] certificates = keyStore.getCertificateChain("theCertAlias"); Certificate certificate = certificates[0]; 

Источник

Оцените статью