本文介绍了从.key和.cer文件实例化java.security类PrivateKey和X509Certificate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最初的目标是:

生成一个https网址,其中一个参数是PKCS7分离签名(RSA,SHA-256,UTF-8,BASE64).

Generate a https url where one of parameters is PKCS7 detached signature (RSA, SHA-256, UTF-8, BASE64).

我拥有什么:

  1. 私钥(.key文件以"----- BEGIN RSA PRIVATE KEY -----"开头,这样结束"kIng0BFt5cjuur81oQqGJgvU + dC4vQio + hVc + eAQTGmNQJV56vAHcq4v----- END RSA PRIVATE KEY -----)
  2. 自签名证书(.cer文件以"----- BEGIN CERTIFICATE -----"开头,这样结束"xwRtGsSkfOFL4ehKn/K7mgQEc1ZVPrxTC7C/g + 7grbKufvqNmsYW4w ==----- END CERTIFICATE -----)
  3. 要签名的数据

我找到了可以满足我所需的Java代码.

I found a java code that do almost what I need.

方法签名:

 public static String sign(PrivateKey privateKey,
                           X509Certificate certificate,
                           String data);

现在,我被困在如何从给定文件中获取PrivateKey和X509Certficiate类.

Now I'm stuck on how to get PrivateKey and X509Certficiate classes from given files.

我看了很多例子,对这些时刻感到困惑:

I looked at many examples and got confused by these moments:

1.

KeyStore ks = KeyStore.getInstance("pkcs12");

PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);

找不到PKCS7标准的替代品.

Didn't find alternatives for PKCS7 standard.

  1. 使用bouncycastle库构建PrivateKey的方法的摘要:

  1. A snippet of method that builds PrivateKey using bouncycastle library:

    inputStream = Files.newInputStream(privateKeyFile.toPath());
    reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
    pemParser = new PEMParser(reader);
    PEMDecryptorProvider decryptorProvider = new JcePEMDecryptorProviderBuilder()
            .setProvider(PROVIDER)
            .build(privateKeyPassword.toCharArray());
    PEMEncryptedKeyPair encryptedKeyPair = (PEMEncryptedKeyPair) pemParser.readObject();
    PEMKeyPair keyPair = encryptedKeyPair.decryptKeyPair(decryptorProvider);
    ...

在此示例中,我必须向PEMDecryptorProvider提供一些privateKeyPassword.该密码的目的是什么?我在哪里可以得到它?

In this example I have to provide some privateKeyPassword to PEMDecryptorProvider. What is the point of this password and where can I get it?

从keyPair值中,我可以同时获得privateKey和publicKey.

From keyPair value I can get both privateKey and publicKey.

PEMKeyPair的publicKey与我的证书之间有什么关系?他们是一样的吗?

What is the connection between publicKey from PEMKeyPair and my certificate ? Are they the same?

任何帮助将不胜感激,谢谢!

Any help will be appreciated, thanks!

推荐答案

由于Java的CertificateFactory直接支持.cer文件的格式,因此您不需要bouncycastle即可读取公共密钥.

You don't need bouncycastle to read in the public key as Java's CertificateFactory directly supports the format of your .cer file.

私钥似乎是openssl可以产生的PKCS1格式.如果您希望保留该格式,请此答案说明如何提取私钥.结合这两个,这是读取证书和私钥的简短代码段.

The private key appears to be in a PKCS1 format that openssl can produce. If you wish to keep that format this answer shows how to extract the private key. Combining the two, here is a short snippet to read in a certificate and a private key.

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;

import java.io.FileInputStream;
import java.io.FileReader;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.Security;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

public class Main {

    private static PrivateKey readPrivateKey(String filename) throws Exception {
        PEMParser pemParser = new PEMParser(new FileReader(filename));
        JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
        PEMKeyPair pemKeyPair = (PEMKeyPair) pemParser.readObject();
        KeyPair kp = converter.getKeyPair(pemKeyPair);
        return kp.getPrivate();
    }

    private static X509Certificate readCertificate(String filename) throws Exception {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        return (X509Certificate) certificateFactory.generateCertificate(new FileInputStream(filename));
    }

    public static void main(String[] args) throws Exception {
        Security.addProvider(new BouncyCastleProvider());
        PrivateKey privateKey = readPrivateKey("myKey.priv");
        X509Certificate cert = readCertificate("mycert.cer");
    }
}

这篇关于从.key和.cer文件实例化java.security类PrivateKey和X509Certificate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-27 13:42