首页 > 解决方案 > 如何从文件中读取公钥

问题描述

我有这个问题,我不知道如何读取我的公钥文件,我已经寻找了一段时间的解决方案,但他们往往不会回答我的问题。我有一个生成公钥和私钥的程序,我有另一种方法可以分别将它们写在自己的文件中。这听起来可能很傻,但我真的不知道如何从文件中读取密钥。这是必需的,因为我想做不对称加密,因此将围绕密钥文件进行传输。我将在下面链接我的代码,非常感谢您的帮助 :)
如果您需要更多详细信息来解释我的解释,请随时提出。
谢谢!

密钥生成和存储方法:

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();
        
    
    }
  }

标签: javafileencryptionrsa

解决方案


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));
    }
}

推荐阅读