[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Java Source Code Example - Sign and Verify Document with expired certificate



 
    
Java Source Code Example - Sign and Verify Document with expired certificate
============================================================================


/*
* SignVerifyDoc.java
*
* This program
*
*      - sign and verify with digital certificate which in PEM format, and
*        private key in PKCS8, DER format, no matter certificate is validated
*        or has been expired... if you don't use Java KeyStore
*
*  Original: <http://www.comu.de/docs/tomcat_ssl/comu/ImportKey.java>
*
*  Tip: openssl pkcs8 -topk8 -nocrypt -in U.KEY -out U.KEY.der -outform DER
*
*  Date: July 2006
*
*  Author: Terrence Miao <terrence.miao@xxxxxxxxx>
*
*  Version: 1.0
*/

package asic;

import java.io.*;

import java.security.*;
import java.security.spec.*;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;

import java.util.Collection;
import java.util.Iterator;

import asic.util.Base64;


public class SignVerifyDoc {

 /*
  * Creates an InputStream from a file, and fills it with the complete
  * file. Thus, available () on the returned InputStream will return the
  * full number of bytes the file contains
  *
  * @param fname The filename
  * @return The filled InputStream
  * @exception IOException, if the Streams couldn't be created.
  */
 private static InputStream fullStream (String fname) throws IOException {
   FileInputStream fis = new FileInputStream (fname);
   DataInputStream dis = new DataInputStream (fis);
   byte[] bytes = new byte[dis.available ()];

   dis.readFully (bytes);
   ByteArrayInputStream bais = new ByteArrayInputStream (bytes);
   return bais;
 }

 public static void main(String[] args) throws Exception {
   if (args.length != 5) {
     System.out.println(
         "Usage: SignVerifyDoc -s|-v CertificateFile PrivateKeyFile "
+ "messagefile signaturefile");
     return;
   }

   String options = args[0];
   String certfile = args[1];
   String keyfile = args[2];
   String messagefile = args[3];
   String signaturefile = args[4];

/*
   try {
     // loading private key file
     InputStream infile = fullStream (keyfile);
     byte[] key = new byte[infile.available ()];
     infile.read (key, 0, infile.available ());
     infile.close ();
   } catch (Exception ex) {
     ex.printStackTrace ();
   }
*/

   // KeyStore keystore = KeyStore.getInstance (KeyStore.getDefaultType ());
   // keystore.load (new FileInputStream (keystorefile),
storepass.toCharArray ());

   // Signature signature = Signature.getInstance("MD5withRSA");
   // Signature signature = Signature.getInstance("DSA");
   // Signature signature = Signature.getInstance("SHA1withRSA");

   // ASIC use MD5 signature
   Signature signature = Signature.getInstance("MD5withRSA");

   if (options.indexOf("s") != -1) {
     // KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry)
keystore.getEntry (alias, new KeyStore.PasswordProtection
(storepass.toCharArray ()));
     // PrivateKey myPrivateKey = pkEntry.getPrivateKey ();

     // PrivateKey myPrivateKey = (PrivateKey) keystore.getKey
(alias, storepass.toCharArray ());

     // loading key
     FileInputStream infile = new FileInputStream (keyfile);
     int infilelength = infile.available ();
     byte[] key = new byte[infilelength];
     infile.read (key);
     infile.close ();

     String keyString = new String (key);

     // System.out.println ("File lenght is: " + infilelength);
     // System.out.println ("File content is:");
     // System.out.println (keyString);

     PKCS8EncodedKeySpec keyspec = new PKCS8EncodedKeySpec (key);
     // System.out.println (keyspec.getFormat ());

     KeyFactory kf = KeyFactory.getInstance ("RSA");
     PrivateKey myPrivateKey = kf.generatePrivate (keyspec);

     signature.initSign (myPrivateKey);
   }
   else {
     // signature.initVerify (keystore.getCertificate(alias).getPublicKey());

     // loading certificate chain
     FileInputStream fis = new FileInputStream (certfile);
     BufferedInputStream bis = new BufferedInputStream (fis);

     CertificateFactory cf = CertificateFactory.getInstance ("X.509");

/*
     Collection c = cf.generateCertificates (fis);
     Iterator i = c.iterator ();

     while (i.hasNext ()) {
       Certificate cert = (Certificate) i.next();
     }
*/

     while (bis.available () > 0) {
       Certificate cert = cf.generateCertificate (bis);
       // System.out.println (cert.toString ());

       signature.initVerify (cert.getPublicKey ());
     }
   }

   FileInputStream in = new FileInputStream (messagefile);

   byte[] buffer = new byte[8192];
   int length;

   while ((length = in.read (buffer)) != -1)
     signature.update (buffer, 0, length);

   in.close ();

   if (options.indexOf ("s") != -1) {
     FileOutputStream out = new FileOutputStream (signaturefile);
     byte[] raw = signature.sign ();

     // out.write(raw);
     // out.write (Base64.encode (raw).getBytes ());

     String signatureInPEM = new String (Base64.encode (raw));

     for (int i = 1; i <= signatureInPEM.length (); i++) {
       if ((i % 64) == 0) {
         System.out.println (signatureInPEM.charAt (i-1));
         out.write (signatureInPEM.charAt (i-1));
         out.write ('\n');
       }
       else {
         System.out.print (signatureInPEM.charAt (i-1));
         out.write (signatureInPEM.charAt (i-1));
       }
     }

     if ((signatureInPEM.length () % 64 ) != 0) {
       System.out.println ();
       out.write ('\n');
     }

     out.close();
   }
   else {
     FileInputStream sigIn = new FileInputStream (signaturefile);
     byte[] raw = new byte[sigIn.available ()];
     sigIn.read (raw);
     sigIn.close ();
     String rawInString = new String (raw);
     System.out.println ("The signature is:");
     System.out.println (rawInString.replaceAll ("\n", ""));

     // if (signature.verify(raw))
     if (signature.verify (Base64.decode (rawInString.replaceAll ("\n", ""))))
       System.out.println("The signature is good.");
     else
       System.out.println("The signature is bad.");
   }
 }
}

Google