package net.suberic.crypto.examples; import net.suberic.crypto.*; import javax.mail.*; import javax.mail.internet.*; import java.util.Set; import java.util.Iterator; import java.security.Key; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; /** * An example of using this API to read an encrypted message. */ public class ReadEncryptedMessage { /** * Runs the Example. */ public static void main(String[] argv) { try { if (argv.length < 3) { System.err.println("usage: ReadEncrytpedMessage filename keystore password"); System.err.println("note: the passphrase for id.p12 (S/MIME) is 'hello world'"); System.err.println("and for bob.skr is 'TestingPassphrase'"); System.exit(-1); } Session mailSession = Session.getDefaultInstance(System.getProperties()); // create the message. FileInputStream fis = new FileInputStream(new File(argv[0])); MimeMessage msg = new MimeMessage(mailSession, fis); // get our encryption utilities. //EncryptionUtils cryptoUtils = EncryptionManager.getEncryptionUtils(msg); String cryptotype = EncryptionManager.checkEncryptionType(msg); EncryptionUtils cryptoUtils = EncryptionManager.getEncryptionUtils(cryptotype); if (cryptoUtils == null) { System.err.println("failed to get encryption utilities."); System.exit(-1); } // load the associated store(s) String keyStore = argv[1]; char[] pw = argv[2].toCharArray(); if (pw.length == 0) pw = null; EncryptionKeyManager keyMgr = cryptoUtils.createKeyManager(); keyMgr.loadPrivateKeystore(new FileInputStream(new File(keyStore)), pw); // we're not sure which key we should use, so let's just go through // each one. Set privateKeys = keyMgr.privateKeyAliases(); Iterator iter = privateKeys.iterator(); MimeMessage decryptedMsg = null; while (decryptedMsg == null && iter.hasNext()) { Key privateKey = keyMgr.getPrivateKey((String) iter.next(), pw); try { decryptedMsg = cryptoUtils.decryptMessage(mailSession, msg, privateKey); } catch (Exception e) { Object o = msg.getContent(); System.err.println("msg.getContent() = " + o + ", a " + o.getClass().getName()); System.err.println("error decrypting message with key " + privateKey + ": " + e); e.printStackTrace(); } } if (decryptedMsg != null) { decryptedMsg.writeTo(System.out); } else { System.out.println("failed to decrypt message."); } } catch (Exception e) { e.printStackTrace(); } } }