如何生成PEM格式的公钥和私钥

use*_*162 7 java rsa pem dsa public-key

我需要使用 java 生成 PEM 格式的 RSA 和 DSA 密钥对(公钥和私钥)。\n我希望使用以下格式打开公钥和私钥文件:

\n\n
\n

-----开始公钥----- MIIBIjANBgkqhkiG9w0BAQEFAOCAQ8AMIIBCgKCAQEAryQICCl6NZ5gDKrnSztO\n 3Hy8PEUcuyvg/ikC+VcIo2SFFSf18a3IMYldIugqqqZCs4/4uVW3sbdLs/6PfgdX\n 7O9D 22ZiFWHPYA2k2N744MNiCD1UE+tJyllUhSblK480亿+v1oZHCM0nYQ2NqUkvS\n j+hwUU3RiWl7x3D2s9wSdNt7XUtW05a/FXehsPSiJfKvHJJnGOX0BgTvkLnkAOTd\n OrUZ/wK69Dzu4I vrN4vs9Nes8vbwPa/ddZEzGR0cQMt0JBkhk9kU/qwqUseP1QRJ\n 5I1jR4g8aYPL/ke9K35PxZWuDp3U0UPAZ3PjFAh+5T+fc7gzCs9dPzSHloruU+gl\n FQIDAQAB\n -----结束公钥-----

\n
\n\n

我的公钥之前已经以这种格式生成,但我不想要它:

\n\n
\n

0\xc5\xb80 *\xe2\x80\xa0H\xe2\x80\xa0\xc3\xb7 0\xc5\xb80 *\xe2\x80\xa0H\xe2\x80\xa0\xc3\xb7

\n
\n\n

好的,这是我的密钥生成代码:

\n\n
private static void createKey()\n        throws Exception {\n\n            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());\n\n            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));\n            System.out.print("Password to encrypt the private key: ");\n            String password = in.readLine();\n            System.out.println("Generating an RSA keypair...");\n\n            // Create an RSA key\n            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");\n            keyPairGenerator.initialize(1024);\n            KeyPair keyPair = keyPairGenerator.genKeyPair();\n\n            System.out.println("Done generating the keypair.\\n");\n\n            // Now we need to write the public key out to a file\n            System.out.print("Public key filename: ");\n            String publicKeyFilename = "C:/Users/Joe/Desktop/" + in.readLine();\n\n            // Get the encoded form of the public key so we can\n            // use it again in the future. This is X.509 by default.\n            byte[] publicKeyBytes = keyPair.getPublic().getEncoded();\n\n            // Write the encoded public key out to the filesystem\n            FileOutputStream fos = new FileOutputStream(publicKeyFilename);\n            fos.write(publicKeyBytes);\n            fos.close();\n\n            // Now we need to do the same thing with the private key,\n            // but we need to password encrypt it as well.\n            System.out.print("Private key filename: ");\n            String privateKeyFilename = "C:/Users/Joe/Desktop/" + in.readLine();\n\n            // Get the encoded form. This is PKCS#8 by default.\n            byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();\n\n            // Here we actually encrypt the private key\n            byte[] encryptedPrivateKeyBytes =\n            passwordEncrypt(password.toCharArray(),privateKeyBytes);\n\n            fos = new FileOutputStream(privateKeyFilename);\n            fos.write(encryptedPrivateKeyBytes);\n            fos.close();\n        }\n
Run Code Online (Sandbox Code Playgroud)\n\n

感谢您的帮助..

\n

小智 9

您可以使用充气城堡来代替手动生成 PEM 字符串:因为它是经过测试的库,所以您可以确定输出。以下代码采用 Kotlin 编写,但可以轻松地与 Java 语法一起使用:

        val gen = KeyPairGenerator.getInstance("RSA")
        gen.initialize(2048)
        val pair = gen.generateKeyPair()
        val privateKey: PrivateKey = pair.private
       
  
        val pemObject = PemObject("RSA PRIVATE KEY", privateKey.encoded)
        
        val byteStream = ByteArrayOutputStream()
        val pemWriter = PemWriter(OutputStreamWriter(byteStream))
        pemWriter.writeObject(pemObject)
        pemWriter.close();
        println(String(byteStream.toByteArray()))

Run Code Online (Sandbox Code Playgroud)


Bit*_*ord 4

也许有点晚了,但我有解决方案。希望它对其他人有帮助。

byte[] publicKeyBytes = keyPair.getPublic().getEncoded();
Run Code Online (Sandbox Code Playgroud)

在这里,您将获取密钥字节并直接写入文件。这样您就得到了适当的结果 - DER 编码的文件。然而,PEM 是 Base64 编码格式,每 64 个符号和页眉/页脚带有换行符。

有代码实现这个逻辑:

String publicKeyContent = Base64.getEncoder().encodeToString(publicKeyBytes);
String publicKeyFormatted = "-----BEGIN PUBLIC KEY-----" + System.lineSeparator();
for (final String row: 
        Splitter
            .fixedLength(64)
            .split(publicKeyContent)
    ) 
{
    publicKeyFormatted += row + System.lineSeparator();
}
publicKeyFormatted += "-----END PUBLIC KEY-----";
Run Code Online (Sandbox Code Playgroud)

因此 publicKeyFormatted 将包含 PEM 编码的公钥字符串。

PS Splitter 是 Guava lib 中提供的一个类,但您可以通过简单的循环或其他方式分割字符串。