I'm currently working on RSA encryption and try to encrypt and decrypt using public and private key file stored in assets directory in android project.
Currently, the public key file is in assets/public_key.pem and I use code below to read the file to get the key.
InputStream is = assetManager.open(stringKey);
String publicKeyString= "";
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while (( line= reader.readLine()) != null) {
publicKeyString += line;
}
is.close();
Then I get the publicKeyString value. Then I tried to initialize a PublicKey object with publicKeyString using following code.
PublicKey pubKey = null;
byte[] publicBytes = Base64.decode(publicKeyString, Base64.DEFAULT);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
pubKey = keyFactory.generatePublic(keySpec);
However I got following exception
java.security.spec.InvalidKeySpecException: java.lang.RuntimeException: error:0D0680A8:asn1 encoding routines:ASN1_CHECK_TLEN:wrong tag
I'm not sure if there is something wrong with public key file itself or the code that i use. Any idea?