【轉載】OpenSSL 提取 pfx 數字證書公鑰與私鑰

轉自https://www.cnblogs.com/Irving/p/9551110.html

OpenSSL 提取 pfx 數字證書公鑰與私鑰

 

因爲以前生產環境已經使用了 Identityserver4 用來作受權與認證的服務,而新項目採用 Spring Cloud 微服務體系,一方面 Spring Cloud 官方暫時只支持 OAuth2.0 協議,還不支持 OpenID Connect 協議(因爲考慮到前項目後端分離登錄安全相關的功能已經作好了,不考慮再次修改 Spring Security 二次開發與其餘開源框架如:Keycloak);另外默認 Identityserver4  也支持 JwtToken ,如今的思路是登錄使用 Identityserver4  的 OpenID Connect 協議認證,受權是在 Zuul 網關中得到 Identityserver4 服務端的公鑰從而進行驗籤,因此就有了這篇文章。html

建立證書node

複製代碼
#生成私鑰文件
openssl genrsa -out idsrv4.key 2048
#建立證書籤名請求文件 CSR(Certificate Signing Request),用於提交給證書頒發機構(即 Certification Authority (CA))即對證書籤名,申請一個數字證書。
openssl req -new -key idsrv4.key -out idsrv4.csr
#生成自簽名證書(證書頒發機構(CA)簽名後的證書,由於本身作測試那麼證書的申請機構和頒發機構都是本身,crt 證書包含持有人的信息,持有人的公鑰,以及簽署者的簽名等信息。當用戶安裝了證書以後,便意味着信任了這份證書,同時擁有了其中的公鑰。)
openssl x509 -req -days 365 -in idsrv4.csr -signkey idsrv4.key -out idsrv4.crt
#自簽名證書與私匙合併成一個文件
openssl pkcs12 -export -in idsrv4.crt -inkey idsrv4.key -out idsrv4.pfx

或
openssl req -newkey rsa:2048 -nodes -keyout idsrv4.key -x509 -days 365 -out idsrv4.cer
openssl pkcs12 -export -in idsrv4.cer -inkey idsrv4.key -out idsrv4.pfx
複製代碼

OpenSSL 提取 pfx 證書公鑰與私鑰git

複製代碼
從pfx證書中提取密鑰信息,並轉換爲key格式(pfx使用pkcs12模式補足)
提取密鑰對(若是pfx證書已加密,會提示輸入密碼)
openssl pkcs12 -in idsrv4.pfx -nocerts -nodes -out idsrv4.key
從密鑰對提取公鑰
openssl rsa -in idsrv4.key -pubout -out idsrv4_pub.key
從密鑰對提取私鑰
openssl rsa -in  idsrv4.key -out idsrv4_pri.key
由於RSA算法使用的是 pkcs8 模式補足,須要對提取的私鑰進一步處理獲得最終私鑰
openssl pkcs8 -topk8 -inform PEM -in idsrv4_pri.key -outform PEM -nocrypt
複製代碼

代碼方式獲取github

複製代碼
public class PFXUtil {

    /**
     * 獲取RSA算法的keyFactory
     *
     * @return
     */
    private static KeyFactory getKeyFactory() throws Exception {
        return getKeyFactory("RSA");
    }

    /**
     * 獲取指定算法的keyFactory
     *
     * @param algorithm
     * @return
     */
    private static KeyFactory getKeyFactory(String algorithm) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
        return keyFactory;
    }

    /**
     * 根據pfx證書獲取keyStore
     *
     * @param pfxData
     * @param password
     * @return
     * @throws Exception
     */
    private static KeyStore getKeyStore(byte[] pfxData, String password) throws Exception {
        KeyStore keystore = KeyStore.getInstance("PKCS12");
        keystore.load(new ByteArrayInputStream(pfxData), password.toCharArray());
        return keystore;
    }

    /**
     * 根據pfx證書獲得私鑰
     *
     * @param pfxData
     * @param password
     * @throws Exception
     */
    public static PrivateKey getPrivateKeyByPfx(byte[] pfxData, String password) throws Exception {
        PrivateKey privateKey = null;
        KeyStore keystore = getKeyStore(pfxData, password);
        Enumeration<String> enums = keystore.aliases();
        String keyAlias = "";
        while (enums.hasMoreElements()) {
            keyAlias = enums.nextElement();
            if (keystore.isKeyEntry(keyAlias)) {
                privateKey = (PrivateKey) keystore.getKey(keyAlias, password.toCharArray());
            }
        }
        return privateKey;
    }

    /**
     * 根據pfx證書獲得私鑰
     *
     * @param pfxPath
     * @param password
     * @return
     * @throws Exception
     */
    public static PrivateKey getPrivateKeyByPfx(String pfxPath, String password) throws Exception {
        File pfxFile = new File(pfxPath);
        return getPrivateKeyByPfx(FileUtils.readFileToByteArray(pfxFile), password);
    }

    /**
     * 根據私鑰字節數組獲取私鑰對象
     *
     * @param privateKeyByte
     * @return
     * @throws Exception
     */
    public static PrivateKey getPrivateKey(byte[] privateKeyByte) throws Exception {
        PrivateKey privateKey = null;
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyByte);
        KeyFactory keyFactory = getKeyFactory();
        privateKey = keyFactory.generatePrivate(keySpec);
        return privateKey;
    }

    /**
     * 根據私鑰Base64字符串獲取私鑰對象
     *
     * @param privateKeyStr
     * @return
     * @throws Exception
     */
    public static PrivateKey getPrivateKey(String privateKeyStr) throws Exception {
        byte[] privateKeyByte = Base64.decodeBase64(privateKeyStr);
        return getPrivateKey(privateKeyByte);
    }

    /**
     * 根據公鑰字節數組獲取公鑰
     *
     * @param publicKeyByte 公鑰字節數組
     * @return
     * @throws Exception
     */
    public static PublicKey getPublicKey(byte[] publicKeyByte) throws Exception {
        PublicKey publicKey = null;
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyByte);
        KeyFactory keyFactory = getKeyFactory();
        publicKey = keyFactory.generatePublic(keySpec);
        return publicKey;
    }

    /**
     * 根據公鑰base64字符串獲取公鑰
     *
     * @param publicKeyStr Base64編碼後的公鑰字節數組
     * @return
     * @throws Exception
     */
    public static PublicKey getPublicKey(String publicKeyStr) throws Exception {
        byte[] publicKeyByte = Base64.decodeBase64(publicKeyStr);
        return getPublicKey(publicKeyByte);
    }

    /**
     * 根據pfx證書獲取證書對象
     *
     * @param pfxData  pfx的字節數組
     * @param password pfx證書密碼
     * @return
     * @throws Exception
     */
    public static X509Certificate getX509Certificate(byte[] pfxData, String password) throws Exception {
        X509Certificate x509Certificate = null;
        KeyStore keystore = getKeyStore(pfxData, password);
        Enumeration<String> enums = keystore.aliases();
        String keyAlias = "";
        while (enums.hasMoreElements()) {
            keyAlias = enums.nextElement();
            if (keystore.isKeyEntry(keyAlias)) {
                x509Certificate = (X509Certificate) keystore.getCertificate(keyAlias);
            }
        }
        return x509Certificate;
    }

    /**
     * 根據pfx證書獲取證書對象
     *
     * @param pfxPath  pfx證書路徑
     * @param password pfx證書密碼
     * @return
     * @throws Exception
     */
    public static X509Certificate getX509Certificate(String pfxPath, String password) throws Exception {
        File pfxFile = new File(pfxPath);
        return getX509Certificate(FileUtils.readFileToByteArray(pfxFile), password);
    }

    //生成pkcs12

    /**
     * 根據私鑰、公鑰證書、密碼生成pkcs12
     *
     * @param privateKey      私鑰
     * @param x509Certificate 公鑰證書
     * @param password        須要設置的密鑰
     * @return
     * @throws Exception
     */
    public static byte[] generatorPkcx12(PrivateKey privateKey, X509Certificate x509Certificate, String password)
            throws Exception {
        Certificate[] chain = {x509Certificate};
        KeyStore keystore = KeyStore.getInstance("PKCS12");
        keystore.load(null, password.toCharArray());
        keystore.setKeyEntry(x509Certificate.getSerialNumber().toString(), privateKey, password.toCharArray(), chain);
        ByteArrayOutputStream bytesos = new ByteArrayOutputStream();
        keystore.store(bytesos, password.toCharArray());
        byte[] bytes = bytesos.toByteArray();
        return bytes;
    }

    //合成pfx

    /**
     * 根據私鑰、公鑰證書、密鑰,保存爲pfx文件
     *
     * @param privateKey      私鑰
     * @param x509Certificate 公鑰證書
     * @param password        打開pfx的密鑰
     * @param saveFile        保存的文件
     * @return
     * @throws Exception
     */
    public static String generatorPFX(PrivateKey privateKey, X509Certificate x509Certificate, String password, File
            saveFile) throws Exception {
        //判斷文件是否存在
        if (!saveFile.exists()) {
            //判斷文件的目錄是否存在
            if (!saveFile.getParentFile().exists()) {
                saveFile.getParentFile().mkdirs();
            }
            saveFile.createNewFile();
        }
        byte[] pkcs12Byte = generatorPkcx12(privateKey, x509Certificate, password);
        FileUtils.writeByteArrayToFile(saveFile, pkcs12Byte);
        return saveFile.getPath();
    }
}

public class TestRsa {

    @Test
    public void contextLoads() {
        String pfxPath ="D:\\github\\SecuringForWebAPI\\IdSrv4.HostSrv\\Certs\\idsrv4.pfx";
        String password = "123456";
        try {
            //私鑰:pfx文件中獲取私鑰對象
            PrivateKey privateKey  = getPrivateKeyByPfx(pfxPath, password);
            byte[] privateKeyByte = privateKey.getEncoded();
            String privateKeyStr = Base64.encodeBase64String(privateKeyByte);
            System.out.println("私鑰Base64字符串:" + privateKeyStr);
            //=====私鑰Base64字符串轉私鑰對象
            PrivateKey privateKey2 = getPrivateKey(privateKeyStr);
            System.out.println("私鑰Base64字符串2:" + Base64.encodeBase64String(privateKey2.getEncoded()));
            //證書:從pfx文件中獲取證書對象
            X509Certificate certificate = getX509Certificate(pfxPath, password);
            System.out.println("證書主題:" + certificate.getSubjectDN().getName());
            String publicKeyStr = Base64.encodeBase64String(certificate.getPublicKey().getEncoded());
            System.out.println("公鑰Base64字符串:" + publicKeyStr);
            //=====根據公鑰Base64字符串獲取公鑰對象
            System.out.println("公鑰Base64字符串2:" + Base64.encodeBase64String(getPublicKey(publicKeyStr).getEncoded()));
//        //PFX:合成pfx(須要私鑰、公鑰證書)
//        String savePath = generatorPFX(privateKey, certificate, "1", new File
//                ("C:\\Users\\irving\\Desktop\\idrv4.pfx"));
//        System.out.println(savePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
複製代碼

REFER:
OpenSSL使用文檔
https://github.com/KaiZhang890/openssl-howto算法

相關文章
相關標籤/搜索