01: package org.bouncycastle.mail.smime.examples;
02:
03: import java.io.FileInputStream;
04: import java.security.KeyStore;
05: import java.security.cert.X509Certificate;
06: import java.util.Enumeration;
07: import java.util.Properties;
08:
09: import javax.mail.Session;
10: import javax.mail.internet.MimeBodyPart;
11: import javax.mail.internet.MimeMessage;
12:
13: import org.bouncycastle.cms.RecipientId;
14: import org.bouncycastle.cms.RecipientInformation;
15: import org.bouncycastle.cms.RecipientInformationStore;
16: import org.bouncycastle.mail.smime.SMIMEEnveloped;
17: import org.bouncycastle.mail.smime.SMIMEUtil;
18:
19: /**
20: * a simple example that reads an encrypted email.
21: * <p>
22: * The key store can be created using the class in
23: * org.bouncycastle.jce.examples.PKCS12Example - the program expects only one
24: * key to be present.
25: */
26: public class ReadEncryptedMail {
27: public static void main(String args[]) throws Exception {
28: if (args.length != 2) {
29: System.err
30: .println("usage: ReadEncryptedMail pkcs12Keystore password");
31: System.exit(0);
32: }
33:
34: //
35: // Open the key store
36: //
37: KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
38:
39: ks.load(new FileInputStream(args[0]), args[1].toCharArray());
40:
41: Enumeration e = ks.aliases();
42: String keyAlias = null;
43:
44: while (e.hasMoreElements()) {
45: String alias = (String) e.nextElement();
46:
47: if (ks.isKeyEntry(alias)) {
48: keyAlias = alias;
49: }
50: }
51:
52: if (keyAlias == null) {
53: System.err.println("can't find a private key!");
54: System.exit(0);
55: }
56:
57: //
58: // find the certificate for the private key and generate a
59: // suitable recipient identifier.
60: //
61: X509Certificate cert = (X509Certificate) ks
62: .getCertificate(keyAlias);
63: RecipientId recId = new RecipientId();
64:
65: recId.setSerialNumber(cert.getSerialNumber());
66: recId.setIssuer(cert.getIssuerX500Principal().getEncoded());
67:
68: //
69: // Get a Session object with the default properties.
70: //
71: Properties props = System.getProperties();
72:
73: Session session = Session.getDefaultInstance(props, null);
74:
75: MimeMessage msg = new MimeMessage(session, new FileInputStream(
76: "encrypted.message"));
77:
78: SMIMEEnveloped m = new SMIMEEnveloped(msg);
79:
80: RecipientInformationStore recipients = m.getRecipientInfos();
81: RecipientInformation recipient = recipients.get(recId);
82:
83: MimeBodyPart res = SMIMEUtil.toMimeBodyPart(recipient
84: .getContent(ks.getKey(keyAlias, null), "BC"));
85:
86: System.out.println("Message Contents");
87: System.out.println("----------------");
88: System.out.println(res.getContent());
89: }
90: }
|