Java Key Public getPublicKeyFromPEMFile(String fileName, String jceProvider)

Here you can find the source of getPublicKeyFromPEMFile(String fileName, String jceProvider)

Description

Reads the public key from a PEM formatted file (via the cert)

License

Open Source License

Parameter

Parameter Description
String that designates the JCE Provider

Return

PublicKey java.security.PublicKey extracted from the file

Declaration

public static PublicKey getPublicKeyFromPEMFile(String fileName,
        String jceProvider) 

Method Source Code

//package com.java2s;
/*//  w  w  w .  j a  v a 2  s .c o  m
 * PKIUtils.java
 *
 * This file is part of the IHMC Util Library
 * Copyright (c) 1993-2016 IHMC.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * version 3 (GPLv3) as published by the Free Software Foundation.
 *
 * U.S. Government agencies and organizations may redistribute
 * and/or modify this program under terms equivalent to
 * "Government Purpose Rights" as defined by DFARS 
 * 252.227-7014(a)(12) (February 2014).
 *
 * Alternative licenses that allow for use within commercial products may be
 * available. Contact Niranjan Suri at IHMC (nsuri@ihmc.us) for details.
 */

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileReader;

import java.security.PublicKey;

import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

public class Main {
    private static String _jceProvider = "puretls";
    private static final boolean _debug = false;

    /**
     * Reads the public key from a PEM formatted file (via the cert)
     * @see getCertFromPEMFile (String)
     * 
     * @param String fileName PEM formatted textfile that contains the certificate
     * @param String that designates the JCE Provider
     * @return PublicKey java.security.PublicKey extracted from the file
     */
    public static PublicKey getPublicKeyFromPEMFile(String fileName,
            String jceProvider) {
        _jceProvider = jceProvider;
        if (_debug) {
            System.out
                    .println("getPublicKeyFromPEMFile: Reading public key from "
                            + fileName);
        }
        return getCertFromPEMFile(fileName, _jceProvider).getPublicKey();
    }

    /**
     * Reads the user certificate originally generated by OpenSSL from a PEM formatted file
     * and transform into a java.security.cert.X509Certificate.
     * 
     * These methods will not work in Oasis - Oasis fails with a msg to the affect that it cannot invoke a 
     * method with a return type of 20 - VirtualMachine error stemming from java.security.cert.CertificateGenerator
     * 
     * These were really implemented to assist in the use of a Sun VM underlying the MASTConsole, and to ensure that
     * we could use SSL, and accomplish our cached certificate validation with a MASTKernel on the other end.
     * These will also be useful in getting away from PureTLS as our SSL implementation, and replacing it with
     * Sun's JSSE, as that appears to be the one that is currently being maintained.
     * 
     * @param String fileName PEM formatted textfile that contains the certificate
     * @return X509Certificate java.security.cert.X509Certificate extracted from the file
     */
    public static X509Certificate getCertFromPEMFile(String fileName,
            String jceProvider) {
        if (_debug) {
            System.out.println("getCertFromPEMFile: Reading cert from "
                    + fileName);
        }
        try {
            File inputFile = new File(fileName);
            BufferedReader inputReader = new BufferedReader(new FileReader(
                    inputFile));
            String inputString = extractPEMDelimitedBlock(inputReader,
                    "CERTIFICATE", 0);
            CertificateFactory certificateFactory = null;
            if (jceProvider.startsWith("Sun")
                    || jceProvider.startsWith("SUN")) {
                certificateFactory = CertificateFactory
                        .getInstance("X.509");
            } else {
                certificateFactory = CertificateFactory.getInstance(
                        "X.509", jceProvider);
            }
            X509Certificate clientCert = (java.security.cert.X509Certificate) certificateFactory
                    .generateCertificate(new ByteArrayInputStream(
                            inputString.getBytes()));
            if (clientCert == null) {
                throw new Exception(
                        "PKIUils.getCertFromPEMFile: Generated X509 Certificate is null");
            }
            return clientCert;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    private static String extractPEMDelimitedBlock(
            BufferedReader inputReader, String delimiter, int desiredIndex)
            throws Exception {
        String startDelimiter = "-----BEGIN " + delimiter + "-----";
        String stopDelimiter = "-----END " + delimiter + "-----";

        inputReader.mark(500000);
        String currentLine = null;
        int blockIndex = 0;
        while (blockIndex < desiredIndex) {
            while (((currentLine = inputReader.readLine()) != null)
                    && !currentLine.equalsIgnoreCase(startDelimiter)) {
            }
            if (currentLine == null) {//no such block exists in file
                inputReader.reset();
                return null;
            }
            while (((currentLine = inputReader.readLine()) != null)
                    && !currentLine.equalsIgnoreCase(stopDelimiter)) {
            }
            if (currentLine == null) {//no such block exists in file
                inputReader.reset();
                return null;
            }
            blockIndex++;
        }

        while (((currentLine = inputReader.readLine()) != null)
                && !currentLine.equalsIgnoreCase(startDelimiter)) {
        }
        if (currentLine == null) {//no such block exists in file
            inputReader.reset();
            return null;
        }
        StringBuffer block = new StringBuffer();
        if (delimiter.equalsIgnoreCase("CERTIFICATE")) {
            block.append(currentLine + "\n");
        }
        while (((currentLine = inputReader.readLine()) != null)
                && !currentLine.equalsIgnoreCase(stopDelimiter)) {
            if (currentLine.startsWith("Proc-Type")
                    || currentLine.startsWith("DEK-Info")) {
                block.append(currentLine + "\n");
            } else
                block.append(currentLine);
        }
        if (currentLine.equalsIgnoreCase(stopDelimiter)
                && delimiter.equalsIgnoreCase("CERTIFICATE")) {
            block.append("\n" + currentLine + "\n");
        }
        inputReader.reset();
        return block.toString();
    }
}

Related

  1. getPublicKey(String publicKeyContents)
  2. getPublicKey(String publicKeyFile)
  3. getPublicKey(String publicKeyFilepath, String algorithm)
  4. getPublicKeyFromBytes(final String algorithm, final byte[] publicKeyBytes)
  5. getPublicKeyFromFile(File cert, String alias, String password)
  6. getPublicKeyFromString(String certificateString)
  7. getPublicKeyModulus(RSAPublicKey publicKey)
  8. getPublicKeySpec(KeyPair kp)
  9. getPublicPutMethodForResultClass(final Class resultClass)