I am trying to encrypt some sample text from a private key file that has been generated with a SHA-256 with RSA password. This private key has been generated from Verisign (CA authority) and passed to us.
Here is the code I am using:
public class EncryptionUtil {
public static final String ALGORITHM = "RSA";
public static final String PRIVATE_KEY_FILE = "C:\\keys\\private.key";
public static byte[] encrypt(String text, PrivateKey key) {
byte[] cipherText = null;
try {
final Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);
cipherText = cipher.doFinal(text.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
return cipherText;
}
public static void main(String[] args) {
try {
final String originalText = "This is a test";
// Encrypt
final PrivateKey privateKey = readPrivateKey(new File(
PRIVATE_KEY_FILE));
final byte[] cipherText = encrypt(originalText, privateKey);
// Printing
System.out.println("Original: " + originalText);
System.out.println("Encrypted: " + cipherText.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
private static PrivateKey readPrivateKey(File file) throws IOException,
GeneralSecurityException {
DataInputStream input = new DataInputStream(new FileInputStream(file));
try {
byte[] bytes = new byte[(int) file.length()];
input.read(bytes);
KeySpec spec = new PKCS8EncodedKeySpec(bytes);
try {
return KeyFactory.getInstance("RSA").generatePrivate(spec);
} catch (InvalidKeySpecException ex) {
return KeyFactory.getInstance("DSA").generatePrivate(spec);
}
} finally {
input.close();
}
}
}
But at the return KeyFactory.getInstance("RSA").generatePrivate(spec);
(and also return KeyFactory.getInstance("DSA").generatePrivate(spec);
line) I got the following error:
java.security.spec.InvalidKeySpecException: Inappropriate key specification: invalid key format
at sun.security.provider.DSAKeyFactory.engineGeneratePrivate(DSAKeyFactory.java:156)
at java.security.KeyFactory.generatePrivate(KeyFactory.java:372)
Do you know what I am missing?
My private key looks like:
-----BEGIN ENCRYPTED PRIVATE KEY-----
base64 private key
-----END ENCRYPTED PRIVATE KEY-----
So I tried to decode64 the byte array and now got the following error:
java.security.spec.InvalidKeySpecException: Inappropriate key specification: IOException : DER input, Integer tag error
at sun.security.provider.DSAKeyFactory.engineGeneratePrivate(DSAKeyFactory.java:156)
at java.security.KeyFactory.generatePrivate(KeyFactory.java:372)
When the private key is not encrypted the previous code works perfectly.