001package edu.pdx.cs410J.security;
002
003import java.io.*;
004import java.security.*;
005import java.security.spec.*;
006
007/**
008 * This program computes the DSA digital signature of a message using
009 * a private key.  The digest is written to a file named
010 * <code>digest.out</code>.
011 */
012public class SignMessage {
013  public static void main(String[] args) {
014    String fileName = args[0];
015    String message = args[1];
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      PKCS8EncodedKeySpec spec = 
025        new PKCS8EncodedKeySpec(encodedKey);
026      KeyFactory factory = 
027        KeyFactory.getInstance("DSA", "SUN");
028      PrivateKey privateKey = factory.generatePrivate(spec);
029
030      // Compute DSA signature
031      Signature sig = Signature.getInstance("DSA");
032
033      sig.initSign(privateKey);
034      sig.update(message.getBytes());
035      byte[] digest = sig.sign();
036
037      FileOutputStream fos = new FileOutputStream("digest.out");
038      fos.write(digest);
039      return;
040
041    } catch (IOException ex) {
042      ex.printStackTrace(System.err);
043
044    } catch (NoSuchProviderException ex) {
045      ex.printStackTrace(System.err);
046
047    } catch (NoSuchAlgorithmException ex) {
048      ex.printStackTrace(System.err);
049
050    } catch (InvalidKeySpecException ex) {
051      ex.printStackTrace(System.err);
052
053    } catch (SignatureException ex) {
054      ex.printStackTrace(System.err);
055
056    } catch (InvalidKeyException ex) {
057      ex.printStackTrace(System.err);
058    }
059
060    System.exit(1);
061  }
062}