如何使用 OpenSSL 支持的格式在 Java 中生成 RSA 密钥对?
换句话说,我如何使用Java来实现
openssl
中的内容?
openssl genrsa -out mykey.pem 1024
输出应该是这样的:
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3Qa9WiabsxGv2uJBNNFn
Ai3vEDF7Evr85RlgrviUSzkSupEH29PaazKX04/4M7mEQswVZOHSzkFRXiviImi1
c1UrWlZENctS3A6P3RSqOonzrw6CVDJ4Nn/iydWlHhFaHBPpCopS537iHvJIey7K
-----END PUBLIC KEY-----
-----BEGIN PRIVATE KEY-----
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDdBr1aJpuzEa/a
4kE00WcCLe8QMXsS+vzlGWCu+JRLORK6kQfb09prMpfTj/gzuYRCzBVk4dLOQVFe
K+IiaLVzVStaVkQ1y1LcDo/dFKo6ifOvDoJUMng2f+LJ1aUeEVocE+kKilLnfuIe
8kh7LsplosEQSxpfhjQcxt6qgRQk+eI9kyxczLvt2S0goAoO7rPIhi1LQFI1uUij
U18a+vsu9uv/mMAa/R101EZxIJyZZDtjyajPUP3Zo7LfxXZpVgg8xXAE6xY3PGlJ
-----END PRIVATE KEY-----
您说的是 OpenSSL 支持的“该”格式,但 OpenSSL 支持(RSA 和其他)私钥的多种格式,根据您的计数方式,有十多种格式。
您显示的特定格式(也许是巧合)是Java加密直接支持的两种格式的PEM形式,私有的PKCS8未加密和公共的“X.509”(实际上是SubjectPublicKeyInfo,又名SPKI),因此可以创建简单:
//nopackage
import java.security.*;
import java.util.Base64;
public class SO43459993SimpleRSAPEM {
public static void main (String[] args) throws Exception {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048); KeyPair kp = kpg.generateKeyPair();
System.out.println ("-----BEGIN PRIVATE KEY-----");
System.out.println (Base64.getMimeEncoder().encodeToString( kp.getPrivate().getEncoded()));
System.out.println ("-----END PRIVATE KEY-----");
System.out.println ("-----BEGIN PUBLIC KEY-----");
System.out.println (Base64.getMimeEncoder().encodeToString( kp.getPublic().getEncoded()));
System.out.println ("-----END PUBLIC KEY-----");
}
}
输出示例:
-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCiaT/zBxjS6ZBiCbUBiUFirm3/
xo+A8LY3yBsffu6/6mO0ZwrXNtrHmpQEdld5/XM+k8vKOE+KTfeUwikKOLnHeuzV5qrO4/WZPDyz
ggXGqFrgI3/WT8AqTcAmc21CG92Wx+omVaFyl5j5/Sh6aapYl6TG7qX4NXzEln7Ka70Az39nKtqi
oe7LA5ARjcyOBRPXVg2Oq/O+XSwy/epFHIs83ucswF1j/4Nv4u7juCIQ4+sQFyBUwh2docgH9+Ls
MQ18a2N3khNbhxD9TkehuSGU+/KHd0OmEXVHx6dxEvvVTG+MYuuqBbUxdnReggTdX5bJUXtzf+RM
+6yuqauLNlJDAgMBAAECggEAES0WYUpn2q5u4Z9rMC1m59vQsFM8jANpEf8stykCcPOF9edL4zTe
8GstqkcluzYNwRl6XPmVl+fk/iuGkZksNKeQcpLBj73WFI2lUcq3d6oIaln2xCCNDyxH3QkqDerK
hY7A+armtyrHN/EJHeEc7d+jwpIspVJqzpOn9xpr07DyPJ7EK2IsoupMrJ3OwAmcTWvCnv0465fr
t+OOzlHF6m1fQtTKD7kBcKE9vnGdkNbpOxY6VI0p9e0R3ymITeXWFxebq8G7hMO3baD775t55smv
fbWPl41idvTfwAIgUdfKaEk/28zlXwm6WBt3MBF+jlhbfe3zr5RphxtVdIzIYQKBgQD2iqtSXM6/
PrxM2CNnS0RwVNvDcx6+BwemJk+pkfq1BSuXrLbAs3KPfZ51ASHmV9+8IDuV98nJEEKu4einIGUa
m4GK7gHAq0Ml2ISyXTB+28ZXkgDWqvP044T1RbakBrccDDcbsSiIRznyXkJ2VrTA6+Xufz4rIs2Y
IkYnwBKPkwKBgQCopFGz/7VqPDRd5RL0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