Encrypt and Decrypt Android String in SharedPreferences - java

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;
}

Related

Image encryption and decryption in android Java AES256

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

Cipher Algorithm AES CBC Insecure Android

I am currently using Cipher cipher = Cipher.getInstance ("AES / CBC / PKCS5Padding") on my Android app.
Those responsible for the security of the app tell me this: "It should also be noted that AES encryption is secure when it is not AES CBC.", so they want me to modify the algorithm.
I tried AES/GCM/NoPadding and AES/CTR/PKCS5Padding, if I uninstall the old version and install it again, the app works, but if I install it on top of a version with CBC I get the following error: javax.crypto.BadPaddingException: pad block corrupted
How can I solve this? I am afraid that if I update the app that is in the store, this error will happen to end users.
Notes:
public static String encrypt (String plaintext, String pwd) {
try {
byte [] salt = generateSalt ();
SecretKey key = deriveKey (salt, pwd);
Cipher cipher = Cipher.getInstance (CIPHER_ALGORITHM);
byte [] iv = generateIv (cipher.getBlockSize ());
IvParameterSpec ivParams = new IvParameterSpec (iv);
cipher.init (Cipher.ENCRYPT_MODE, key, ivParams);
byte [] cipherText = cipher.doFinal (plaintext.getBytes ("UTF-8"));
if (salt! = null) {
return String.format ("% s% s% s% s% s", toBase64 (salt), DELIMITER,
toBase64 (iv), DELIMITER, toBase64 (cipherText));
}
return String.format ("% s% s% s", toBase64 (iv), DELIMITER,
toBase64 (cipherText));
} catch (GeneralSecurityException e) {
throw new RuntimeException (e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException (e);
}
}
public static String decrypt (byte [] cipherBytes, SecretKey key, byte [] iv) {
try {
Cipher cipher = Cipher.getInstance (CIPHER_ALGORITHM);
IvParameterSpec ivParams = new IvParameterSpec (iv);
cipher.init (Cipher.DECRYPT_MODE, key, ivParams);
byte [] plaintext = cipher.doFinal (cipherBytes);
String plainrStr = new String (plaintext, "UTF-8");
return plainrStr;
} catch (GeneralSecurityException e) {
throw new RuntimeException (e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException (e);
}
}
etc...
Update!
I decided to make the code cleaner and here it is for you to understand. My goal was to replace "AES / CBC / PKCS7Padding" with "AES / GCM / NoPadding", as they consider AES with CBC unsafe :(
Questions that arose for this GCM implementation: do I have to use GCMParameterSpec on the cipher? Do I need to import the BouncyCastle provider?
public static final String PBKDF2_DERIVATION_ALGORITHM = "PBKDF2WithHmacSHA1";
private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS7Padding";
//private static final String CIPHER_ALGORITHM = "AES/GCM/NoPadding";
private static String DELIMITER = "]";
private static final int PKCS5_SALT_LENGTH = 8;
private static SecureRandom random = new SecureRandom();
private static final int ITERATION_COUNT = 1000;
private static final int KEY_LENGTH = 256;
public static String encrypt(String plaintext, String pwd) {
byte[] salt = generateSalt();
SecretKey key = deriveKey(pwd, salt);
try {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
byte[] iv = generateIv(cipher.getBlockSize());
IvParameterSpec ivParams = new IvParameterSpec(iv);
cipher.init(Cipher.ENCRYPT_MODE, key, ivParams);
byte[] cipherText = cipher.doFinal(plaintext.getBytes("UTF-8"));
return String.format("%s%s%s%s%s", toBase64(salt), DELIMITER, toBase64(iv), DELIMITER, toBase64(cipherText));
} catch (GeneralSecurityException | UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
public static String decrypt(String ciphertext, String pwd) {
String[] fields = ciphertext.split(DELIMITER);
if (fields.length != 3) {
throw new IllegalArgumentException("Invalid encypted text format");
}
byte[] salt = fromBase64(fields[0]);
byte[] iv = fromBase64(fields[1]);
byte[] cipherBytes = fromBase64(fields[2]);
SecretKey key = deriveKey(pwd, salt);
try {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
IvParameterSpec ivParams = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, key, ivParams);
byte[] plaintext = cipher.doFinal(cipherBytes);
return new String(plaintext, "UTF-8");
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
private static byte[] generateSalt() {
byte[] b = new byte[PKCS5_SALT_LENGTH];
random.nextBytes(b);
return b;
}
private static byte[] generateIv(int length) {
byte[] b = new byte[length];
random.nextBytes(b);
return b;
}
private static SecretKey deriveKey(String pwd, byte[] salt) {
try {
KeySpec keySpec = new PBEKeySpec(pwd.toCharArray(), salt, ITERATION_COUNT, KEY_LENGTH);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(PBKDF2_DERIVATION_ALGORITHM);
byte[] keyBytes = keyFactory.generateSecret(keySpec).getEncoded();
return new SecretKeySpec(keyBytes, "AES");
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
}
private static String toBase64(byte[] bytes) {
return Base64.encodeToString(bytes, Base64.NO_WRAP);
}
public static byte[] fromBase64(String base64) {
return Base64.decode(base64, Base64.NO_WRAP);
}

Android/Java Decryption Block Size Calculation - Cipher functions:EVP_DecryptFinal_ex:WRONG_FINAL_BLOCK_LENGTH

I am getting an error "Cipher functions:EVP_DecryptFinal_ex:WRONG_FINAL_BLOCK_LENGTH" and I am not sure why. Can someone please tell me how to fix this?
Here is how I call it
String encrypted = "E5ADDEB05D9D7B3925B7DE16B560D87C";
String sKey = "3985661DD71D591665BD39476636486B";
This is the procedure
public static String decrypt2(final String sEncryptedMessageBase64,
final String sSymKeyHex,
final String sIvHex)
{
final byte[] byteEncryptedMessage = Base64.decode(sEncryptedMessageBase64, Base64.DEFAULT);
try
{
final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
final SecretKeySpec symKey = new SecretKeySpec(byteSymKeyData, "AES");
final IvParameterSpec iv = new IvParameterSpec(byteIvData);
cipher.init(Cipher.DECRYPT_MODE, symKey, iv);
final byte[] encodedMessage = cipher.doFinal(byteEncryptedMessage);
final String message = new String(encodedMessage, Charset.forName("UTF-8"));
return message;
}
catch (GeneralSecurityException e) {
Log.e("%%%%%", e.getMessage());
throw new IllegalStateException(
"Unexpected exception during decryption", e);
}
}
This is the error I am getting
error:1e06b07b:Cipher functions:EVP_DecryptFinal_ex:WRONG_FINAL_BLOCK_LENGTH
Thanks for any help you can provide

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