vishal vishal - 7 months ago 18
Java Question

Android: Unable to Decrypt Value

Successfully get Right encrypted value but facing problem to decrypt that value(already encrypted).

Value: 123456

Encrpted: ncSzDj4j8l44iM5qgaqHgA==

Why i got java.lang.Exception: [decrypt] Invalid int: "Bo" ?

Is there any solution / Suggestion it would be appreciated. Thanks

MainActivity.java

package iqpo.qxltd.com.encrytiondecryption;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import java.net.URLDecoder;

public class MainActivity extends AppCompatActivity {
ApiCrypter3 apiCrypter;

//123456
//ncSzDj4j8l44iM5qgaqHgA==

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
apiCrypter = new ApiCrypter3();
try {
byte[] encryptedRequest = this.apiCrypter.encrypt(value);
String EncryptStr = new String(encryptedRequest, "UTF-8");
Log.e("ENCRYPTION: ", EncryptStr.toString());

String res = new String(this.apiCrypter.decrypt(EncryptStr), "UTF-8");
res = URLDecoder.decode(res, "UTF-8");
Log.e("DECRYPTION: ", res.toString());

} catch (Exception e) {
e.printStackTrace();
}
}
}


ApiCrypter3.java

package iqpo.qxltd.com.encrytiondecryption;

import android.util.Base64;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class ApiCrypter3 {

private byte[] sessionKey = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6}; //Where you get this from is beyond the scope of this post
private byte[] iv = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 5, 0, 5}; //Ditto
private IvParameterSpec ivspec;
private SecretKeySpec keyspec;
private Cipher cipher;

public ApiCrypter3()
{
ivspec = new IvParameterSpec(iv);
keyspec = new SecretKeySpec(sessionKey, "AES");

try {
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
}
}

public byte[] encrypt(String text) throws Exception
{
if(text == null || text.length() == 0) {
throw new Exception("Empty string");
}
byte[] encrypted = null;
try {
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
encrypted = Base64.encode(cipher.doFinal(text.getBytes("UTF-8")), Base64.DEFAULT);
}
catch (Exception e) {
throw new Exception("[encrypt] " + e.getMessage());
}
return encrypted;
}

public byte[] decrypt(String code) throws Exception
{
if(code == null || code.length() == 0) {
throw new Exception("Empty string");
}
byte[] decrypted = null;
try {
cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
//decrypted = Base64.decode(cipher.doFinal(code.getBytes()),Base64.DEFAULT);
decrypted = Base64.decode(cipher.doFinal(hexToBytes(code)),Base64.DEFAULT);
}
catch (Exception e) {
throw new Exception("[decrypt] " + e.getMessage());
}
return decrypted;
}

public static String bytesToHex(byte[] data) {
if (data==null) {
return null;
}
int len = data.length;
String str = "";
for (int i=0; i<len; i++) {
if ((data[i]&0xFF)<16) {
str = str + "0" + Integer.toHexString(data[i]&0xFF);
}
else {
str = str + Integer.toHexString(data[i]&0xFF);
}
}
return str;
}

public static byte[] hexToBytes(String str) {
if (str==null) {
return null;
}
else if (str.length() < 2) {
return null;
}
else {
int len = str.length() / 2;
byte[] buffer = new byte[len];
for (int i=0; i<len; i++) {
//No effect
//buffer[i] = (byte) Integer.parseInt(str.substring(i*2,i*2+2),16);
buffer[i]=Integer.valueOf(str.substring(i*2,i*2+2),16).byteValue();
}
return buffer;
}
}
}


Logs:

04-29 16:51:25.831 10918-10918/iqpo.qxltd.com.encrytiondecryption W/System: ClassLoader referenced unknown path: /data/app/iqpo.qxltd.com.encrytiondecryption-2/lib/x86_64
04-29 16:51:26.281 10918-10918/iqpo.qxltd.com.encrytiondecryption W/System: ClassLoader referenced unknown path: /data/app/iqpo.qxltd.com.encrytiondecryption-2/lib/x86_64
04-29 16:51:26.364 10918-10918/iqpo.qxltd.com.encrytiondecryption W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
04-29 16:51:26.399 10918-10918/iqpo.qxltd.com.encrytiondecryption E/ENCRYPTION:: ncSzDj4j8l44iM5qgaqHgA==
04-29 16:51:26.399 10918-10918/iqpo.qxltd.com.encrytiondecryption W/System.err: java.lang.Exception: [decrypt] Invalid int: "nc"
04-29 16:51:26.399 10918-10918/iqpo.qxltd.com.encrytiondecryption W/System.err: at iqpo.qxltd.com.encrytiondecryption.ApiCrypter3.decrypt(ApiCrypter3.java:64)
04-29 16:51:26.399 10918-10918/iqpo.qxltd.com.encrytiondecryption W/System.err: at iqpo.qxltd.com.encrytiondecryption.MainActivity.onCreate(MainActivity.java:41)
04-29 16:51:26.399 10918-10918/iqpo.qxltd.com.encrytiondecryption W/System.err: at android.app.Activity.performCreate(Activity.java:6237)
04-29 16:51:26.399 10918-10918/iqpo.qxltd.com.encrytiondecryption W/System.err: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
04-29 16:51:26.399 10918-10918/iqpo.qxltd.com.encrytiondecryption W/System.err: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
04-29 16:51:26.399 10918-10918/iqpo.qxltd.com.encrytiondecryption W/System.err: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
04-29 16:51:26.399 10918-10918/iqpo.qxltd.com.encrytiondecryption W/System.err: at android.app.ActivityThread.-wrap11(ActivityThread.java)
04-29 16:51:26.399 10918-10918/iqpo.qxltd.com.encrytiondecryption W/System.err: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
04-29 16:51:26.399 10918-10918/iqpo.qxltd.com.encrytiondecryption W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
04-29 16:51:26.399 10918-10918/iqpo.qxltd.com.encrytiondecryption W/System.err: at android.os.Looper.loop(Looper.java:148)
04-29 16:51:26.399 10918-10918/iqpo.qxltd.com.encrytiondecryption W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5417)
04-29 16:51:26.399 10918-10918/iqpo.qxltd.com.encrytiondecryption W/System.err: at java.lang.reflect.Method.invoke(Native Method)
04-29 16:51:26.399 10918-10918/iqpo.qxltd.com.encrytiondecryption W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
04-29 16:51:26.399 10918-10918/iqpo.qxltd.com.encrytiondecryption W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
04-29 16:51:26.411 10918-10955/iqpo.qxltd.com.encrytiondecryption D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true

[ 04-29 16:51:26.414 10918:10918 D/ ]
HostConnection::get() New Host Connection established 0x7f58eefbe960, tid 10918


[ 04-29 16:51:26.453 10918:10955 D/ ]
HostConnection::get() New Host Connection established 0x7f58eefbee00, tid 10955
04-29 16:51:26.465 10918-10955/iqpo.qxltd.com.encrytiondecryption I/OpenGLRenderer: Initialized EGL, version 1.4
04-29 16:51:26.565 10918-10955/iqpo.qxltd.com.encrytiondecryption W/EGL_emulation: eglSurfaceAttrib not implemented
04-29 16:51:26.565 10918-10955/iqpo.qxltd.com.encrytiondecryption W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x7f58f6fd2d80, error=EGL_SUCCESS

Answer

It looks like the exception is being thrown by this line in your hexToBytes function, and then caught and rethrown in decrypt:

buffer[i]=Integer.valueOf(str.substring(i*2,i*2+2),16).byteValue();

The problem is that the string you are passing in to the hexToBytes function is Base64 encoded, it's not a hex string, so reading the first two characters as an integer causes an exception.

Change the line in decrypt to this:

decrypted = cipher.doFinal(Base64.decode(code,Base64.DEFAULT)); 

When you encrypt you are encrypting and then Base64 encoding, so when you decrypt you should do it in the reverse order: Base64 decode then decrypt.