I have my pair of Public and Private keys and my certificate. Those where created in OpenSSL (why? because I was asked to do it in OpenSSL). Now I want to use those things to make a Java app that uses digital signatures. How can I use my private and public keys to encrypt/decrypt info (and use the certificate to see if data is valid? What are the classes in java that allow me to do that?
My keys are in plain text something like this:
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDDuyg3h0VbP9iZ6RCxSU6x4WX4
anAwedMVUTqF0WHlvHl1Kiqa6N6TiUk23uXAVUX8RwLFjXWHlG0xwW7mGByA2mX9
5oPQpQFu8C70aMuUotGv87iiLi0UKCZV+9wS9rMdg5LHu1mMPilwgOO6MlyTxKem
-----END PUBLIC KEY-----
UPDATE
I made this code but still can't use the private key to sign a string.
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 exception I'm gettin' is
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)
... 3 more