error trying to sign a file in java using a MakeCert.exe generated DSA private key

171 Views Asked by At

I need to sign a large file in java, using a MakeCert.exe (from from the Windows SDK 8.) generated DSA private key.

makecert.exe -sy 13 -sv C:\SignFile3\dsasign.pvk -pe -r -n "CN=LGS CA" C:\SignFile3\dsasign.crt

The pvk is the private key I want to sign with.

Next my complete Java code:

import java.io.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.DataInputStream;
import java.io.BufferedReader;
import java.io.FileReader;
import java.security.*;
import java.security.spec.*;

class GenSig {
    public static final String PRIVATE_KEY_FILE = "dsasign.pvk";

    public static byte[] fullyReadFile(File file) throws IOException {
        DataInputStream dis = new DataInputStream(new FileInputStream(file));
        byte[] bytesOfFile = new byte[(int) file.length()];
        dis.readFully(bytesOfFile);
        dis.close();
        return bytesOfFile;
    }

    public static void main(String[] args) {
        if (args.length != 1) {
            System.out.println("Usage: GenSig nameOfFileToSign");
        }
        else {
            try { 
                KeyFactory keyFactory = KeyFactory.getInstance("DSA");

                File myfile = new File(PRIVATE_KEY_FILE);
                byte[] decodedprivatekey = fullyReadFile(myfile);
                PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(decodedprivatekey);
                PrivateKey priv = keyFactory.generatePrivate(priKeySpec);

                Signature dsa = Signature.getInstance("SHA1withDSA", "SUN"); 
                dsa.initSign(priv);

                /* Update and sign the data */
                FileInputStream fis = new FileInputStream(args[0]);
                BufferedInputStream bufin = new BufferedInputStream(fis);
                byte[] buffer = new byte[1024];
                int len;
                while (bufin.available() != 0) {
                    len = bufin.read(buffer);
                    dsa.update(buffer, 0, len);
                };

                bufin.close();

                /* Now that all the data to be signed has been read in, generate a signature for it */
                byte[] realSig = dsa.sign();

                /* Save the signature in a file */
                FileOutputStream sigfos = new FileOutputStream("signature.binary");
                sigfos.write(realSig);
                sigfos.close();
            }
        }
        catch (Exception e) {
            System.err.println("Caught exception " + e.toString());
        }
    };
}

The error I get running it is: Caught exception java.security.spec.InvalidKeySpecException: Inappropriate key specification: IOException : DerInputStream.getLength(): lengthTag=113, too big.

0

There are 0 best solutions below