I try to use the follow Java code to decrypt a S/MIME message from the JavaMail API:
String mimeType = mail.getContentType();
if( mimeType == null ) {
return mail;
}
ContentType contentType = new ContentType( mimeType );
if( "application/pkcs7-mime".equals( contentType.getBaseType() ) //
&& "smime.p7m".equals( contentType.getParameter( "name" ) ) ) {
Object content = mail.getContent();
if( content instanceof InputStream ) {
CMSEnvelopedDataParser ep = new CMSEnvelopedDataParser( (InputStream)content );
RecipientInformationStore recipients = ep.getRecipientInfos();
Iterator<RecipientInformation> it = recipients.getRecipients().iterator();
RecipientInformation recipient = (RecipientInformation) it.next();
recipient.getContent(new JceKeyTransEnvelopedRecipient(privateKey).setProvider( provider) );
}
}
I have a list of PrivateKeys. How can I find the right PrivateKey to pass in the JceKeyTransEnvelopedRecipient constructor? I think that this should be possible with the RecipientInformation object.
S/MIME messages are usually encrypted using publickey from a certificate specifically an X.509 or PKIX certificate (PKIX is the Internet 'version' or technically profile of X.509) and KeyTransRI -- if that is indeed what you have, your code doesn't check -- or KeyAgreeRI contains a 'recipient id' which actually identifies the certificate; you are expected to map that certificate to the corresponding privatekey, which is how Java crypto normally works (the KeyStore
API stores a privatekey with its corresponding certificate or chain).
RecipientInformation.getRID()
returns a RecipientId
, normally KeyTransRecipientId
or KeyAgreeRecipientId
corresponding to the RecipientInfo
, either of which allows you to get the issuer and serial of the cert, or the 'subject key identifier' an extension in most certs that normally contains a hash of its subject key bit-string value.
Similarly signing is done with the privatekey, and SignerInfo
includes the id of the corresponding certificate, which is distributed to and used by reliers to verify the signature.