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

发布于 2024-11-17 05:24:26 字数 233 浏览 2 评论 0 原文

我需要java中的非对称加密。我使用自己的密码生成 .key 和 .crt 文件,并通过 openssl 生成 .crt 文件,如 http 中所述://www.imacat.idv.tw/tech/sslcerts.html .
如何使用这些.key和.crt文件在Java中提取公钥和私钥?

I need asymmetric encryption in 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 .
How to use these .key and .crt file to extract publickey and private key in Java?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

落墨 2024-11-24 05:24:26

您的 .key.crt 文件可能采用 PEM 格式。要检查这一点,请使用文本编辑器打开它们,并检查内容是否类似于 -----BEGIN CERTIFICATE------ (或“开始 RSA 私钥”...)。这通常是 OpenSSL 使用的默认格式,除非您明确指定了 DER。

它可能不是必需的(见下文),但如果您的证书是 DER 格式(二进制格式),您可以使用以下方法将它们转换为 PEM 格式:(

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

查看 openssl rsa 的帮助以执行类似的操作如果需要,请使用私钥。)

然后您将获得两个选项:

  • 构建 PKCS#12 文件

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

然后您可以直接从 Java 将其用作“PKCS12”类型的密钥库。大多数 Java 应用程序应该允许您指定除文件位置之外的密钥库类型。对于默认系统属性,这是通过 javax.net.ssl.keyStoreType 完成的(但您正在使用的应用程序可能不使用此属性)。否则,如果您想显式加载它,请使用类似以下内容:(

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();

然后,您应该能够迭代 aliases() .com/javase/6/docs/api/java/security/KeyStore.html" rel="noreferrer">KeyStore 并使用 getCertificate (然后getPublicKey() 表示公钥)和 getKey()

  • 使用 BouncyCastlePEMReader

     FileReader fr = ... // 为 myhost.crt 创建一个 FileReader
     PEMReader pemReader = new PEMReader(fr);
     X509Certificate cert = (X509Certificate)pemReader.readObject();
     公钥 pk = cert.getPublicKey();
     // 关闭读者...
    

对于私钥,如果私钥受密码保护,您需要实现一个 PasswordFinder(请参阅 PEMReader 文档中的链接)来构建 PEMReader。 (您需要将 readObject() 的结果转换为 KeyPrivateKey。)

Your .key and .crt files may be in PEM format. To check this open them with a text editor and check whether the content looks like ------BEGIN CERTIFICATE------ (or "begin RSA private key"...). This is generally the default format used by OpenSSL, unless you've explicitly specified 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:

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.)

You then get two options:

  • Build a PKCS#12 file

    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". Most Java applications should allow you to specify a keystore type in addition to the file location. For the default system properties, this is done with javax.net.ssl.keyStoreType (but the application you're using might not be using this). 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().

  • Use BouncyCastle's PEMReader.

     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. (You'll need to cast the result of readObject() into a Key or PrivateKey.)

旧城空念 2024-11-24 05:24:26

这应该做你想做的事情(使用上面建议的 BouncyCastle PEMReader)——获取 PEM 编码的私钥 + 证书,并输出 PKCS#12 文件。对用于保护私钥的 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();
}

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. Uses the same password for the PKCS12 that was used to protect the private key.

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();
}
东京女 2024-11-24 05:24:26

看一下 org.bouncycastle.crypto.generators.OpenSSLPBEParametersGenerator

Take a look at org.bouncycastle.crypto.generators.OpenSSLPBEParametersGenerator

甜嗑 2024-11-24 05:24:26

据我了解,OpenSSL 以所谓的 PEM 格式保存文件。您需要将其转换为 Java 密钥存储 (JKS) 格式,然后使用该格式(Java 本身的格式)来提取文件。如需转换,请使用此 Google 查询,它会提供相当不错的结果。

将 JKS 文件加载到 java.security.KeyStore 类。然后使用 getCertificate 和 getKey 方法获取所需的信息。

As I understand it, OpenSSL has saved files in so-called PEM format. You need to convert it to Java Key Storage (JKS) format, then work with that format (which is native to Java) to extract files. For conversion please use this Google query, it gives pretty good results.

Load the JKS file to java.security.KeyStore class. Then use getCertificate and getKey methods to get the needed information.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文