從PEM 編碼檔案擷取RSA 私鑰
問題:
您有一個有一個私人編碼的私編碼鑰檔案PEM BASE64 格式並希望在外部上下文中使用它。但是,在嘗試解碼金鑰時遇到錯誤。
程式碼片段與錯誤:
用於讀取私鑰和解碼 BASE64 資料的 Java 程式碼片段:
// Code omitted for brevity
遇到的錯誤:
InvalidKeySpecException: Inappropriate key specification: DerInputStream.getLength(): lengthTag=127, too big.
解決方案:
該錯誤表明密鑰採用PKCS#1 格式,這需要與您的格式程式碼中針對的PKCS#8 格式。以下是解決此問題的修訂解決方案:
import sun.security.util.DerInputStream; import sun.security.util.DerValue; // Code omitted for brevity public static PrivateKey pemFileLoadPrivateKeyPkcs1OrPkcs8Encoded(File pemFileName) throws GeneralSecurityException, IOException { // PKCS#8 format final String PEM_PRIVATE_START = "-----BEGIN PRIVATE KEY-----"; final String PEM_PRIVATE_END = "-----END PRIVATE KEY-----"; // PKCS#1 format final String PEM_RSA_PRIVATE_START = "-----BEGIN RSA PRIVATE KEY-----"; final String PEM_RSA_PRIVATE_END = "-----END RSA PRIVATE KEY-----"; Path path = Paths.get(pemFileName.getAbsolutePath()); String privateKeyPem = new String(Files.readAllBytes(path)); if (privateKeyPem.indexOf(PEM_PRIVATE_START) != -1) { // PKCS#8 format // Code omitted for brevity } else if (privateKeyPem.indexOf(PEM_RSA_PRIVATE_START) != -1) { // PKCS#1 format 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); // Code omitted for brevity } throw new GeneralSecurityException("Not supported format of a private key"); }
此更新的程式碼可處理 PKCS#8 和 PKCS#1 格式,使您能夠成功提取私鑰並繼續您的預期用途。
以上是遇到「InvalidKeySpecException」時,如何從 PEM 編碼檔案擷取 RSA 私鑰?的詳細內容。更多資訊請關注PHP中文網其他相關文章!