CreateEncryptedMail.javaAPI DocBouncy Castle Crypto API 1.41 (Java 1.5)3711Wed Oct 01 10:55:28 BST 2008org.bouncycastle.mail.smime.examples


public class CreateEncryptedMail extends Object
a simple example that creates a single encrypted mail message.

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.

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.

Fields Summary
Constructors Summary
Methods Summary
public static voidmain(java.lang.String[] args)

        if (args.length != 2)
            System.err.println("usage: CreateEncryptedMail pkcs12Keystore password");

        // 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!");

        Certificate[]   chain = ks.getCertificateChain(keyAlias);

        // create the generator for creating an smime/encrypted message
        SMIMEEnvelopedGenerator  gen = new SMIMEEnvelopedGenerator();

        // create a subject key id - this has to be done the same way as
        // it is done in the certificate associated with the private key
        // version 3 only.
        MessageDigest           dig = MessageDigest.getInstance("SHA1", "BC");

        gen.addKeyTransRecipient(cert.getPublicKey(), dig.digest());
        // create the base for our message
        MimeBodyPart    msg = new MimeBodyPart();

        msg.setText("Hello world!");

        MimeBodyPart mp = gen.generate(msg, SMIMEEnvelopedGenerator.RC2_CBC, "BC");
        // Get a Session object and create the mail message
        Properties props = System.getProperties();
        Session session = Session.getDefaultInstance(props, null);

        Address fromUser = new InternetAddress("\"Eric H. Echidna\"<>");
        Address toUser = new InternetAddress("");

        MimeMessage body = new MimeMessage(session);
        body.setRecipient(Message.RecipientType.TO, toUser);
        body.setSubject("example encrypted message");
        body.setContent(mp.getContent(), mp.getContentType());

        body.writeTo(new FileOutputStream("encrypted.message"));