I am trying to read a private key from a der file. I am getting the following error in my logcat. And the returned value is empty.
java.security.spec.InvalidKeySpecException: java.lang.RuntimeException: error:0c0000af:ASN.1 encoding routines:OPENSSL_internal:TOO_LONG
I tried searching for situations where this had already happened but could find none. I would like to know what this error means and how I can solve it.
Here is my code:
public static String decryptionWithFile(String encrypted,String privateFile2)throws Exception {
PrivateKey privateKey = getPrivateKey(privateFile2);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] bts = Hex.decodeHex(encrypted.toCharArray());
bts = cipher.doFinal(bts);
bts = getFinalBytesOfDycryptedString(bts);
String decryptedMessage = new String(cipher.doFinal(encrypted.getBytes()));
return new String(bts,"UTF-8");
}
And here is the getPrivateKey(); Method:
private static PrivateKey getPrivateKey(String privateFile2)throws Exception {
File f = new File(privateFile2);
FileInputStream fis = new FileInputStream(f);
DataInputStream dis = new DataInputStream(fis);
byte[] keyBytes = new byte[(int) f.length()];
dis.readFully(keyBytes);
dis.close();
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
RSAPrivateKey privKey = (RSAPrivateKey) keyFactory.generatePrivate(spec);
return privKey;
}
Important Note: I added the .der file to my assets folder and then saved it to a file in Internal Storage in order to access the path - which my function requires. Do you think, anything must have happened to the file during this process? (It worked fine with the Public Key)
The problem turned out to be what I'd guessed. When I was writing the .der file to the Internal Storage, it was getting altered somehow and thus wasn't working.
So instead of that. I directly used the InputStream
returned from getAssets().open(filename) to read the private key. That fixed it.