你說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+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UXubxolHGq56o+UL4M=
-----END PRIVATE KEY-----
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAomk/8wcY0umQYgm1AYlBYq5t/8aPgPC2
N8gbH37uv+pjtGcK1zbax5qUBHZXef1zPpPLyjhPik33lMIpCji5x3rs1eaqzuP1mTw8s4IFxqha
4CN/1k/AKk3AJnNtQhvdlsfqJlWhcpeY+f0oemmqWJekxu6l+DV8xJZ+ymu9AM9/ZyraoqHuywOQ
EY3MjgUT11YNjqvzvl0sMv3qRRyLPN7nLMBdY/+Db+Lu47giEOPrEBcgVMIdnaHIB/fi7DENfGtj
d5ITW4cQ/U5HobkhlPvyh3dDphF1R8encRL71UxvjGLrqgW1MXZ0XoIE3V+WyVF7c3/kTPusrqmr
izZSQwIDAQAB
-----END PUBLIC KEY-----
我不明白的問題向下票.. – Jonathan
OpenSSL的 - 它可以使用「的OpenSSL genrsa -out的myKey完成。 pem 1 024',但有沒有辦法在java中立即做到這一點? –
可能重複的[生成RSA密鑰對和編碼私人作爲字符串](http://stackoverflow.com/questions/1709441/generate-rsa-key-pair-and-encode-private-as-string) – sm4