如何正确创建私钥和公钥,以便Java可以读取它们?

时间:2016-09-03 20:30:15

标签: openssl rsa keystore pem

我按照OpenSSL: Generating an RSA Key From the Command Line中的步骤进行了操作。

1. openssl genrsa -des3 -out private.pem 2048
2. openssl rsa -in private.pem -outform PEM -pubout -out public.pem
3. openssl rsa -in private.pem -out private_unencrypted.pem -outform PEM

现在我想用Java代码读取这些文件。所以编写下面的代码,根据链接下面的代码是正确的,但我使用上面三个命令创建的文件格式可以解决问题。有人可以指导我吗?

public class PublicPrivateKeyDemo {
    private static File privateKeyFile = null;
    private static File publicKeyFile = null;

    public static void main(String[] args) {
        String path = "E:/Advance Java/AJAX/1";
        privateKeyFile = new File(path + "/" + "private.pem");
        publicKeyFile = new File(path + "/" + "public.pem");

        try {
            loadkeys();
        } catch (IOException | GeneralSecurityException e) {
            System.out.println(e.getMessage());
        }
    }

    private static void loadkeys() throws IOException, GeneralSecurityException {
        byte[] publicKeyBytes = new byte[(int) publicKeyFile.length()];
        FileInputStream publicFis = null;
        publicFis = new FileInputStream(publicKeyFile);
        if (publicFis.read(publicKeyBytes) > 0) {
            X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes);
            KeyFactory factory = KeyFactory.getInstance("RSA");
            RSAPublicKey pubKey = (RSAPublicKey) factory.generatePublic(publicKeySpec);
            BigInteger pKeyModulus = pubKey.getModulus();
            BigInteger pKeyExponent = pubKey.getPublicExponent();
            System.out.println("PUBLIC KEY EXPO : "+pKeyExponent);

        }

        byte[] privateKeyBytes = new byte[(int) privateKeyFile.length()];
        FileInputStream privateFis = null;
        privateFis = new FileInputStream(privateKeyFile);
        if (privateFis.read(privateKeyBytes) > 0) {
            PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(privateKeyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            RSAPrivateKey privKey = (RSAPrivateKey) keyFactory.generatePrivate(spec);
            BigInteger pKeyModulus = privKey.getModulus();
            BigInteger pKeyExponent = privKey.getPrivateExponent();
            System.out.println("PRIVATE KEY : "+pKeyExponent);
        } 
    }
}

0 个答案:

没有答案