我想用Java发送加密的邮件。 BouncyCastle(版本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
返回与给定别名关联的证书链。证书链必须已经通过调用setKeyEntry或通过调用带有PrivateKeyEntry的setEntry与别名相关联。
但是我没有私钥。
另一种方法是使用CertificateFactory.getInstance("X.509");
is there a way to decrypt smime public key data。
但是我只来java.security.cert.CertificateParsingException: signed fields invalid
找到该异常的stackoverflow,但解决方案再次使用KeyStore.getCertificate()
。
我有:适用于Windows信任库中SMIME的证书。该证书在前景中起作用。我可以将证书导出到文件中。
我想要:类型为证书(X509Certificate
)的Java对象,用于带有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;
}