简体   繁体   English

如何在openssl生成的java中使用.key和.crt文件?

[英]How to use .key and .crt file in java that generated by openssl?

I need asymmetric encryption in java. 我需要java中的非对称加密。 I generate .key and .crt files with own password and .crt file by openssl that said in http://www.imacat.idv.tw/tech/sslcerts.html . 我在http://www.imacat.idv.tw/tech/sslcerts.html中用openssl生成带有自己密码和.crt文件的.key和.crt文件。
How to use these .key and .crt file to extract publickey and private key in Java? 如何使用这些.key和.crt文件在Java中提取publickey和私钥?

Your .key and .crt files may be in PEM format. 您的.key.crt文件可能采用PEM格式。 To check this open them with a text editor and check whether the content looks like ------BEGIN CERTIFICATE------ (or "begin RSA private key"...). 要检查这一点,请使用文本编辑器打开它们,并检查内容是否类似------BEGIN CERTIFICATE------ (或“开始RSA私钥”...)。 This is generally the default format used by OpenSSL, unless you've explicitly specified DER. 这通常是OpenSSL使用的默认格式,除非您明确指定了DER。

It's probably not required (see below), but if your certificate is in DER format (a binary format), you can convert them in PEM format using: 它可能不是必需的(见下文),但如果您的证书是DER格式(二进制格式),您可以使用以下方式将它们转换为PEM格式:

openssl x509 -inform DER -in cert.crt -outform PEM -out cert.pem

(Check the help for openssl rsa for doing something similar with the private key if needed.) (如果需要,请检查openssl rsa的帮助,以便使用私钥执行类似操作。)

You then get two options: 然后你有两个选择:

  • Build a PKCS#12 file 构建PKCS#12文件

     openssl pkcs12 -export -in myhost.crt -inkey myhost.key -out myhost.p12 

You can then use it directly from Java as a keystore of type "PKCS12". 然后,您可以直接从Java中将其用作“PKCS12”类型的密钥库。 Most Java applications should allow you to specify a keystore type in addition to the file location. 除文件位置外,大多数Java应用程序都应允许您指定密钥库类型。 For the default system properties, this is done with javax.net.ssl.keyStoreType (but the application you're using might not be using this). 对于默认的系统属性,这是通过javax.net.ssl.keyStoreType完成的(但您正在使用的应用程序可能没有使用它)。 Otherwise, if you want to load it explicitly, use something like this: 否则,如果要显式加载它,请使用以下内容:

KeyStore ks = KeyStore.getInstance("PKCS12");
FileInputStream fis =
    new FileInputStream("/path/to/myhost.p12");
ks.load(fis, "password".toCharArray()); // There are other ways to read the password.
fis.close();

(Then, you should be able to iterate through the aliases() of the KeyStore and use getCertificate (and then getPublicKey() for the public key) and getKey() . (然后,您应该能够遍历KeyStorealiases()并使用getCertificate (然后使用getPublicKey()作为公钥)和getKey()

  • Use BouncyCastle 's PEMReader . 使用BouncyCastlePEMReader

      FileReader fr = ... // Create a FileReader for myhost.crt PEMReader pemReader = new PEMReader(fr); X509Certificate cert = (X509Certificate)pemReader.readObject(); PublicKey pk = cert.getPublicKey(); // Close reader... 

For the private key, you'll need to implement a PasswordFinder (see link from PEMReader doc) for constructing the PEMReader if the private key is password-protected. 对于私钥,如果私钥受密码保护,则需要实现PasswordFinder (请参阅PEMReader文档中的链接)以构建PEMReader (You'll need to cast the result of readObject() into a Key or PrivateKey .) (您需要将readObject()的结果readObject()转换为KeyPrivateKey 。)

This should do what you want to do (using the BouncyCastle PEMReader as suggested above) -- take a PEM-encoded private key + certificate, and output a PKCS#12 file. 这应该做你想做的事情(使用上面建议的BouncyCastle PEMReader) - 获取PEM编码的私钥+证书,并输出PKCS#12文件。 Uses the same password for the PKCS12 that was used to protect the private key. 使用用于保护私钥的PKCS12的相同密码。

public static byte[] pemToPKCS12(final String keyFile, final String cerFile, final String password) throws Exception {
    // Get the private key
    FileReader reader = new FileReader(keyFile);

    PEMReader pem = new PEMReader(reader, new PasswordFinder() {
        @Override public char[] getPassword() {
            return password.toCharArray();
        }
    });

    PrivateKey key = ((KeyPair)pem.readObject()).getPrivate();

    pem.close();
    reader.close();

    // Get the certificate      
    reader = new FileReader(cerFile);
    pem = new PEMReader(reader);

    X509Certificate cert = (X509Certificate)pem.readObject();

    pem.close();
    reader.close();

    // Put them into a PKCS12 keystore and write it to a byte[]
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    KeyStore ks = KeyStore.getInstance("PKCS12");
    ks.load(null);
    ks.setKeyEntry("alias", (Key)key, password.toCharArray(), new java.security.cert.Certificate[]{cert});
    ks.store(bos, password.toCharArray());
    bos.close();
    return bos.toByteArray();
}

看看org.bouncycastle.crypto.generators.OpenSSLPBEParametersGenerator

As I understand it, OpenSSL has saved files in so-called PEM format. 据我了解,OpenSSL已经以所谓的PEM格式保存了文件。 You need to convert it to Java Key Storage (JKS) format, then work with that format (which is native to Java) to extract files. 您需要将其转换为Java密钥存储(JKS)格式,然后使用该格式(Java本机)来提取文件。 For conversion please use this Google query , it gives pretty good results. 要进行转换,请使用此Google查询 ,它会产生非常好的结果。

Load the JKS file to java.security.KeyStore class. 将JKS文件加载到java.security.KeyStore类。 Then use getCertificate and getKey methods to get the needed information. 然后使用getCertificate和getKey方法获取所需的信息。

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

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