首頁 > Java > java教程 > 主體

如何從檔案載入 RSA 私鑰並避免'InvalidKeySpecException”?

Linda Hamilton
發布: 2024-10-25 03:36:30
原創
952 人瀏覽過

How to Load an RSA Private Key from a File and Avoid the

如何從檔案載入 RSA 私鑰

在 Java 中使用 RSA 私鑰時,通常需要載入從一個檔案載入。這可以使用 java.security 套件來完成。但是,在此過程中有時可能會出現錯誤。

一個常見錯誤是:

java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format
登入後複製

這通常表示私鑰檔案的格式不正確。私鑰必須是 PKCS8 格式。

要將私鑰轉換為 PKCS8 格式,可以使用下列指令:

openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key_file  -nocrypt > pkcs8_key
登入後複製

執行此指令後,轉換後的私密金鑰將會儲存在 pkcs8_key 檔案中。然後,您可以使用以下程式碼將此檔案載入到您的 Java 程式中:

<code class="java">import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.InvalidKeySpecException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;

public class LoadRsaPrivateKeyFromFile {

    public static void main(String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
        // Read the converted private key file
        byte[] keyBytes = Files.readAllBytes(Paths.get("pkcs8_key"));

        // Create a PKCS8EncodedKeySpec to wrap the key bytes
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);

        // Create a KeyFactory to generate the private key
        KeyFactory factory = KeyFactory.getInstance("RSA");

        // Generate the private key
        PrivateKey privateKey = factory.generatePrivate(spec);
        
        // Use the private key to sign a message
        // ...
    }
}</code>
登入後複製

以上是如何從檔案載入 RSA 私鑰並避免'InvalidKeySpecException”?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!