简体   繁体   中英

How to find the PrivateKey for decrypt smime.p7m message with RecipientInformation?

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 Inte.net '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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM