Image encryption and decryption in android Java AES256 - java

I am trying to fetch image from the camera & want to encrypt that bitmap and want to store that bitmap in internal storage in encrypted format and store path of that file in Sqlite DB also want to decrypt that file from path receiving from the Sqlite DB.
Using code following.
For Camera I Am using normal camera code
and found a bitmap mImageCaptureBitmap
for encryption and decryption we use following.
private static String Key = "key#123";
public static byte[] encryptString(String stringToEncode) throws NullPointerException {
try {
SecretKeySpec skeySpec = getKey(Key);
byte[] clearText = stringToEncode.getBytes("UTF8");
final byte[] iv = new byte[16];
Arrays.fill(iv, (byte) 0x00);
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivParameterSpec);
byte[] encryptedValue = cipher.doFinal(clearText);
return encryptedValue;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String decryptString(String stringToEncode) throws NullPointerException {
try {
SecretKeySpec skeySpec = getKey(Key);
final byte[] iv = new byte[16];
Arrays.fill(iv, (byte) 0x00);
IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivParameterSpec);
byte[] cipherData = cipher.doFinal(Base64.decode(stringToEncode.getBytes("UTF-8"),
Base64.DEFAULT));
String decoded = new String(cipherData, "UTF-8");
return decoded;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static SecretKeySpec getKey(String password) throws UnsupportedEncodingException {
int keyLength = 256;
byte[] keyBytes = new byte[keyLength / 8];
Arrays.fill(keyBytes, (byte) 0x0);
byte[] passwordBytes = password.getBytes("UTF-8");
int length = passwordBytes.length < keyBytes.length ? passwordBytes.length : keyBytes.length;
System.arraycopy(passwordBytes, 0, keyBytes, 0, length);
SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
return key;
}
for storing file in local
public static void storeFile(Bitmap bitmap, String filename, Context ctx
,String ID,String type){
ContextWrapper cw = new ContextWrapper(ctx);
File directory = cw.getDir("IntegratorApp", Context.MODE_PRIVATE);
File file = new File(directory, filename);
DatabaseHelper mdaDatabaseHelper = new DatabaseHelper(ctx);
mdaDatabaseHelper.insertDocData(leadID,file.getAbsolutePath(),docType);
try {
StorageUnit.saveImage(ctx,bitmap,filename);
} catch (IOException e) {
e.printStackTrace();
}
}
I don't know where I am doing wrong but the image is not stored in db in encrypted format.
Thanks in advance

Related

Encrypt and Decrypt Android String in SharedPreferences

i need to save and load String savedText in SharedPreferences so I need to encrypt and decrypt my string. I save my string at saveText() and load at loadText(String UNIC). UNIC is an ID to save my string. I have this code, It works, but it doesn't crypt.
private void saveText() throws GeneralSecurityException, IOException {
for (int i = 0; i < myArr.size(); i++) { //here i create my string
SAVEDITEMS = SAVEDITEMS + myArr.get(i).replace("✔", "") + "&";
}
KeyGenParameterSpec keyGenParameterSpec = MasterKeys.AES256_GCM_SPEC;
String masterKeyAlias = MasterKeys.getOrCreate(keyGenParameterSpec);
String fileToWrite = SAVEDITEMS;
//getFilesDir() is ok? is was variable directory at documentation
try {
EncryptedFile encryptedFile = new EncryptedFile.Builder(
new File(getApplicationContext().getFilesDir(), fileToWrite),
getApplicationContext(),
masterKeyAlias,
EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB
).build();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
encryptedFile.openFileOutput()));
writer.write("MY SUPER-SECRET INFORMATION");
} catch (GeneralSecurityException gse) {
// Error occurred getting or creating keyset.
} catch (IOException ex) {
// Error occurred opening file for writing.
}
sPref = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor ed = sPref.edit();
ed.putString(UNIC, SAVEDITEMS);
ed.commit();
}
private void loadText(String UNIC) throws GeneralSecurityException, IOException {
KeyGenParameterSpec keyGenParameterSpec = MasterKeys.AES256_GCM_SPEC;
String masterKeyAlias = MasterKeys.getOrCreate(keyGenParameterSpec);
String fileToRead = SAVEDITEMS;
EncryptedFile encryptedFile = new EncryptedFile.Builder(
new File(getApplicationContext().getFilesDir(), fileToRead),
getApplicationContext(),
masterKeyAlias,
EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB
).build();
StringBuffer stringBuffer = new StringBuffer();
try (BufferedReader reader =
new BufferedReader(new FileReader(String.valueOf(encryptedFile)))) {
String line = reader.readLine();
while (line != null) {
stringBuffer.append(line).append('\n');
line = reader.readLine();
}
} catch (IOException e) {
// Error occurred opening raw file for reading.
} finally {
String contents = stringBuffer.toString();
}
sPref = getPreferences(MODE_PRIVATE);
String savedText = sPref.getString(UNIC, SAVEDITEMS);
//here i toast my string
Toast toast = Toast.makeText(getApplicationContext(),
savedText, Toast.LENGTH_SHORT);
toast.show();
}
}
Help me please, is the problem at the getFilesDir() or somewhere else? Thanks for any help. It is really important for me.
You can use Hawk, it supports encryption and decryption of data and uses shared prefs to store the encrypted data.
Here's the flow:
(source: https://github.com/orhanobut/hawk)
You can encrypt and decrypt your string using these methods and save the results in your SharedPreferences:
public static byte[] encrypt(byte[] plaintext, SecretKey key, byte[] IV) throws Exception
{
Cipher cipher = Cipher.getInstance("AES");
SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES");
IvParameterSpec ivSpec = new IvParameterSpec(IV);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
byte[] cipherText = cipher.doFinal(plaintext);
return cipherText;
}
And for descryption:
public static String decrypt(byte[] cipherText, SecretKey key, byte[] IV)
{
try {
Cipher cipher = Cipher.getInstance("AES");
SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES");
IvParameterSpec ivSpec = new IvParameterSpec(IV);
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
byte[] decryptedText = cipher.doFinal(cipherText);
return new String(decryptedText);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

Java: How to convert String to base64string?

I am using this method to decrypt my incoming messages:
private static String decrypt(String key, String initVector, String dataToDecrypt) {
try {
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
String safeString = dataToDecrypt.replace('-', '+').replace('_', '/');
byte[] decodedString = Base64.decodeBase64(safeString);
byte[] original = cipher.doFinal(decodedString);
return new String(original);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
However, my Android app crashes, showing the following exception:
java.lang.NoSuchMethodError: No static method
decodeBase64(Ljava/lang/String;)[B in class
Lorg/apache/commons/codec/binary/Base64; or its super classes
(declaration of 'org.apache.commons.codec.binary.Base64' appears in
/system/framework/ext.jar)
accordingly, the method decodeBase64 takes base64string, but I pass string. Here comes my question:
How to convert String to base64string ?!
Please note that I am trying to DECODE not ENCODE. Almost all the solutions provided are for the encoding part which is not my worry.
P.S.: I am developing an Android-app on Android-Studio
try this:
Base64.encodeToString(mStringToEncode.getBytes(), Base64.NO_WRAP)
it exist many encoding mode use autocompletion to see more Base64.NO_WRAP, Base64.CRLF, etc...
you need to import package:
import android.util.Base64;
public static String toBase64(String value){
if (value == null)
value = "";
return Base64.encodeToString(value.trim().getBytes(), android.util.Base64.DEFAULT);
}
Have you check this answer
// decode data from base 64
private static byte[] decodeBase64(String dataToDecode)
{
byte[] dataDecoded = Base64.decode(dataToDecode, Base64.DEFAULT);
return dataDecoded;
}
//enconde data in base 64
private static byte[] encodeBase64(byte[] dataToEncode)
{
byte[] dataEncoded = Base64.encode(dataToEncode, Base64.DEFAULT);
return dataEncoded;
}
Try this code
private static String encryptNew(String key, String initVector, String dataToEncrypt) throws Exception{
byte[] plainTextbytes = dataToEncrypt.getBytes("UTF-8");
byte[] keyBytes = key.getBytes("UTF-8");
byte[] IvkeyBytes = initVector.getBytes("UTF-8");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(IvkeyBytes);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
plainTextbytes = cipher.doFinal(plainTextbytes);
return Base64.encodeToString(plainTextbytes, Base64.DEFAULT);
}
private static String decrypt(String key, String initVector, String dataToDecrypt) {
try {
byte[] cipheredBytes = Base64.decode(dataToDecrypt, Base64.DEFAULT);
byte[] keyBytes = key.getBytes("UTF-8");
byte[] IvkeyBytes = initVector.getBytes("UTF-8");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
SecretKeySpec secretKeySpecy = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(IvkeyBytes);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpecy, ivParameterSpec);
cipheredBytes = cipher.doFinal(cipheredBytes);
return new String(cipheredBytes,"UTF-8");
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}

How to encrypt a stringbuilder message using AES algorithm in java

I have a stringBuilder message appended with "||" symbol.(Ex: Hi||How||are||26 04 2016||finish) i have to encrypt the message and send it to the server using AES and decrypt the same at the server side. Can anyone help me out in solving this?
You can encrypt and decrypt like this:
public class AES {
public static byte[] encrypt(String key, String initVector, String value) {
try {
IvParameterSpec vector = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, secretKey, vector);
byte[] encrypted = cipher.doFinal(value.getBytes());
System.out.println("encrypted string: "+ Base64.encodeBase64(encrypted));
return Base64.encodeBase64(encrypted);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static String decrypt(String key, String initVector, byte[] encrypted) {
try {
IvParameterSpec vector = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKey, vector);
byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));
return new String(original);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static void main(String[] args) {
String key = "Foo12345Bar67890"; // 128 bit key
String initVector = "RandomInitVector"; // 16 bytes IV
StringBuilder sb = new StringBuilder("Hi||How||are||26 04 2016||finish"); //Your Text here
byte[] encryptedBytes = encrypt(key, initVector, sb.toString());
System.out.println(decrypt(key, initVector,encryptedBytes));
}
}

Decryption of file fails: javax.crypto.BadPaddingException: pad block corrupted

I've created a ZIP-File on my pc (I compressed it with the os x zipper in the finder) and after that I encrypted it with my java program:
public class ResourceEncrypter {
static byte[] salt = { (byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c,
(byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99 };
public static void main(String[] args) {
new ResourceEncrypter().encryptAllFiles();
System.out.println("Okay, done");
}
private byte[] getKey() {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(salt);
kgen.init(128, sr);
SecretKey skey = kgen.generateKey();
byte[] key = skey.getEncoded();
return key;
} catch(Exception e) {
e.printStackTrace();
}
return null;
}
private void encryptAllFiles() {
try {
byte[] key = getKey();
//Take a list of files and encrypt each file...
String srcFilesPath = System.getProperty("user.dir") + "/srcFiles";
String encryptedSrcFilesPath = System.getProperty("user.dir") + "/encryptedSrcFiles";
File[] listOfFiles = new File(srcFilesPath).listFiles();
for(int i = 0; i < listOfFiles.length; ++i) {
if(listOfFiles[i].getAbsolutePath().contains(".zip")) {
//Encrypt this file!
byte[] data = Files.readAllBytes(Paths.get(listOfFiles[i].getAbsolutePath()));
byte[] encryptedData = ResourceEncrypter.encrypt(key, data);
String filename = listOfFiles[i].getName();
System.out.println("Write result to " + encryptedSrcFilesPath + "/" + filename);
FileOutputStream output = new FileOutputStream(encryptedSrcFilesPath + "/" + filename);
output.write(encryptedData);
output.close();
}
}
} catch(Exception e) {
e.printStackTrace();
}
}
private static byte[] encrypt(byte[] key, byte[] data) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encryptedData = cipher.doFinal(data);
return encryptedData;
}
So, this takes any zip file encrypts it and saves the result to another folder.
Now, I got an android app and I put the encrypyted zip file into an asset folder main/assets/pic.zip.encrypted.
In my android app I do the following:
public class MainActivity extends AppCompatActivity {
static byte[] salt = { (byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c,
(byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99 };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
decryptZipFile();
}
private byte[] getKey() {
try {
//Create the key for the encryption/decryption
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(salt);
kgen.init(128, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
byte[] key = skey.getEncoded();
return key;
} catch(Exception e) {
e.printStackTrace();
}
return null;
}
private static byte[] decrypt(byte[] key, byte[] encryptedData) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(key,"AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encryptedData);
return decrypted;
}
public void decryptZipFile() {
// First decrypt the zip file
try {
InputStream is = getResources().getAssets().open("pics.zip.encrypted");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int count;
while ((count = is.read(buffer)) != -1)
baos.write(buffer, 0, count);
byte[] encryptedData = baos.toByteArray();
byte[] decryptedData = decrypt(getKey(), encryptedData);
} catch(Exception e) {
e.printStackTrace();
}
}
When I now try to decrypt my zip file with this code I get the following error:
09-23 18:41:21.117 30799-30799/demo.zip.app.zipapp W/System.err﹕ javax.crypto.BadPaddingException: pad block corrupted
09-23 18:41:21.117 30799-30799/demo.zip.app.zipapp W/System.err﹕ at com.android.org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineDoFinal(BaseBlockCipher.java:854)
09-23 18:41:21.117 30799-30799/demo.zip.app.zipapp W/System.err﹕ at javax.crypto.Cipher.doFinal(Cipher.java:1340)
09-23 18:41:21.117 30799-30799/demo.zip.app.zipapp W/System.err﹕ at demo.zip.app.zipapp.MainActivity.decrypt(MainActivity.java:63)
However, when I apply the same methods for decrypting on my PC it works fine.
What is happening here?
Okay, I found the solution.
The problem is that SecureRandom and in particular the setSeed method works differently on Android than on normal Java.
So, instead you should not construct a key from a salt key as I do above. Instead you should go to the PC and get the key from private byte[] getKey() as a Base64 string object. Then the key looks something like this in my case: n9dReP+BPwHWGCLpDQe+MQ== and then copy an paste this into the android method which becomes this:
private byte[] getKey() {
byte[] key = Base64.decode(new String("n9dReP+BPwHWGCLpDQe+MQ==").getBytes(), 0);
return key;
}
That's it.

How to resolve "javax.crypto.IllegalBlockSizeException: last block incomplete in decryption" in this code

I read a lot of stuff explaining how to resolve this kind of exception but i am still unable to resolve this.
My target is :
1. Encrypt String data using SecretKey and store it into SQLite database.
2. read data from SQLite database and decrypt it using the same SecretKey.
This is my class to encrypt and decrypt data in android application (implementation of target 1 & 2). This code is giving exception -- javax.crypto.IllegalBlockSizeException: last block incomplete in decryption
How can i solve this error ? Any sugestion will be appreciated.. Thanks
public class Cryptography {
private String encryptedFileName = "Enc_File2.txt";
private static String algorithm = "AES";
private static final int outputKeyLength = 256;
static SecretKey yourKey = null;
SQLiteDatabase database;
DBHelper helper;
Context context;
//saveFile("Hello From CoderzHeaven testing :: Gaurav Wable");
//decodeFile();
public Cryptography (Context context) {
this.context = context;
helper = new DBHelper(context);
database = helper.getWritableDatabase();
}
public String encryptString(String data) {
char[] p = { 'p', 'a', 's', 's' };
//SecretKey yourKey = null;
byte[] keyBytes = null;
byte[] filesBytes = null;
try {
if(this.yourKey == null) {
Log.d("key", "instance null");
Cursor cursor = database.query("assmain", new String[]{"keyAvailability"}, null, null, null, null, null);
cursor.moveToFirst();
if(cursor.getInt(cursor.getColumnIndex("keyAvailability")) == 1) {
Log.d("key", "exists in DB");
keyBytes = cursor.getBlob(cursor.getColumnIndex("key"));
cursor.close();
filesBytes = encodeFile(keyBytes, data.getBytes());
} else {
Log.d("key", "generating");
this.yourKey = generateKey(p, generateSalt().toString().getBytes());
filesBytes = encodeFile(this.yourKey, data.getBytes());
}
} else {
Log.d("key", "instance exists");
//yourKey = this.yourKey;
filesBytes = encodeFile(yourKey, data.getBytes());
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return new String(filesBytes);
}
public String decryptString(String data) {
String str = null;
byte[] decodedData = null;
try {
Log.d("To decrypt", data);
if(this.yourKey == null) {
Log.d("key", "null");
Cursor cursor = database.query("assmain", new String[]{"keyAvailability"}, null, null, null, null, null);
cursor.moveToFirst();
if(cursor.getInt(cursor.getColumnIndex("keyAvailability")) == 1) {
Log.d("key", "exists in DB");
byte[] keyBytes = cursor.getBlob(cursor.getColumnIndex("key"));
cursor.close();
decodedData = decodeFile(keyBytes, data.getBytes());
} else {
Log.d("key", "Unavailable");
Toast.makeText(context, "Key Unavailable", Toast.LENGTH_SHORT).show();
}
} else {
Log.d("key", "instance exists");
decodedData = decodeFile(this.yourKey, data.getBytes());
}
decodedData = decodeFile(yourKey, data.getBytes());
str = new String(decodedData);
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
public static SecretKey generateKey(char[] passphraseOrPin, byte[] salt)
throws NoSuchAlgorithmException, InvalidKeySpecException {
// Number of PBKDF2 hardening rounds to use. Larger values increase
// computation time. You should select a value that causes computation
// to take >100ms.
final int iterations = 1000;
// Generate a 256-bit key
//final int outputKeyLength = 256;
SecretKeyFactory secretKeyFactory = SecretKeyFactory
.getInstance("PBKDF2WithHmacSHA1");
KeySpec keySpec = new PBEKeySpec(passphraseOrPin, salt, iterations,
outputKeyLength);
yourKey = secretKeyFactory.generateSecret(keySpec);
return yourKey;
}
public static SecretKey generateSalt() throws NoSuchAlgorithmException {
// Generate a 256-bit key
//final int outputKeyLength = 256;
SecureRandom secureRandom = new SecureRandom();
// Do *not* seed secureRandom! Automatically seeded from system entropy.
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(outputKeyLength, secureRandom);
SecretKey key = keyGenerator.generateKey();
return key;
}
public static byte[] encodeFile(SecretKey yourKey, byte[] fileData)
throws Exception {
byte[] data = yourKey.getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(data, 0, data.length,
algorithm);
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(fileData);
return encrypted;
}
public static byte[] encodeFile(byte[] data, byte[] fileData)
throws Exception {
//byte[] data = yourKey.getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(data, 0, data.length,
algorithm);
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(fileData);
return encrypted;
}
public static byte[] decodeFile(SecretKey yourKey, byte[] fileData)
throws Exception {
byte[] data = yourKey.getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(data, 0, data.length,
algorithm);
//Cipher cipher = Cipher.getInstance(algorithm);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(fileData);
return decrypted;
}
public static byte[] decodeFile(byte[] data, byte[] fileData)
throws Exception {
//byte[] data = yourKey.getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(data, 0, data.length,
algorithm);
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(fileData);
return decrypted;
}
}
This is error snippet
07-01 14:50:48.230: W/System.err(11715): javax.crypto.IllegalBlockSizeException: last block incomplete in decryption
07-01 14:50:48.230: W/System.err(11715): at com.android.org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineDoFinal(BaseBlockCipher.java:705)
07-01 14:50:48.230: W/System.err(11715): at javax.crypto.Cipher.doFinal(Cipher.java:1111)
07-01 14:50:48.230: W/System.err(11715): at com.cdac.authenticationl3.Cryptography.decodeFile(Cryptography.java:170)
07-01 14:50:48.230: W/System.err(11715): at com.cdac.authenticationl3.Cryptography.decryptString(Cryptography.java:95)
You are using AES/ECB/PKCS5Padding for decrypting the file but not while encrypting the file.
Add AES/ECB/PKCS5Padding for the encryption process as well. So it should be
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
Hope this helps

Categories

Resources