从crt文件创建p12和keyStore

问题描述:

我想用java apis创建一个来自现有crt文件的密钥库“PCKS12”。 有可能吗?如果是的话,该怎么做?从crt文件创建p12和keyStore

EDIT

1/ OpenSSL的REQ -newkey RSA:2048 -nodes -keyout keyFile.key -x509 -days 3650 -out certFile.crt
2/ OpenSSL的PKCS12 - 出口-in certFile.crt -inkey keyFile.key退房手续tmp.p12 -name别名
3/ 密钥工具-importkeystore -srckeystore tmp.p12 -srcstoretype PKCS12 -srcstorepass密码-destkeystore keySto reFile.jks -deststoretype JKS -deststorepass password -destkeypass password -alias别名

如何以编程方式进行步骤2和3?

+0

假设CRT文件只包含一个公共密钥,它不会做你多好。一个p12文件通常是一个公钥/私钥对。 – rmlan

您可以创建一个包含Java的keytool一个根CA PKCS#12密钥库:

keytool -importcert -trustcacerts -keystore keystore.p12 -storetype pkcs12 \ 
    -alias root -file root.crt 

系统将提示您为将要用来保护密钥存储的完整性的密码,这样就没有你可以修改你的信任锚而不需要检测。您可以使用其他选项指定密码,但可能会在系统上留下密码记录。

这里,-trustcacerts表示您信任您正在导入的证书作为认证机构。如果不填写,则会显示证书,并且系统会提示您检查并接受它。

别名“root”实际上是商店中证书的昵称,它可以是任何可以帮助您稍后识别此证书的昵称。

而且,当然,文件“root.crt”是您要导入的CA证书。


编程方式:

static void createTrustStore(Path certificate, Path keystore, char[] password) 
     throws IOException, GeneralSecurityException { 
    CertificateFactory cf = CertificateFactory.getInstance("X.509"); 
    Certificate root; 
    try (InputStream is = Files.newInputStream(certificate)) { 
     root = cf.generateCertificate(is); 
    } 
    KeyStore pkcs12 = KeyStore.getInstance("PKCS12"); 
    pkcs12.load(null, null); 
    pkcs12.setCertificateEntry("root", root); 
    try (OutputStream os = Files.newOutputStream(keystore, StandardOpenOption.CREATE_NEW)) { 
     pkcs12.store(os, password); 
    } 
} 

private static final byte[] HEADER = "-----".getBytes(StandardCharsets.US_ASCII); 

static void createIdentityStore(Path certificate, Path key, Path keystore, char[] password) 
     throws IOException, GeneralSecurityException { 
    byte[] pkcs8 = decode(Files.readAllBytes(key)); 
    KeyFactory kf = KeyFactory.getInstance("RSA"); 
    PrivateKey pvt = kf.generatePrivate(new PKCS8EncodedKeySpec(pkcs8)); 
    CertificateFactory cf = CertificateFactory.getInstance("X.509"); 
    Certificate pub; 
    try (InputStream is = Files.newInputStream(certificate)) { 
     pub = cf.generateCertificate(is); 
    } 
    KeyStore pkcs12 = KeyStore.getInstance("PKCS12"); 
    pkcs12.load(null, null); 
    pkcs12.setKeyEntry("identity", pvt, password, new Certificate[] { pub }); 
    try (OutputStream s = Files.newOutputStream(keystore, StandardOpenOption.CREATE_NEW)) { 
     pkcs12.store(s, password); 
    } 
} 

private static byte[] decode(byte[] raw) { 
    if (!Arrays.equals(Arrays.copyOfRange(raw, 0, HEADER.length), HEADER)) return raw; 
    CharBuffer pem = StandardCharsets.US_ASCII.decode(ByteBuffer.wrap(raw)); 
    String[] lines = Pattern.compile("\\R").split(pem); 
    String[] body = Arrays.copyOfRange(lines, 1, lines.length - 1); 
    return Base64.getDecoder().decode(String.join("", body)); 
} 
+0

我想以编程方式创建它 –

+1

@MedBesbes精细 – erickson

+0

你能看到我的编辑请因为作为输入我有.crt和.key文件 –