java使用RSA私钥错误签名

时间:2015-10-28 11:51:19

标签: java rsa sign

我有一个RSA私钥,我想用我的RSA密钥签署我的文件。但我有一个错误,我不知道如何解决。

我的代码:

 public static void ReadKeysFromFile() throws FileNotFoundException, IOException, NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, NoSuchProviderException, SignatureException{
        FileInputStream keyfis = new FileInputStream("private.key");
        byte[] encKey = new byte[keyfis.available()];
        keyfis.read(encKey);
        keyfis.close();

        PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(encKey);

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privKey = keyFactory.generatePrivate(privKeySpec);
        /* Create a Signature object and initialize it with the private key */

        Signature dsa = Signature.getInstance("SHA1withRSA", "BC");

        dsa.initSign(privKey);
        SignFile(dsa);
}

public static void SignFile(Signature dsa) throws FileNotFoundException, IOException, SignatureException{
     /* Update and sign the data */
        FileInputStream fis = new FileInputStream("test.txt");
        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("sig");
        sigfos.write(realSig);

        sigfos.close();
}

}
我的错误显示:

Exception in thread "main" java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : DerInputStream.getLength(): lengthTag=109, too big.
    at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:217)
    at java.security.KeyFactory.generatePrivate(KeyFactory.java:372)
    at skripsi.signing.GenSig.ReadKeysFromFile(GenSig.java:55)
    at skripsi.signing.GenSig.main(GenSig.java:13)

0 个答案:

没有答案
相关问题