I've been writing some code to sign data. So far this is what I have
public void encryptHash(String hashToEncrypt, String pathOfKey, String Algorithm) {
FileInputStream fis = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len;
File f = new File(pathOfKey);
fis = new FileInputStream(pathOfKey);
len = 0;
while((len = fis.read()) != -1){
baos.write(len);
}
KeyFactory kf = KeyFactory.getInstance(Algorithm); //Algorithm = "RSA"
KeySpec keySpec = new PKCS8EncodedKeySpec(baos.toByteArray());
baos.close();
PrivateKey privateKey = kf.generatePrivate(keySpec); //Here's the exception thrown
Signature rsaSigner = Signature.getInstance("SHA1withRSA");
rsaSigner.initSign(privateKey);
fis = new FileInputStream(hashToEncrypt);
BufferedInputStream bis = new BufferedInputStream(fis);
byte[] buffer = new byte[1024];
len = 0;
while((len = bis.read(buffer)) >= 0){
try {
rsaSigner.update(buffer, 0, len);
} catch (SignatureException ex) {
Logger.getLogger(DataEncryptor.class.getName()).log(Level.SEVERE, null, ex);
}
}
bis.close();
byte[] signature = rsaSigner.sign();
System.out.println(new String(signature));
}
The problem is that I'm getting the following exception and I can't find infomation about it.
dic 09, 2011 12:49:02 PM firmaelectronica.DataEncryptor encryptHash
Grave: null
java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : DER input, Integer tag error
at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:217)
at java.security.KeyFactory.generatePrivate(KeyFactory.java:372)
at firmaelectronica.DataEncryptor.encryptHash(DataEncryptor.java:40)
at firmaelectronica.FirmaElectronica.main(FirmaElectronica.java:39)
Caused by: java.security.InvalidKeyException: IOException : DER input, Integer tag error
at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:361)
at sun.security.pkcs.PKCS8Key.decode(PKCS8Key.java:367)
at sun.security.rsa.RSAPrivateCrtKeyImpl.<init>(RSAPrivateCrtKeyImpl.java:91)
at sun.security.rsa.RSAPrivateCrtKeyImpl.newKey(RSAPrivateCrtKeyImpl.java:75)
at sun.security.rsa.RSAKeyFactory.generatePrivate(RSAKeyFactory.java:316)
at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(RSAKeyFactory.java:213)
What does
DER input, Integer tag error means? How can I read a
password-protected PKCS8 DER private key to sign a file?
Thanks so much in advance !!!!!
Edited by: 879653 on 09-dic-2011 15:44