java驗證openssl生成的ssl證書和私鑰是否匹配
阿新 • • 發佈:2018-12-13
最近有一個需求上傳ssl證書和私鑰,但是上傳之前需要驗證ssl證書和私鑰是否正確,其中的業務邏輯涉及到以下幾點:
一、讀取ssl證書,讀取ssl證書公鑰
要實現該功能比較簡單,java裡面有現成的api支援。
證書格式:
-----BEGIN CERTIFICATE----- MIICYTCCAcoCCQCs45mePIbzRTANBgkqhkiG9w0BAQUFADB1MQswCQYDVQQGEwJV UzENMAsGA1UECAwETWFyczETMBEGA1UEBwwKaVRyYW5zd2FycDETMBEGA1UECgwK aVRyYW5zd2FycDETMBEGA1UECwwKaVRyYW5zd2FycDEYMBYGA1UEAwwPd3d3LjU5 MXdpZmkuY29tMB4XDTE4MTAxNzAyMTA0OFoXDTI4MTAxNDAyMTA0OFowdTELMAkG A1UEBhMCVVMxDTALBgNVBAgMBE1hcnMxEzARBgNVBAcMCmlUcmFuc3dhcnAxEzAR BgNVBAoMCmlUcmFuc3dhcnAxEzARBgNVBAsMCmlUcmFuc3dhcnAxGDAWBgNVBAMM D3d3dy41OTF3aWZpLmNvbTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAtxtP cxgppTHrbzWloh26fXfIyLZI+YpNMCnJ+4wcv3jnZZ6OZsvnoo0z/yl/A9kDY9r5 Rft9fwE4WKMSPNKlGd4psPLw1XNHAXhi8RAy1cHgkBMuwor6ZJhFgnsqKk4Xp68D jaCI2oxu2SYIBU67Fxy+h7G5BsWKwARtj5kP8NECAwEAATANBgkqhkiG9w0BAQUF AAOBgQC2Pko8q1NicJ0oPuhFTPm7n03LtPhCaV/aDf3mqtGxraYifg8iFTxVyZ1c ol0eEJFsibrQrPEwdSuSVqzwif5Tab9dV92PPFm+Sq0D1Uc0xI4ziXQ+a55K9wrV TKXxS48TOpnTA8fVFNkUkFNB54Lhh9AwKsx123kJmyaWccbt9Q== -----END CERTIFICATE-----
相關程式碼:
/** * 從證書檔案獲取公鑰 * * @param file * @return * @throws CertificateException * @throws FileNotFoundException */ public static PublicKey getPublicKeyFromCert(File file) { try { CertificateFactory cf= CertificateFactory.getInstance("X.509"); FileInputStream in = new FileInputStream(file); Certificate crt = cf.generateCertificate(in); PublicKey publicKey = crt.getPublicKey(); return publicKey; } catch (CertificateException e) { logger.error("read public key fail,the reason is :"+e.getMessage()); e.printStackTrace(); } catch (FileNotFoundException e) { logger.error("read public key fail,the reason is the file not exist"); e.printStackTrace(); } return null; }
二、讀取ssl證書私鑰
該功能實現有點困難,網上方法五花八門,需要對openssl生成私鑰的格式和原理比較瞭解,openssl生成的RSA金鑰預設是PEM格式,java包預設只支援DER格式,不能直接讀取PEM格式檔案,說了那麼多,實際上PEM格式只是多了頁面頁尾,由於涉及到的知識點很多,網上資料很多,這裡不在詳細解釋,我們只需要將頁面頁尾去掉然後進行base64位解碼就可以正常讀取了,推薦用第三方包Bouncycastle裡面的pemReader工具類讀取。
私鑰格式:
-----BEGIN RSA PRIVATE KEY----- MIICXgIBAAKBgQC3G09zGCmlMetvNaWiHbp9d8jItkj5ik0wKcn7jBy/eOdlno5m y+eijTP/KX8D2QNj2vlF+31/AThYoxI80qUZ3imw8vDVc0cBeGLxEDLVweCQEy7C ivpkmEWCeyoqThenrwONoIjajG7ZJggFTrsXHL6HsbkGxYrABG2PmQ/w0QIDAQAB AoGBAIxvTcggSBCC8OciZh6oXlfMfxoxdFavU/QUmO1s0L+pow+1Q9JjoQxy7+ZL lTcGQitbzsN11xKJhQW2TE6J4EVimJZQSAE4DDmYpMOrkjnBQhkUlaZkkukvDSRS JqwBI/04G7se+RouHyXjRS9U76HnPM8+/IS2h+T6CbXLOpYBAkEA2j0JmyGVs+WV I9sG5glamJqTBa4CfTORrdFW4EULoGkUc24ZFFqn9W4e5yfl/pCkPptCenvIrAWp /ymnHeLn6QJBANbKGO9uBizAt4+o+kHYdANcbU/Cs3PLj8yOOtjkuMbH4tPNQmB6 /u3npiVk7/Txfkg0BjRzDDZib109eKbvGKkCQBgMneBghRS7+gFng40Z/sfOUOFR WajeY/FZnk88jJlyuvQ1b8IUc2nSZslmViwFWHQlu9+vgF+kiCU8O9RJSvECQQCl Vkx7giYerPqgC2MY7JXhQHSkwSuCJ2A6BgImk2npGlTw1UATJJq4Z2jtwBU2Z+7d ha6BEU6FTqCLFZaaadKBAkEAxko4hrgBsX9BKpFJE3aUIUcMTJfJQdiAhq0k4DV8 5GVrcp8zl6mUTPZDaOmDhuAjGdAQJqj0Xo0PZ0fOZPtR+w== -----END RSA PRIVATE KEY-----
相關程式碼:
/** * 利用開源的工具類解析openssl私鑰,openssl私鑰檔案格式為pem,需要去除頁首頁尾後才能被java讀取 * * @param file * @return */ public static PrivateKey getPrivateKey(File file) { if (file == null) { return null; } PrivateKey privKey = null; PemReader pemReader = null; try { pemReader = new PemReader(new FileReader(file)); PemObject pemObject = pemReader.readPemObject(); byte[] pemContent = pemObject.getContent(); //私鑰需要使用pkcs8格式編碼 PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(pemContent); KeyFactory kf = KeyFactory.getInstance("RSA"); privKey = kf.generatePrivate(privKeySpec); return privKey; } catch (FileNotFoundException e) { logger.error("read public key fail,the reason is the file not exist"); e.printStackTrace(); } catch (IOException e) { logger.error("read public key fail,the reason is :"+e.getMessage()); e.printStackTrace(); } catch (NoSuchAlgorithmException e) { logger.error("read public key fail,the reason is :"+e.getMessage()); e.printStackTrace(); } catch (InvalidKeySpecException e) { logger.error("read public key fail,the reason is :"+e.getMessage()); e.printStackTrace(); } catch (GeneralSecurityException e) { logger.error("read public key fail,the reason is :"+e.getMessage()); e.printStackTrace(); } finally { try { if (pemReader != null) { pemReader.close(); } } catch (IOException e) { e.printStackTrace(); } } return privKey; }
三、ssl證書公鑰和私鑰是否匹配
讀取證書公鑰和私鑰後,將測試的字串經過證書公鑰加密後,再根據證書私鑰解密後能後還原,說明上傳的證書和私鑰是正確的。
/** * 加密 * * @param key * @param plainBytes * @return */ public static byte[] encrypt(PublicKey key, byte[] plainBytes) { ByteArrayOutputStream out = null; try { Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, key); int inputLen = plainBytes.length; if (inputLen <= MAX_ENCRYPT_BLOCK) { return cipher.doFinal(plainBytes); } out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; // 資料太長對資料分段加密 while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_ENCRYPT_BLOCK) { cache = cipher.doFinal(plainBytes, offSet, MAX_ENCRYPT_BLOCK); } else { cache = cipher.doFinal(plainBytes, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_ENCRYPT_BLOCK; } return out.toByteArray(); } catch (NoSuchAlgorithmException e) { logger.error("rencrypt fail,the reason is : no such decryption algorithm,"+e.getMessage()); e.printStackTrace(); return null; } catch (NoSuchPaddingException e) { logger.error("rencrypt fail,the reason is :"+e.getMessage()); e.printStackTrace(); return null; } catch (InvalidKeyException e) { logger.error("rencrypt fail,the reason is : decrypting the private key is illegal, please check,"+e.getMessage()); e.printStackTrace(); return null; } catch (IllegalBlockSizeException e) { logger.error("rencrypt fail,the reason is : Illegal ciphertext length, please check,"+e.getMessage()); e.printStackTrace(); return null; } catch (BadPaddingException e) { logger.error("rencrypt fail,the reason is : ciphertext data is corrupt, please check,"+e.getMessage()); e.printStackTrace(); return null; } finally { try { if (out != null) out.close(); } catch (Exception e2) { } } } /** * 根據公鑰加密字串 * * @param key * @param plainText 需要加密的字串 * @return */ public static String encrypt(PublicKey key, String plainText) { byte[] encodeBytes = encrypt(key, plainText.getBytes(DEFAULT_CHARSET)); return Base64.encodeBase64String(encodeBytes); } /** * 解密 * * @param key * @param encodedText * @return */ public static String decrypt(PrivateKey key, byte[] encodedText) { ByteArrayOutputStream out = null; try { Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, key); int inputLen = encodedText.length; if (inputLen <= MAX_DECRYPT_BLOCK) { return new String(cipher.doFinal(encodedText), DEFAULT_CHARSET); } out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; // 對資料分段解密 while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_DECRYPT_BLOCK) { cache = cipher.doFinal(encodedText, offSet, MAX_DECRYPT_BLOCK); } else { cache = cipher.doFinal(encodedText, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_DECRYPT_BLOCK; } return new String(out.toByteArray(), DEFAULT_CHARSET); } catch (NoSuchAlgorithmException e) { logger.error("rencrypt fail,the reason is : no such decryption algorithm,"+e.getMessage()); e.printStackTrace(); return null; } catch (NoSuchPaddingException e) { logger.error("rencrypt fail,the reason is :"+e.getMessage()); e.printStackTrace(); return null; } catch (InvalidKeyException e) { logger.error("rencrypt fail,the reason is : decrypting the private key is illegal, please check,"+e.getMessage()); e.printStackTrace(); return null; } catch (IllegalBlockSizeException e) { logger.error("rencrypt fail,the reason is : Illegal ciphertext length, please check,"+e.getMessage()); e.printStackTrace(); return null; } catch (BadPaddingException e) { logger.error("rencrypt fail,the reason is : ciphertext data is corrupt, please check,"+e.getMessage()); e.printStackTrace(); return null; } finally { try { if (out != null) out.close(); } catch (Exception e2) { } } } /** * 根據私鑰解密加密過的字串 * * @param key * @param encodedText 加密過的字串 * @return 解密後的字串 */ public static String decrypt(PrivateKey key, String encodedText) { byte[] bytes = Base64.decodeBase64(encodedText); return decrypt(key, bytes); } /** * 驗證證書 * @param cert * @return */ public static String validateCert(File cert){ if (cert == null) { return "證書CRT檔案不能為空"; } PublicKey publicKey = getPublicKeyFromCert(cert); if (publicKey == null) { return "無法讀取證書公鑰,證書CRT檔案格式錯誤"; } return null; } /** * 驗證私鑰 * @param privateKey * @return */ public static String validatePrivateKey( File privateKey){ if (privateKey == null) { return "證書私鑰不能為空"; } PrivateKey privKey = getPrivateKey(privateKey); if (privKey == null) { return "無法讀取證書私鑰,證書私鑰檔案格式錯誤"; } return null; } /** * 驗證證書私鑰是否匹配,如果不匹配返回錯誤訊息 * @param cert * @param privateKey * @return 錯誤訊息 */ public static String validate(File cert, File privateKey) { String res = validateCert(cert);//驗證證書 if((res!=null)&&(res.length()>0)){ return res;//返回錯誤訊息 } res = validatePrivateKey(privateKey);//驗證私鑰 if((res!=null)&&(res.length()>0)){ return res;//返回錯誤訊息 } PublicKey publicKey = getPublicKeyFromCert(cert); PrivateKey privKey = getPrivateKey(privateKey); String str = "haha";//測試字串 String encryptStr = OpensslUtils.encrypt(publicKey, str);//根據證書公鑰對字串進行加密 String decryptStr = OpensslUtils.decrypt(privKey, encryptStr);//根據證書私鑰對加密字串進行解密 if(!str.equals(decryptStr)){//字串根據證書公鑰加密,私鑰解密後不能還原說明證書與私鑰不匹配 return "證書與私鑰不匹配"; } return null; }
四、完整程式碼
package com.shixun.ewifi.utils; import org.apache.commons.codec.binary.Base64; import org.apache.log4j.Logger; import org.bouncycastle.util.io.pem.PemObject; import org.bouncycastle.util.io.pem.PemReader; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import java.io.*; import java.nio.charset.Charset; import java.security.*; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; /** * openssl 證書公鑰私鑰讀取加密解密工具類,主要用於驗證上傳的openssl 生成的證書和私鑰檔案是否正確的問題 * * @author yinliang 2018.12.13 add * 主要邏輯: * 1、根據私鑰檔案讀取私鑰 * 2、根據公鑰檔案讀取公鑰 * 3、根據證書檔案讀取公鑰 * 4、根據證書公鑰加密字串 * 5、根據證書私鑰解密字串 * 6、如果字串經過證書公鑰加密後,再根據證書私鑰解密後能後還原,說明上傳的證書和私鑰是正確的 */ public class OpensslUtils { private static final String DEFAULT_ENCODING = "UTF-8"; private static final Charset DEFAULT_CHARSET = Charset.forName(DEFAULT_ENCODING); private static final String KEY_ALGORITHM = "RSA"; /** * 預設是RSA/NONE/PKCS1Padding */ private static final String CIPHER_ALGORITHM = "RSA/ECB/PKCS1Padding"; /** * RSA金鑰長度必須是64的倍數,在512~65536之間。預設是1024 */ private static final int KEY_SIZE = 1024; /** * RSA最大加密明文大小:明文長度(bytes) <= 金鑰長度(bytes)-11 */ private static final int MAX_ENCRYPT_BLOCK = KEY_SIZE / 8 - 11; /** * RSA最大解密密文大小 */ private static final int MAX_DECRYPT_BLOCK = KEY_SIZE / 8; private static Logger logger = Logger.getLogger(OpensslUtils.class); /** * 利用開源的工具類解析openssl私鑰,openssl私鑰檔案格式為pem,需要去除頁首頁尾後才能被java讀取 * * @param file * @return */ public static PrivateKey getPrivateKey(File file) { if (file == null) { return null; } PrivateKey privKey = null; PemReader pemReader = null; try { pemReader = new PemReader(new FileReader(file)); PemObject pemObject = pemReader.readPemObject(); byte[] pemContent = pemObject.getContent(); //私鑰需要使用pkcs8格式編碼 PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(pemContent); KeyFactory kf = KeyFactory.getInstance("RSA"); privKey = kf.generatePrivate(privKeySpec); return privKey; } catch (FileNotFoundException e) { logger.error("read public key fail,the reason is the file not exist"); e.printStackTrace(); } catch (IOException e) { logger.error("read public key fail,the reason is :"+e.getMessage()); e.printStackTrace(); } catch (NoSuchAlgorithmException e) { logger.error("read public key fail,the reason is :"+e.getMessage()); e.printStackTrace(); } catch (InvalidKeySpecException e) { logger.error("read public key fail,the reason is :"+e.getMessage()); e.printStackTrace(); } catch (GeneralSecurityException e) { logger.error("read public key fail,the reason is :"+e.getMessage()); e.printStackTrace(); } finally { try { if (pemReader != null) { pemReader.close(); } } catch (IOException e) { e.printStackTrace(); } } return privKey; } /** * 利用java自帶的方法讀取openssl私鑰,openssl私鑰檔案格式為pem,需要去除頁首頁尾後,再進行base64位解碼才能被java讀取 * 注意該方法有缺陷,只是簡單的根據註釋將頁首頁尾去掉了,不是很完善,如果頁首頁尾前面有空格和註釋的情況的會有問題,保留此方法是為方便弄清楚openssl私鑰解析原理 * * @param file * @return */ public static PrivateKey getPrivateKey1(File file) { if (file == null) { return null; } PrivateKey privKey = null; try { BufferedReader privateKey = new BufferedReader(new FileReader( file)); String line = ""; String strPrivateKey = ""; while ((line = privateKey.readLine()) != null) { if (line.contains("--")) {//過濾掉首尾頁首頁尾 continue; } strPrivateKey += line; } privateKey.close(); ; //使用base64位解碼 byte[] privKeyByte = Base64.decodeBase64(strPrivateKey); //私鑰需要使用pkcs8格式編碼 PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(privKeyByte); KeyFactory kf = KeyFactory.getInstance("RSA"); privKey = kf.generatePrivate(privKeySpec); return privKey; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeySpecException e) { e.printStackTrace(); } return privKey; } /** * 從證書檔案獲取公鑰 * * @param file * @return * @throws CertificateException * @throws FileNotFoundException */ public static PublicKey getPublicKeyFromCert(File file) { try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); FileInputStream in = new FileInputStream(file); Certificate crt = cf.generateCertificate(in); PublicKey publicKey = crt.getPublicKey(); return publicKey; } catch (CertificateException e) { logger.error("read public key fail,the reason is :"+e.getMessage()); e.printStackTrace(); } catch (FileNotFoundException e) { logger.error("read public key fail,the reason is the file not exist"); e.printStackTrace(); } return null; } /** * 從openssl公鑰檔案中讀取公鑰 * @param file * @return */ public static PublicKey getPublicKey(File file) { if (file == null) { return null; } PublicKey pubKey = null; PemReader pemReader = null; try { pemReader = new PemReader(new FileReader(file)); PemObject pemObject = pemReader.readPemObject(); byte[] pemContent = pemObject.getContent(); //公鑰需要使用x509格式編碼 X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(pemContent); KeyFactory kf = KeyFactory.getInstance("RSA"); pubKey = kf.generatePublic(pubKeySpec); return pubKey; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeySpecException e) { e.printStackTrace(); } catch (GeneralSecurityException e) { e.printStackTrace(); } finally { try { if (pemReader != null) { pemReader.close(); } } catch (IOException e) { e.printStackTrace(); } } return pubKey; } /** * 加密 * * @param key * @param plainBytes * @return */ public static byte[] encrypt(PublicKey key, byte[] plainBytes) { ByteArrayOutputStream out = null; try { Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, key); int inputLen = plainBytes.length; if (inputLen <= MAX_ENCRYPT_BLOCK) { return cipher.doFinal(plainBytes); } out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; // 資料太長對資料分段加密 while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_ENCRYPT_BLOCK) { cache = cipher.doFinal(plainBytes, offSet, MAX_ENCRYPT_BLOCK); } else { cache = cipher.doFinal(plainBytes, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_ENCRYPT_BLOCK; } return out.toByteArray(); } catch (NoSuchAlgorithmException e) { logger.error("rencrypt fail,the reason is : no such decryption algorithm,"+e.getMessage()); e.printStackTrace(); return null; } catch (NoSuchPaddingException e) { logger.error("rencrypt fail,the reason is :"+e.getMessage()); e.printStackTrace(); return null; } catch (InvalidKeyException e) { logger.error("rencrypt fail,the reason is : decrypting the private key is illegal, please check,"+e.getMessage()); e.printStackTrace(); return null; } catch (IllegalBlockSizeException e) { logger.error("rencrypt fail,the reason is : Illegal ciphertext length, please check,"+e.getMessage()); e.printStackTrace(); return null; } catch (BadPaddingException e) { logger.error("rencrypt fail,the reason is : ciphertext data is corrupt, please check,"+e.getMessage()); e.printStackTrace(); return null; } finally { try { if (out != null) out.close(); } catch (Exception e2) { } } } /** * 根據公鑰加密字串 * * @param key * @param plainText 需要加密的字串 * @return */ public static String encrypt(PublicKey key, String plainText) { byte[] encodeBytes = encrypt(key, plainText.getBytes(DEFAULT_CHARSET)); return Base64.encodeBase64String(encodeBytes); } /** * 解密 * * @param key * @param encodedText * @return */ public static String decrypt(PrivateKey key, byte[] encodedText) { ByteArrayOutputStream out = null; try { Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, key); int inputLen = encodedText.length; if (inputLen <= MAX_DECRYPT_BLOCK) { return new String(cipher.doFinal(encodedText), DEFAULT_CHARSET); } out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; // 對資料分段解密 while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_DECRYPT_BLOCK) { cache = cipher.doFinal(encodedText, offSet, MAX_DECRYPT_BLOCK); } else { cache = cipher.doFinal(encodedText, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_DECRYPT_BLOCK; } return new String(out.toByteArray(), DEFAULT_CHARSET); } catch (NoSuchAlgorithmException e) { logger.error("rencrypt fail,the reason is : no such decryption algorithm,"+e.getMessage()); e.printStackTrace(); return null; } catch (NoSuchPaddingException e) { logger.error("rencrypt fail,the reason is :"+e.getMessage()); e.printStackTrace(); return null; } catch (InvalidKeyException e) { logger.error("rencrypt fail,the reason is : decrypting the private key is illegal, please check,"+e.getMessage()); e.printStackTrace(); return null; } catch (IllegalBlockSizeException e) { logger.error("rencrypt fail,the reason is : Illegal ciphertext length, please check,"+e.getMessage()); e.printStackTrace(); return null; } catch (BadPaddingException e) { logger.error("rencrypt fail,the reason is : ciphertext data is corrupt, please check,"+e.getMessage()); e.printStackTrace(); return null; } finally { try { if (out != null) out.close(); } catch (Exception e2) { } } } /** * 根據私鑰解密加密過的字串 * * @param key * @param encodedText 加密過的字串 * @return 解密後的字串 */ public static String decrypt(PrivateKey key, String encodedText) { byte[] bytes = Base64.decodeBase64(encodedText); return decrypt(key, bytes); } /** * 驗證證書 * @param cert * @return */ public static String validateCert(File cert){ if (cert == null) { return "證書CRT檔案不能為空"; } PublicKey publicKey = getPublicKeyFromCert(cert); if (publicKey == null) { return "無法讀取證書公鑰,證書CRT檔案格式錯誤"; } return null; } /** * 驗證私鑰 * @param privateKey * @return */ public static String validatePrivateKey( File privateKey){ if (privateKey == null) { return "證書私鑰不能為空"; } PrivateKey privKey = getPrivateKey(privateKey); if (privKey == null) { return "無法讀取證書私鑰,證書私鑰檔案格式錯誤"; } return null; } /** * 驗證證書私鑰是否匹配,如果不匹配返回錯誤訊息 * @param cert * @param privateKey * @return 錯誤訊息 */ public static String validate(File cert, File privateKey) { String res = validateCert(cert);//驗證證書 if((res!=null)&&(res.length()>0)){ return res;//返回錯誤訊息 } res = validatePrivateKey(privateKey);//驗證私鑰 if((res!=null)&&(res.length()>0)){ return res;//返回錯誤訊息 } PublicKey publicKey = getPublicKeyFromCert(cert); PrivateKey privKey = getPrivateKey(privateKey); String str = "haha";//測試字串 String encryptStr = OpensslUtils.encrypt(publicKey, str);//根據證書公鑰對字串進行加密 String decryptStr = OpensslUtils.decrypt(privKey, encryptStr);//根據證書私鑰對加密字串進行解密 if(!str.equals(decryptStr)){//字串根據證書公鑰加密,私鑰解密後不能還原說明證書與私鑰不匹配 return "證書與私鑰不匹配"; } return null; } /** * 測試主方法 * * @param args */ public static void main(String[] args) { File privateKeyFile = new File("src/main/resources/www.test.com.key"); PrivateKey privKey = OpensslUtils.getPrivateKey(privateKeyFile); System.out.println("privKey:" + privKey); File certFile = new File("src/main/resources/www.test.com.crt"); publicKey = OpensslUtils.getPublicKeyFromCert(certFile); System.out.println("publicKey:" + publicKey); String validateResult = validate(certFile,privateKeyFile); System.out.println("validateResult:" + validateResult); } }
五:涉及到的第三方jar包
<dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcprov-jdk15on</artifactId> <version>1.58</version> </dependency>
六、參考資料
java讀取openssl生成的RSA金鑰 線上驗證證書與私鑰正確性