I have problem when i try to read a .key file. This file is created by a normal java (J2SE) and i read it from android application. When i read this file from android it gives me nothing and i have done some debugging and i noticed that it can't read the file. Also i have checked if i can read the file (using file.canRead())
and it appears that i can't. Notice that i created normal java application (J2SE) with the same code and it worked successfully.
The code I have used is this:
public KeyPair LoadKeyPair(String algorithm, String publicFileName, String privateFileName) {
// Read Public Key.
PublicKey publicKey = null;
PrivateKey privateKey = null;
try {
File filePublicKey = new File(publicFileName);
FileInputStream fis = new FileInputStream(publicFileName); // The program stops here
byte[] encodedPublicKey = new byte[(int) filePublicKey.length()];
fis.read(encodedPublicKey);
fis.close();
// Read Private Key.
File filePrivateKey = new File(privateFileName);
fis = new FileInputStream(privateFileName);
byte[] encodedPrivateKey = new byte[(int) filePrivateKey.length()];
fis.read(encodedPrivateKey);
fis.close();
// Generate KeyPair.
KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(
encodedPublicKey);
publicKey = keyFactory.generatePublic(publicKeySpec);
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(
encodedPrivateKey);
privateKey = keyFactory.generatePrivate(privateKeySpec);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return new KeyPair(publicKey, privateKey);
}