繁体   English   中英

从crt文件创建p12和keyStore

[英]create p12 and keyStore from crt file

我想从现有的crt文件中使用Java API创建密钥存储区“ PCKS12”。 可能吗? 如果是,该怎么做?

编辑

1 / openssl req -newkey rsa:2048 -nodes -keyout keyFile.key -x509 -days 3650 -out certFile.crt
2 / openssl pkcs12 -export -in certFile.crt -inkey keyFile.key -out tmp.p12 -name别名
3 / keytool -importkeystore -srckeystore tmp.p12 -srcstoretype PKCS12 -srcstorepass密码-destkeystore keyStoreFile.jks -deststoretype JKS -deststorepass密码-destkeypass密码-alias别名

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

您可以使用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));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM