從PEM 編碼的私鑰檔案取得RSA 私鑰
在這種情況下,提供的私鑰以PEM 格式編碼,特別是使用PKCS#1。若要從此PEM 編碼檔案擷取RSA 私鑰,您可以使用下列方法之一:
方法1:使用DER 序列解析修改程式碼
提供的Java 程式碼讀取PEM 編碼金鑰並嘗試對其進行解碼。以下建議的修改將允許它解析PKCS#1 格式的私鑰:
... // Skip version seq[0]; BigInteger modulus = seq[1].getBigInteger(); BigInteger publicExp = seq[2].getBigInteger(); BigInteger privateExp = seq[3].getBigInteger(); ... RSAPrivateCrtKeySpec keySpec = new RSAPrivateCrtKeySpec(modulus, publicExp, privateExp, prime1, prime2, exp1, exp2, crtCoef); KeyFactory factory = KeyFactory.getInstance("RSA"); return factory.generatePrivate(keySpec); ...
方法2:使用Sun 提供程式改進程式碼
另一種解決方案是利用sun.security 提供者進行DER 序列解析,並利用java.security 套件進行金鑰產生。這種方法提供了更簡潔且符合 FIPS 標準的實作:
import java.io.File; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.PrivateKey; public static PrivateKey pemFileLoadPrivateKeyPkcs1(File pemFileName) throws GeneralSecurityException, IOException { // PKCS#1 format String PEM_RSA_PRIVATE_START = "-----BEGIN RSA PRIVATE KEY-----"; String PEM_RSA_PRIVATE_END = "-----END RSA PRIVATE KEY-----"; Path path = Paths.get(pemFileName.getAbsolutePath()); String privateKeyPem = new String(Files.readAllBytes(path)); privateKeyPem = privateKeyPem.replace(PEM_RSA_PRIVATE_START, "").replace(PEM_RSA_PRIVATE_END, ""); privateKeyPem = privateKeyPem.replaceAll("\s", ""); DerInputStream derReader = new DerInputStream(Base64.getDecoder().decode(privateKeyPem)); DerValue[] seq = derReader.getSequence(0); if (seq.length < 9) { throw new GeneralSecurityException("Could not parse a PKCS1 private key."); } // Skip version seq[0]; BigInteger modulus = seq[1].getBigInteger(); BigInteger publicExp = seq[2].getBigInteger(); BigInteger privateExp = seq[3].getBigInteger(); BigInteger prime1 = seq[4].getBigInteger(); BigInteger prime2 = seq[5].getBigInteger(); BigInteger exp1 = seq[6].getBigInteger(); BigInteger exp2 = seq[7].getBigInteger(); BigInteger crtCoef = seq[8].getBigInteger(); RSAPrivateCrtKeySpec keySpec = new RSAPrivateCrtKeySpec(modulus, publicExp, privateExp, prime1, prime2, exp1, exp2, crtCoef); KeyFactory factory = KeyFactory.getInstance("RSA"); return factory.generatePrivate(keySpec); }
此程式碼將成功從提供的 PEM 檔案中讀取並解析私鑰,並為您提供 RSA 私鑰物件。
以上是如何從 PEM 編碼檔案中提取 RSA 私鑰?的詳細內容。更多資訊請關注PHP中文網其他相關文章!