Home  >  Article  >  Java  >  How to Load an RSA Public Key from a File in Java?

How to Load an RSA Public Key from a File in Java?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-01 04:11:28506browse

How to Load an RSA Public Key from a File in Java?

Load RSA Public Key from File

In this article, we will discuss how to load an RSA public key from a file in Java. This scenario arises when we have generated a private and public key pair using OpenSSL and want to use them in Java for digital signing and verification purposes.

Loading Private Key

We can convert the private key to PKCS8 format using OpenSSL and then load it using the following code:

<code class="java">import java.nio.file.*;
import java.security.*;
import java.security.spec.*;

public class PrivateKeyReader {

  public static PrivateKey get(String filename)
    throws Exception {

    byte[] keyBytes = Files.readAllBytes(Paths.get(filename));

    PKCS8EncodedKeySpec spec =
      new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    return kf.generatePrivate(spec);
  }
}</code>

Loading Public Key

To load the public key, we need to convert it to an X509 format. Here's the code snippet:

<code class="java">import java.nio.file.*;
import java.security.*;
import java.security.spec.*;

public class PublicKeyReader {

  public static PublicKey get(String filename)
    throws Exception {
    
    byte[] keyBytes = Files.readAllBytes(Paths.get(filename));

    X509EncodedKeySpec spec =
      new X509EncodedKeySpec(keyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    return kf.generatePublic(spec);
  }
}</code>

By following these steps, you can successfully load both your RSA public and private keys from files and use them for signing and verification operations.

The above is the detailed content of How to Load an RSA Public Key from a File in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn