package com.nailabs.abac.credential; import java.security.*; import java.security.cert.*; import org.w3c.dom.*; import org.apache.xml.security.signature.*; import org.apache.xml.security.exceptions.*; import org.apache.xml.security.transforms.Transforms; import org.apache.xml.security.utils.*; /** * A utility for signing a credential domain document. */ public class SignCredential extends Application { /** signature algorithm is set to DSA */ protected static String SIG_TYPE = XMLSignature.ALGO_ID_SIGNATURE_DSA; /** digest algorithm is SHA-1 */ protected static String DIGEST_TYPE = Constants.ALGO_ID_DIGEST_SHA1; protected static String KEY_PAIR_TYPE = "DSA"; protected PrivateKey privateKey = null; protected PublicKey publicKey = null; protected X509Certificate cert = null; /** * Constructor for the application which reads in an XML document, * parses the doc into a DOM tree, signs the document, and writes * the signed tree into an XML file. Cryptographic material is supplied * by a Java keystore. */ public SignCredential(String argv[]) { super(argv); name = "SignCredential"; parseParameters(); getKeys(); readDoc(); signDoc(); writeDoc(); } private void generateKeyPair() { if(DEBUG) { out.println("Generating random keypair for use in signature"); out.println("(useful for demo purposes only)" ); } try { KeyPairGenerator kpg = KeyPairGenerator.getInstance(KEY_PAIR_TYPE); kpg.initialize(512); KeyPair newKeyPair = kpg.generateKeyPair(); privateKey = newKeyPair.getPrivate(); publicKey = newKeyPair.getPublic(); } catch( java.security.NoSuchAlgorithmException nsae ) { if(DEBUG)nsae.printStackTrace(); } } protected void getKeys() { super.getKeys(); // loads the keystore to a class instance field if( keys == null ) generateKeyPair(); // Generate a random, one-time-use key else { try { cert = (X509Certificate)keyStore.getCertificate(alias); publicKey = cert.getPublicKey(); privateKey = (PrivateKey)keyStore.getKey(alias, password.toCharArray()); } catch( Exception e ) { cert = null; publicKey = null; e.printStackTrace(); } } } protected void signDoc() { try { String baseURI = outXML.toURL().toString(); XMLSignature sig = new XMLSignature(doc, baseURI, SIG_TYPE ); docElement.appendChild( sig.getElement() ); Transforms transforms = new Transforms( doc ); transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE ); transforms.addTransform( Transforms.TRANSFORM_C14N_WITH_COMMENTS ); if( includeTransform ) { sig.addDocument("", transforms, DIGEST_TYPE); } if( includeCert && ( cert != null ) ) { sig.addKeyInfo( cert ); } else if( publicKey != null ) sig.addKeyInfo( publicKey ); sig.sign( privateKey ); } catch( XMLSecurityException xmlse ) { xmlse.printStackTrace(); } catch( java.net.MalformedURLException murle ) { murle.printStackTrace(); } } /** standard main routine for launching the application */ public static void main(String argv[]) { SignCredential sc = new SignCredential(argv); } }