I want to store an encrypted Profile object in SharedPreferences using gson.
Here's my code:
public void saveProfile(Profile newProfile) {
try {
Log.i(C.TAG, newProfile.toString());
SharedPreferences.Editor editor = prefs.edit();
String profileJSONfied = new Gson().toJson(newProfile);
Log.i(C.TAG, profileJSONfied);
byte[] cleartext = profileJSONfied.getBytes(HTTP.UTF_8);
Log.i(C.TAG, cleartext.toString());
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, key);
String encrypedProfile = Base64.encodeToString(cipher.doFinal(cleartext), Base64.DEFAULT);
Log.i(C.TAG, encrypedProfile);
editor.putString(PROFILE, encrypedProfile);
editor.commit();
profile = newProfile;
} catch (Exception e) {
Log.i(C.TAG, e.getMessage());
}
}
public Profile loadProfile() {
try {
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, key);
Log.i(C.TAG, prefs.getString(PROFILE, null));
// byte[] plainTextProfileBytes = Base64.decode(cipher.doFinal(prefs.getString(PROFILE, null).getBytes(HTTP.UTF_8)), Base64.DEFAULT);
byte[] plainTextProfileBytes = Base64.decode(prefs.getString(PROFILE, null).getBytes(HTTP.UTF_8), Base64.DEFAULT);
Log.i(C.TAG, new String(plainTextProfileBytes, HTTP.UTF_8));
profile = new Gson().fromJson(new String(plainTextProfileBytes, HTTP.UTF_8), PROFILE_TYPE);
Log.i(C.TAG, profile.toString());
} catch (Exception e) {
Log.i(C.TAG, e.getMessage());
}
return profile;
}
Here's an output example (ordered by Log's order):
saveProfile:
Profile#4146a1d8
{"email":"aaa","firstName":"aaa","lastName":"aaa","postal":"aaa", etc etc...}
[B#414819b0
+nLS7XhRoIFPBeC11/h6mMz6hFfc8js03QJ8VwVZH+dPBeC11/h6mJ448CLGPNzz+bU669XpAI8VXchYQJr7mgDwHpeoSrP4BMACydjKpC8Q9atbk9xz6HNqDpNOiqaa75hFM+r9pzm55/E2E2tdjz4s5OzNNppAPzmtS69tZAZLPuYt1kvnJehHa6fDt2o5UCv6VukCwvVgt+UDcCqCKvF22Iv6vdMXWTcm
At this point I think everything went as expected. The problem lies below, decipher operation
loadProfile:(backward process)
+nLS7XhRoIFPBeC11/h6mMz6hFfc8js03QJ8VwVZH+dPBeC11/h6mJ448CLGPNzz+bU669XpAI8VXchYQJr7mgDwHpeoSrP4BMACydjKpC8Q9atbk9xz6HNqDpNOiqaa75hFM+r9pzm55/E2E2tdjz4s5OzNNppAPzmtS69tZAZLPuYt1kvnJehHa6fDt2o5UCv6VukCwvVgt+UDcCqCKvF22Iv6vdMXWTcm
�r��xQ��O���z���W��;4�|WY�O���z��8�"�<���:������]�X#�������J�����ʤ/�[��s�sj�N����E3��9���6k]�>,���6�#?9�K�mdK>�-�K�%�Gk�÷j9P+�V���`��p*�*�v؋��Y7&���-A
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 21
If I instead of:
byte[] plainTextProfileBytes = Base64.decode(prefs.getString(PROFILE,null).getBytes(HTTP.UTF_8), Base64.DEFAULT);
I use:
byte[] plainTextProfileBytes = Base64.decode(cipher.doFinal(prefs.getString(PROFILE, null).getBytes(HTTP.UTF_8)), Base64.DEFAULT);
The error will be:
pad block corrupted
What am I missing here?
Thanks for your time.
So, I've found a solution!
For starters I've changed a bit of my code. I've created a myPBEkey class with two methods, encrypt and decrypt, both return a Cipher object with the respective "opmode":
Then I've changed my saveProfile and loadProfile methos code to:
public void saveProfile(Profile newProfile) {
try {
SharedPreferences.Editor editor = prefs.edit();
String profileJSONfied = new Gson().toJson(newProfile);
byte[] encryptedProfile = pbeKey.encrypt().doFinal(profileJSONfied.getBytes(HTTP.UTF_8));
byte[] encryptedProfileBase64 = Base64.encode(encryptedProfile, Base64.DEFAULT);
editor.putString(PROFILE, new String(encryptedProfileBase64, HTTP.UTF_8));
editor.commit();
profile = newProfile;
} catch (Exception e) {
Log.i(C.TAG, e.getMessage());
}
}
public Profile loadProfile() {
if (profile == null) {
try {
byte[] decodedProfileBase64 = Base64.decode(prefs.getString(PROFILE, null), Base64.DEFAULT);
byte[] plainTextProfileBytes = pbeKey.decrypt().doFinal(decodedProfileBase64);
profile = new Gson().fromJson(new String(plainTextProfileBytes, HTTP.UTF_8), PROFILE_TYPE);
} catch (Exception e) {
Log.i(C.TAG, e.getMessage());
}
return profile;
I think what solved the problem was separating the encrypt/decrypt from Base64 encode/decode, so first we encrypt and then encode the encrypted byte[] and finally store it. The same goes when decrypting, first we decode the encrypted base64 profile and then decrypt the decoded byte[]. Voilà!
Thanks for your time, hope it helps you.
Related
I am new in Text file Encryption in Android. And tried so many example of text encryption but i am so confused how to apply.
I have 5 string records from json response and i want to save them in a text file(in External Storage) and in "Encrypted format" . I've tried code of cipher_text_encoding but really confused with lots of classes in it.
Please suggest me either good tutorial for text encryption or give me hint how to encode.
Thanks in advance.
Encryption and Decryption using AES Secret Key Algorithm
Generate AES Secret Key:
public static byte[] generateAesSecretKey(){
String SALT2 = "strong_salt_value";
String username = "user_name";
String password = "strong_password";
byte[] key = (SALT2 + username + password).getBytes();
SecretKey secretKeySpec = null;
try {
MessageDigest sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
secretKeySpec = new SecretKeySpec(key, "AES");
} catch (Exception e) {
e.printStackTrace();
}
return secretKeySpec.getEncoded();
}
Encryption:
public static byte[] encodeFile(byte[] secretKey, byte[] fileData) {
SecretKeySpec skeySpec = new SecretKeySpec(secretKey, "AES");
byte[] encrypted = null;
try {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
encrypted = cipher.doFinal(fileData);
// Now write your logic to save encrypted data to sdcard here
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
return encrypted;
}
Decryption:
public static byte[] decodeFile(byte[] key, byte[] fileData) {
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
byte[] decrypted = null;
try {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
decrypted = cipher.doFinal(fileData);
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalBlockSizeException | BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(Exception e){
// for all other exception
e.printStackTrace();
}
return decrypted;
}
Hope above methods are useful for you!
AS with every beginner it is normal to get confused, instead of do it yourself everything learn to leverage on code reuse or written shared libraries. This will leverage on code abstraction as you are only interested in say Encryption and Decryption of JSON/Sting.
For a Full Document:
https://docs.oracle.com/javase/8/docs/technotes/guides/security/crypto/CryptoSpec.html
For a reusable (Java/Android) library:
https://github.com/alkathirikhalid/security
Simple Usage:
String plainText = "Your String";
String encryptionKey = "Your Encryption Key";
String IV = "Your Initial Vector";
// To Encrypt
String cipherText = AES.encrypt(plainText, encryptionKey, IV);
// To Decrypt returned value same as plainText
String originalText = AES.decrypt(cipherText, encryptionKey, IV);
Cheers.
I'm developing a native android app and hybrid IOS app. I'm encrypting the password before sending the request to BL. Below is my native code.
public String Encrypt (String plain) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException
{
try {
AssetManager assets = context.getAssets();
byte[] key = readFully(
assets.open("encryption.der", AssetManager.ACCESS_BUFFER));
KeySpec publicKeySpec = new X509EncodedKeySpec(key);
KeyFactory kf = KeyFactory.getInstance("RSA");
Key pk = kf.generatePublic(publicKeySpec);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pk);
ByteArrayOutputStream out = new ByteArrayOutputStream();
CipherOutputStream cout = new CipherOutputStream(out, cipher);
try {
cout.write(plain.getBytes(UTF_8));
cout.flush();
}catch (Exception e){
e.printStackTrace();
}finally {
try {
cout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
encrypted = new String(encode(out.toByteArray(), DEFAULT), "UTF-8");
return encrypted;
} catch (IOException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
return null;
}
static byte[] readFully(InputStream inputStream) throws IOException {
InputStream in = new BufferedInputStream(inputStream);
byte[] tmp = new byte[1024];
int readLen, size = 0;
ByteArrayOutputStream out = new ByteArrayOutputStream();
while ((readLen = in.read(tmp)) != -1) {
if (((long) size + readLen) > Integer.MAX_VALUE) {
// woah! did we just ship an app of 2GB?
throw new IllegalStateException("Invalid file. File size exceeds expected "
+ "maximum of 2GB");
}
size += readLen;
out.write(tmp, 0, readLen);
}
return out.toByteArray();
}
I have my key in encryption.der file. Everything works fine in android. Now coming to IOS which I'm using Ionic to develop. I'm not able to achieve the encryption part. I have used the "cryptico" : link : https://github.com/wwwtyro/cryptico/blob/master/README.md .
And finally converting to Base64 like these.
var EncryptionPassword = cryptico.encrypt($scope.userInfo.Password, publicKey);
$scope.encPass = base64.encode(EncryptionPassword.cipher);
But I'm getting ArrayIndexOutOfBound Exception from BL. Can you suggest exact same solution has android for angularjs too. So RSA encrytion works on both IOS and Android.
Create a Service and place your public Key inside that.
.service('Settings', function(){
this.publicKey = 'MIIBIjANBgdcssvsvsfvsfvsfvrefvfvfviuwoihijwfoiw278499080989i09M+KC8MYYOu/NRLmFg85LRrfRszyI/vZ/k8982789uiwbgchdbhU+3joQZoJ3Sxq/GbIIFf/3y4f9DuKI53y1qR2qD4xIskfa9rPVqvBtAu2KSNRd8V4J8RKI2gT2YEA+A3Z0mQq4GBRS8iYmGLqRQyPfNUSankylBrTpOIVFBZORdZehjJMmwl98UynyfnyMIHUIFuhefuibiufbeufbsoijn93fD7nxt+siZryfazn3EAgBaTKTV/U5xIepzDN6ZYJ4qnC93u6erdb1X4m1zU6RGapwzCOPOORTyzw/uWJ8twcODNt0cqVp+sYQIDAQAB';
})
Now in your JS encrypt using public key and JSEncrypt.
var encrypt = new JSEncrypt(); encrypt.setPublicKey(Settings.publicKey);
EncryptionPin = encrypt.encrypt($scope.customerInfo.Pin);
EncryptionPin is the final key.
I have a settings screen where I want the user to fill personal details.
I want to keep them in sharedpreferences.
I would like to encrypt the data before saving in Sharedpreferences.
Only when it is used, it's in another application activity decrypt what exists in sharedpreferences and use it.
For this purpose I encrypted the information in the settings screen and save the string that was encrypted in to sharedpreferences.
In order to Decrypt I need the same privateKey and I do not know how to move it to the other activity. I tried using sharedpreferences but the program was flying.
Would appreciate help
Code:
try{
SharedPreferences.Editor editor =getActivity().getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
afterEncryptCvv = Encrypt((String) newValue,editor);
editor.putString("cvvValue", afterEncryptCvv);
editor.commit();
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
The Encrypt Function:
public static String Encrypt(String plain, SharedPreferences.Editor editor)
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
IllegalBlockSizeException, BadPaddingException
{
kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(1024);
kp = kpg.genKeyPair();
publicKey = kp.getPublic();
privateKey = kp.getPrivate();
Gson gson4 = new Gson();
String json4 = gson4.toJson(privateKey);
editor.putString("privateKey", json4);
cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
encryptedBytes = cipher.doFinal(plain.getBytes());
encrypted = bytesToString(encryptedBytes);
return encrypted;
}
In The second activity:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
try {
Gson gson4 = new Gson();
String json4 = prefs.getString("privateKey", "");
privateKey = gson4.fromJson(json4, PrivateKey.class);
cvvValue = prefs.getString(Cvv, "");
String temp = Decrypt(cvvValue);
cvvValue =temp;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
The Decrypt Function:
public String Decrypt (String result) throws NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException,
BadPaddingException
{
cipher1= Cipher.getInstance("RSA");
cipher1.init(Cipher.DECRYPT_MODE, privateKey);
decryptedBytes = cipher1.doFinal(stringToBytes(result));
decrypted = new String(decryptedBytes);
return decrypted;
}
You should not store the secret key on the internal storage. Someone with a rooted device can extract it easily.
Instead, after generating the key pair, you can save it in Android Key Store (see here: http://developer.android.com/training/articles/keystore.html) and use it when needed.
For example:
KeyStore ks = KeyStore.getInstance("AndroidKeyStore");
ks.load(null);
KeyStore.Entry entry = ks.getEntry(alias, null);
I am confused by this bit of advice from http://developer.android.com/guide/google/play/billing/billing_integrate.html#billing-signatures
To keep your public key safe from malicious users and hackers, do not
embed your public key as an entire literal string. Instead, construct
the string at runtime from pieces or use bit manipulation (for
example, XOR with some other string) to hide the actual key. The key
itself is not secret information, but you do not want to make it easy
for a hacker or malicious user to replace the public key with another
key.
Does this mean that
String one = "thisIs";
String two = "MyKey";
String base64EncodedPublicKey = one + two;
PublicKey key = Security.generatePublicKey(base64EncodedPublicKey);
verified = Security.verify(key, signedData, signature);
is safer than
String base64EncodedPublicKey = "thisIsMyKey";
PublicKey key = Security.generatePublicKey(base64EncodedPublicKey);
verified = Security.verify(key, signedData, signature);
? If not, could you please give me an example in code of how to do this?
Something that involves some serious change of the key is best. Personally, I prefer using encryption, something like this would work. For the key, string together a few parts, and it should help to getting it together. Use encryptKey to get your key encrypted, then delete the real key from the source code, and you should be fairly secure. Better is to somehow get the key from a secure server, but that isn't always an option.
String encryptKey(String input)
{
byte[] inBytes=input.getBytes();
String finalString=null;
try {
Cipher cipher=Cipher.getInstance("AES/CBC/PKCS5Padding");
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] keyBytes=md.digest((KeyPart1+KeyPart2).getBytes());
keyBytes = Arrays.copyOf(keyBytes, 16);
SecretKey key= new SecretKeySpec(keyBytes,"AES");
IvParameterSpec ivSpec = new IvParameterSpec(new byte[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0});
cipher.init(Cipher.ENCRYPT_MODE,key,ivSpec);
byte[] outBytes = new byte[cipher.getOutputSize(inBytes.length)];
//cipher.update(encrypted, 0, encrypted.length, decrypted, 0);
outBytes=cipher.doFinal(inBytes);
finalString=new String(Base64.encode(outBytes,0));
Log.v(TAG,"Encrypted="+finalString);
} catch (NoSuchAlgorithmException e) {
Log.e(TAG,"No Such Algorithm",e);
} catch (NoSuchPaddingException e) {
Log.e(TAG,"No Such Padding",e);
} catch (InvalidKeyException e) {
Log.e(TAG,"Invalid Key",e);
} catch (InvalidAlgorithmParameterException e) {
Log.e(TAG,"Invalid Algorithm Parameter",e);
} catch (IllegalBlockSizeException e) {
} catch (BadPaddingException e) {}
return finalString;
}
String decryptKey(String base64Text)
{
byte[] encrypted=Base64.decode(base64Text,0);
//encrypted=base64Text.getBytes();
String decryptedString=null;
try {
Cipher cipher=Cipher.getInstance("AES/CBC/PKCS5Padding");
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] keyBytes=md.digest((KeyPart1+KeyPart2).getBytes());
keyBytes = Arrays.copyOf(keyBytes, 16);
SecretKey key= new SecretKeySpec(keyBytes,"AES");
IvParameterSpec ivSpec = new IvParameterSpec(new byte[] {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0});
cipher.init(Cipher.DECRYPT_MODE,key,ivSpec);
byte[] decrypted = new byte[cipher.getOutputSize(encrypted.length)];
//cipher.update(encrypted, 0, encrypted.length, decrypted, 0);
decrypted=cipher.doFinal(encrypted);
decryptedString=new String(decrypted);
} catch (NoSuchAlgorithmException e) {
logStackTrace(e);
} catch (NoSuchPaddingException e) {
logStackTrace(e);
} catch (InvalidKeyException e) {
logStackTrace(e);
} catch (InvalidAlgorithmParameterException e) {
logStackTrace(e);
} catch (IllegalBlockSizeException e) {
logStackTrace(e);
} catch (BadPaddingException e) {
logStackTrace(e);
}
return decryptedString;
}
Yes. Although in this case you're just concatenating strings which is not much better. The reason for this is that somebody could easily disassemble your code and access your public key. If you have to reassemble the key, it makes it much more challenging to grab the key out of the disassembled code.
First of all, I've reviewed all the entries on the forum, and I still can not find a solution to my problem.
I have to measure the time it takes to encode and decode a text with DES, and make a comparison with other algorithms.
When I run the code, I have this error: BadPaddingException: pad block corrupted. When I debug, the code fails in this line:
byte [] plaintext = cipher.doFinal (cipherBytes);
I use class Base64 to encode/decode String <--> byte[]
Any idea?
thanks
private static final String CIPHER_ALGORITHM = "DES/ECB/PKCS5Padding";
private static int KEY_LENGTH = 64;
public static SecretKey deriveKeyDES() {
try {
long start = System.currentTimeMillis();
KeyGenerator kgen = KeyGenerator.getInstance("DES");
kgen.init(KEY_LENGTH);
SecretKey result = kgen.generateKey();
long elapsed = System.currentTimeMillis() - start;
return result;
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
}
}
public static String encrypt(String plaintext, SecretKey key) {
try {
long start = System.currentTimeMillis();
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding")
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] cipherText = cipher.doFinal(plaintext.getBytes("UTF-8"));
long elapsed = System.currentTimeMillis() - start;
return toBase64(cipherText);
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
public static String toBase64(byte[] bytes) {
return Base64.encodeToString(bytes, Base64.NO_WRAP).trim();
}
public static String decrypt(String ciphertext, SecretKey key) {
try {
byte[] cipherBytes = fromBase64(ciphertext);
long start = System.currentTimeMillis();
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key);
cipher.update(cipherBytes);
// This is where I get exception
byte[] plaintext = cipher.doFinal(cipherBytes);
String plainrStr = new String(plaintext, "UTF-8").trim();
long elapsed = System.currentTimeMillis() - start;
return plainrStr;
} catch (GeneralSecurityException e) {
throw new RuntimeException(e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
public static byte[] fromBase64(String base64) {
return Base64.decode(base64, Base64.NO_WRAP);
}
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, key);
cipher.update(cipherBytes);
// byte[] plaintext = cipher.doFinal(cipherBytes);
// ^-- You shouldn't pass cipherBytes twice.
// v-- instead use the parameter-less method:
byte[] plaintext = cipher.doFinal();
Padding exception occur when the last cipher text block does not compute to valid plain text. This would happen if last ciphertext block is corrupted or the key is incorrect. For CBC mode it would also happen if the second to last ciphertext was altered (but you are using ECB mode encryption).
In your case, the deriveKeyDES() is always generating a random key. Although we didn't get the actual calls to the security methods, I would presume you use a different key for encryption and decryption. In that case there is a very high chance that the resulting plain text does not contain valid padding bytes.
Rasmus answer certainly points to an error in your code, and it would screw up your timings and return a the plain text two times, but it would not remove the BadPaddingException.
I had the same problem in one source code, and IllegalBlockSizeException in another one.
Solved this two problems by return encoding data like:
public String encrypt(String input) {
try {
byte[] inputBytes = input.getBytes("UTF-8");
byte[] enc = encryptCipher.doFinal(inputBytes);
// and problem was in return encoding. That's how i fixed it
return Base64.encodeToString(enc,Base64.DEFAULT);
.....
}
}
Give u a code for decrypt:
public String decrypt(String input) {
try {
byte[] dec = Base64.decode(input.getBytes(), Base64.DEFAULT);
//here had exception
byte[] utf8 = decryptCipher.doFinal(dec);
return new String(utf8,"UTF8");
} catch (IOException | BadPaddingException | IllegalBlockSizeException e) {
e.printStackTrace();
}
return null;
}
I should submit, that had BadPaddingException and IllegalBlockSizeException
only in decrypt method byte[] utf8 = decryptCipher.doFinal(dec); (u had exeption in the same place: byte[] plaintext = cipher.doFinal(cipherBytes);), but real wrong is in encrypt method(return value)
That's why i recommend u to use that code in encrypt method:
return Base64.encodeToString(enc,Base64.DEFAULT);
P.S Tried to a give full answer on your question.