使用 Java 从 .pem 和 .pub 密钥文件中找出证书到期日期

Find out the certificate expiry date from a .pem and .pub key file using Java

我需要读取 .pem/.pub 密钥文件并提取证书到期日期。 我的代码抛出错误,因为它无法读取 .pem 文件。 我收到错误 [java.security.cert.CertificateParsingException:无效的 DER 编码证书数据] 我需要 java 代码来满足我的需要。

我正在使用以下代码:

public class GetTheCertificate 
{

    public static void main(String[] args) 
    {

        String path="C/Certificates";  // Path where the certificates are located.


        System.out.println("Certificate Path has been validated. ");
        System.out.println("Counting the no of certificates to validate. Please wait.... \n\n");

        validateCert(path);   // calling the function which will validate the certificates and extract the expiry date.

    } // main function ends here

    public static StringBuffer validateCert(String path)
    {
            int i;
            String a="cer";
            String b="jks";
            String c="pem";
            String d="der";
            Date date = null;
        Date current = null;

            InputStream inStream = null;
            StringBuffer str = new StringBuffer();
        File folder = new File(path);
        File[] listOfFiles = folder.listFiles();
        System.out.println("No of Certificates = " + listOfFiles.length);
        System.out.println("\n\n");
        try
        {
        for (i = 0; i < listOfFiles.length; i++) 
        {

            if (listOfFiles[i].isFile()) 
            {
            inStream = new FileInputStream(listOfFiles[i]);
            String ext = FilenameUtils.getExtension(listOfFiles[i].getName());

            System.out.println("Name of the File being scanned  :: " +listOfFiles[i].getName());
            System.out.println("Extension of the file is  :: " +ext);
            System.out.println("\n\n");

            if(ext.equals(c))
            {
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);
                date = (Date) cert.getNotAfter();
                System.out.println(" I am inside .cer validation .....  all ok");
                current = new Date();
                str.append("For Certificate no. - " + (i + 1));
                        str.append(" ");
                        str.append("Current date - " + current);
                str.append(" ");
                str.append("Expiry date - " + date);
                str.append(" ");


                long diff = date.getTime() - current.getTime();
                long diffDays = diff / (24 * 60 * 60 * 1000);

                        if (diffDays <=0)
                        {
                            str.append("Certificate has expired "
                                        + (Math.abs(diffDays))
                                        + " days ago. \nPlease redeem your SSL certificate as soon as possible.  ");
                            sendMail("xyz@abc.com" , diffDays, listOfFiles[i].getName(), date);
                    System.out.println("\n");
                        }
                else if (diffDays <= 31) 
                {
                    str.append("Less than "
                    + (diffDays)
                        + " days remain to expire. \nPlease redeem your SSL certificate as soon as possible.  ");
                sendMail("xyz@abc.com" , diffDays, listOfFiles[i].getName(), date);
                System.out.println("\n");
                }  
                else if (diffDays >31 && diffDays < 60) 
                {
                 str.append((diffDays) + " days remain. \nPlease redeem your SSL certificate after one month from now.  ");
                 sendMail("xyz@abc.com" , diffDays, listOfFiles[i].getName(), date);
                } 
                else 
                {
                str.append((diffDays) + " days remain for SSL Certificate to expire.  ");
                str.append("<br><br>");
                }
            }
            else if (ext.equals(b))
            {
                KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
                keystore.load(new FileInputStream("C:Certificates/serverProdA.jks"), "abcdef".toCharArray());
                Enumeration<String> aliases = keystore.aliases();
                System.out.println(" \n\nI am inside .jks validation .....  all ok");
                while(aliases.hasMoreElements())
                {
                String alias = aliases.nextElement();
                date = ((X509Certificate) keystore.getCertificate(alias)).getNotAfter();
                current = new Date();
                long diff = date.getTime() - current.getTime();
                long diffDays = diff / (24 * 60 * 60 * 1000);

                if(keystore.getCertificate(alias).getType().equals("X.509"))
                {
                    System.out.println(alias + " expires on " + ((X509Certificate) keystore.getCertificate(alias)).getNotAfter());
                    sendMail("xyz@abc.com" , diffDays, alias, date);
                        }
                else
                {
                     System.out.println("\nUnknown file.......");
                    }
                }
            }
            else
            {
                System.out.println("Certificate cant be validated....");
            }
                }
        }
    }
    catch (Exception e) 
    {
        e.printStackTrace();
    } 
    catch (Error e) 
    {
     e.printStackTrace();
    }

    return str;
}   


// start of mail sending function 

检查您传递的字节是 Base64 编码还是 not.If 不是,将其编码为 Base64string.Then 检查。