001package edu.pdx.cs410J.security;
002
003import java.io.*;
004import java.security.*;
005import java.security.spec.*;
006
007/**
008 * This program verifies that a given message was signed by the person
009 * with a given public key.
010 */
011public class VerifyMessage {
012  public static void main(String[] args) {
013    String fileName = args[0];
014    String digestName = args[1];
015    String message = args[2];
016
017    try {
018      // Read in key from file
019      FileInputStream fis = new FileInputStream(fileName);
020      byte[] encodedKey = new byte[fis.available()];
021      fis.read(encodedKey);
022      fis.close();
023
024      X509EncodedKeySpec spec =
025        new X509EncodedKeySpec(encodedKey);
026      KeyFactory factory =
027        KeyFactory.getInstance("DSA", "SUN");
028      PublicKey publicKey = factory.generatePublic(spec);
029
030      // Read the digest
031      fis = new FileInputStream(digestName);
032      byte[] digest = new byte[fis.available()];
033      fis.read(digest);
034      fis.close();
035
036      // Compute DSA signature
037      Signature sig = Signature.getInstance("DSA");
038
039      sig.initVerify(publicKey);
040      sig.update(message.getBytes());
041      if (sig.verify(digest)) {
042        System.out.println("Success");
043      } else {
044        System.out.println("Failure");
045      }
046      return;
047
048    } catch (IOException ex) {
049      ex.printStackTrace(System.err);
050
051    } catch (NoSuchProviderException ex) {
052      ex.printStackTrace(System.err);
053
054    } catch (NoSuchAlgorithmException ex) {
055      ex.printStackTrace(System.err);
056
057    } catch (InvalidKeySpecException ex) {
058      ex.printStackTrace(System.err);
059
060    } catch (SignatureException ex) {
061      ex.printStackTrace(System.err);
062
063    } catch (InvalidKeyException ex) {
064      ex.printStackTrace(System.err);
065    }
066
067    System.exit(1);
068  }
069}