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 a signed message. */ public class ReadSignedMessage { /** * Runs the Example. */ public static void main(String[] argv) { try { if (argv.length < 3) { System.err.println("usage: ReadSignedMessage filename keystore password"); System.err.println("note: the passphrase for id.p12 (S/MIME) is 'hello world'"); System.err.println("and for alice.pkr is 'TestingPassphrase'"); System.exit(-1); } Session mailSession = Session.getDefaultInstance(System.getProperties()); // create the message. FileInputStream fis = new FileInputStream(new File(argv[0])); MimeMessage signedMsg = new MimeMessage(mailSession, fis); // get our encryption utilities. //EncryptionUtils cryptoUtils = EncryptionManager.getEncryptionUtils(msg); String cryptotype = EncryptionManager.checkEncryptionType(signedMsg); 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.loadPublicKeystore(new FileInputStream(new File(keyStore)), pw); // we're not sure which key we should use, so let's just go through // each one. Set publicKeys = keyMgr.publicKeyAliases(); Iterator iter = publicKeys.iterator(); boolean goodSignature = false; while (! goodSignature && iter.hasNext()) { String alias = (String) iter.next(); Key publicKey = keyMgr.getPublicKey(alias); try { goodSignature = cryptoUtils.checkSignature(signedMsg, publicKey); if (goodSignature) System.out.println(argv[0] + "'s signature checks out."); else System.out.println(argv[0] + " is not signed by key " + alias); } catch (Exception e) { System.err.println("error checking signature with key " + publicKey + ": " + e); e.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); } } }