if (args.length != 2)
{
System.err.println("usage: ReadEncryptedMail pkcs12Keystore password");
System.exit(0);
}
//
// Open the key store
//
KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
ks.load(new FileInputStream(args[0]), args[1].toCharArray());
Enumeration e = ks.aliases();
String keyAlias = null;
while (e.hasMoreElements())
{
String alias = (String)e.nextElement();
if (ks.isKeyEntry(alias))
{
keyAlias = alias;
}
}
if (keyAlias == null)
{
System.err.println("can't find a private key!");
System.exit(0);
}
//
// find the certificate for the private key and generate a
// suitable recipient identifier.
//
X509Certificate cert = (X509Certificate)ks.getCertificate(keyAlias);
RecipientId recId = new RecipientId();
recId.setSerialNumber(cert.getSerialNumber());
recId.setIssuer(cert.getIssuerX500Principal().getEncoded());
//
// Get a Session object with the default properties.
//
Properties props = System.getProperties();
Session session = Session.getDefaultInstance(props, null);
MimeMessage msg = new MimeMessage(session, new FileInputStream("encrypted.message"));
SMIMEEnveloped m = new SMIMEEnveloped(msg);
RecipientInformationStore recipients = m.getRecipientInfos();
RecipientInformation recipient = recipients.get(recId);
MimeBodyPart res = SMIMEUtil.toMimeBodyPart(recipient.getContent(ks.getKey(keyAlias, null), "BC"));
System.out.println("Message Contents");
System.out.println("----------------");
System.out.println(res.getContent());