尝试使用MakeCert.exe生成的DSA私钥在java中签名文件时出错

时间:2015-08-05 21:07:29

标签: java signing dsa makecert

我需要使用MakeCert.exe(来自Windows SDK 8)生成DSA私钥,在java中签署一个大文件。

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

pvk是我要签名的私钥。

接下来是我的完整Java代码:

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());
        }
    };
}

我运行的错误是: 捕获异常java.security.spec.InvalidKeySpecException:不正确的密钥规范:IOException:DerInputStream.getLength():lengthTag = 113,太大了。

0 个答案:

没有答案