简体   繁体   中英

How to read a public key from a file

I have this issue where I dont know how to read my public key file, I have looked for a while now for solutions but they tend to not answer my question in my case. I have a program which generates a public and a private key, I have another method that writes them down in there own files respectively. This may sound silly but I really dont know how I can read the key from a file. This is needed as I want to do asymetrec encryption and so will be transphereing key files around. I will link my code below, any help is much appreaciated:)
If you need anymore detail to my explanation then feel free to ask.
Thanks!

Key Generation and storage methods:

public class Encryption {
    
    
    public static PrivateKey privateKey;
    public static PublicKey publicKey;
    
    public void KeyGeneration() throws NoSuchAlgorithmException{
        KeyPairGenerator Generator = KeyPairGenerator.getInstance("RSA"); // Creat the Generator object with RSA
        Generator.initialize(1024); // Set the generator to make the 2048 bit key
        KeyPair Pair = Generator.genKeyPair(); // Generate the key pair
        publicKey = Pair.getPublic(); // Set the Public Key
        privateKey = Pair.getPrivate(); // Set the private Key
        
        System.out.println(Base64.getEncoder().encodeToString(publicKey.getEncoded()));
        System.out.println(Base64.getEncoder().encodeToString(privateKey.getEncoded()));

              
    }

    

    
    
 
    public void writeToFile(String filePath, byte[] key) throws IOException{
        File fileToWriteto = new File(filePath);
        fileToWriteto.getParentFile().mkdirs();
        FileOutputStream FoutputStream = new FileOutputStream(fileToWriteto);
        FoutputStream.write(key);
        FoutputStream.flush();
        FoutputStream.close();
        
    
    }
  }

The easiest way to save and load RSA key files is by using the encoded version. The below code is saving a private and a public key to a file in encoded form.

The simple output:

Save and load RSA Keys encoded
private key equals: true
public key equals:  true

Warning: please note that the following code has no exception handling and is for educational purpose only.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;

public class SaveLoadRsaKeysSo {
    public static void main(String[] args) throws GeneralSecurityException, IOException {
        System.out.println("Save and load RSA Keys encoded");

        KeyPairGenerator rsaGenerator = KeyPairGenerator.getInstance("RSA");
        SecureRandom random = new SecureRandom();
        rsaGenerator.initialize(2048, random);
        KeyPair rsaKeyPair = rsaGenerator.generateKeyPair();
        PublicKey rsaPublicKey = rsaKeyPair.getPublic();
        PrivateKey rsaPrivateKey = rsaKeyPair.getPrivate();

        // save private & public key
        Files.write(Paths.get("rsaPrivateKey.encoded"), rsaPrivateKey.getEncoded());
        Files.write(Paths.get("rsaPublicKey.encoded"), rsaPublicKey.getEncoded());

        // load private & public key
        byte[] privateKeyBytesLoad = Files.readAllBytes(Paths.get("rsaPrivateKey.encoded"));
        PrivateKey privateKeyLoad = getPrivateKeyFromEncoded(privateKeyBytesLoad);
        byte[] publicKeyBytesLoad = Files.readAllBytes(Paths.get("rsaPublicKey.encoded"));
        PublicKey publicKeyLoad = getPublicKeyFromEncoded(publicKeyBytesLoad);

        System.out.println("private key equals: " + Arrays.equals(rsaPrivateKey.getEncoded(), privateKeyLoad.getEncoded()));
        System.out.println("public key equals:  " + Arrays.equals(rsaPublicKey.getEncoded(), publicKeyLoad.getEncoded()));
    }

    public static PrivateKey getPrivateKeyFromEncoded(byte[] key) throws GeneralSecurityException {
        KeyFactory kf = KeyFactory.getInstance("RSA");
        return (PrivateKey) kf.generatePrivate(new PKCS8EncodedKeySpec(key));
    }

    public static PublicKey getPublicKeyFromEncoded(byte[] key) throws GeneralSecurityException {
        KeyFactory kf = KeyFactory.getInstance("RSA");
        return (PublicKey) kf.generatePublic(new X509EncodedKeySpec(key));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM