It is pretty straightforward to generate public/private key pair from raw resource file(s) and use them to encrypt/decrypt in android app. However, the following code DO NOT correctly recover plaintext when it is run with Android-x86-v4.4.4 emulator in VirtualBox. Could anyone please point-out what is wrong with this code (it does not give any error or generate any exceptions): (Changing to Cipher.getInstance("RSA/NONE/NoPadding") is also of no help)
PublicKey mPublicKey = null;
PrivateKey mPrivateKey = null;
String mPlainText = "The quick brown fox jumped over the lazy dog" ;
byte[] mEncryptText = null;
byte[] mDecryptText = null;
try {
InputStream mIS = getResources().openRawResource(R.raw.test1_public_key);
DataInputStream dis = new DataInputStream(mIS);
byte [] keyBytes = new byte [(int) mIS.available()];
dis.readFully(keyBytes);
dis.close();
mIS.close();
X509EncodedKeySpec mX509KeySpec = new X509EncodedKeySpec(keyBytes);
mPublicKey = (KeyFactory.getInstance("RSA")).generatePublic(mX509KeySpec);
Toast.makeText(this, "Publickey generated", Toast.LENGTH_LONG).show();
}
catch(Exception e){
Log.e("onButtondecrypt", "exception", e);
Log.e("onButtondecrypt", "exception: " + Log.getStackTraceString(e));
}
try {
InputStream mIS = getResources().openRawResource(R.raw.test1_private_key);
DataInputStream dis = new DataInputStream(mIS);
byte [] keyBytes = new byte [(int) mIS.available()];
dis.readFully(keyBytes);
dis.close();
mIS.close();
PKCS8EncodedKeySpec mPKCS8keySpec = new PKCS8EncodedKeySpec(keyBytes);
mPrivateKey = (KeyFactory.getInstance("RSA")).generatePrivate(mPKCS8keySpec);
Toast.makeText(this, "PRIVATE key generated", Toast.LENGTH_LONG).show();
}
catch(Exception e){
Log.e("onButtondecrypt", "exception", e);
Log.e("onButtondecrypt", "exception: " + Log.getStackTraceString(e));
}
Toast.makeText(this, mPlainText, Toast.LENGTH_LONG).show();
Toast.makeText(this, "Encrypting with Publickey ...", Toast.LENGTH_LONG).show();
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, mPublicKey);
mEncryptText = cipher.doFinal(mPlainText.getBytes());
Toast.makeText(this, mEncryptText.toString(), Toast.LENGTH_LONG).show();
}
catch(Exception e){
Log.e("onButtondecrypt", "exception", e);
Log.e("onButtondecrypt", "exception: " + Log.getStackTraceString(e));
}
Toast.makeText(this, "Decrypting with PRIVATE key ...", Toast.LENGTH_LONG).show();
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, mPrivateKey);
mDecryptText = cipher.doFinal(mEncryptText);
Toast.makeText(this, mDecryptText.toString(), Toast.LENGTH_LONG).show();
}
catch(Exception e){
Log.e("onButtondecrypt", "exception", e);
Log.e("onButtondecrypt", "exception: " + Log.getStackTraceString(e));
}
Thanks to all.