如何在没有私钥的情况下获取将邮件加密到 Java 的证书?

How to get Certificate for encrypting mail into Java without private key?

我想在 java 中发送加密邮件。 BouncyCastle (Release 1.6.4) 似乎很流行这样做。在他们的示例 "CreateLargeEncryptedMail.java" 中,您会发现:

/**
 * a simple example that creates a single encrypted mail message.
 * <p>
 * The key store can be created using the class in
 * org.bouncycastle.jce.examples.PKCS12Example - the program expects only one
 * key to be present in the key file.
 * <p>
 * Note: while this means that both the private key is available to
 * the program, the private key is retrieved from the keystore only for
 * the purposes of locating the corresponding public key, in normal circumstances
 * you would only be doing this with a certificate available.
 */
public class CreateLargeEncryptedMail
{
    public static void main(
        String args[])
        throws Exception
    {
        if (args.length != 3)
        {
            System.err.println("usage: CreateLargeEncryptedMail pkcs12Keystore password inputFile");
            System.exit(0);
        }

        //
        // Open the key store
        //
        KeyStore    ks = KeyStore.getInstance("PKCS12", "BC");
        String      keyAlias = ExampleUtils.findKeyAlias(ks, args[0], args[1].toCharArray());

        Certificate[]   chain = ks.getCertificateChain(keyAlias);

但是 ks.getCertificateChain() 没有私钥就无法工作,通常我没有收件人的私钥。 在我的尝试中,它返回 null。来自 documentation

Returns the certificate chain associated with the given alias. The certificate chain must have been associated with the alias by a call to setKeyEntry, or by a call to setEntry with a PrivateKeyEntry.

但是我没有私钥

另一种方法是使用 CertificateFactory.getInstance("X.509"); is there a way to decrypt smime public key data.

但我只是来 java.security.cert.CertificateParsingException: signed fields invalid

发现 Whosebug 到该异常,但解决方案再次使用 KeyStore.getCertificate()

我有: Windows 信任库中适合 SMIME 的证书。该证书在 outlook 中有效。我可以将证书导出到文件中。

我想要:一个 java 证书类型的对象 (X509Certificate) 为带有 BounceCastle 的 SMIME 工作。

那么我必须使用哪种工具创建什么样的文件以及在 Java 中做什么才能初始化此 X509Certificate?我需要该文件中的单个证书还是链?证书是自签名的。

BouncyCastle 不仅支持 SMIME 加密,还包含一个 CertificateFactory,它可以加载我从 Windows certmgr 导出的 p7b 文件。对于导出,我选择了不带私钥和带钥匙链的方式。该文件对我有用:

import org.bouncycastle.jcajce.provider.asymmetric.x509.CertificateFactory;
...

    /**
     * Reads the Certificate from the file with filename.
     * Works for p7b-files.
     * @param filename the name and path of a key-file.
     * @return a Certificate
     */
    public static Certificate getCertificate(String filename) {
        Certificate cert = null;
        try (InputStream is = new FileInputStream(filename)) {
            CertificateFactory fact = new CertificateFactory();
            cert = fact.engineGenerateCertificate(is);
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
        return cert;
    }