Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7665471
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T14:34:32+00:00 2026-05-31T14:34:32+00:00

hello fellow programmers, I followed a tutorial at http://www.androidsnippets.com/encrypt-decrypt-between-android-and-php to send a String encrypted

  • 0

hello fellow programmers,

I followed a tutorial at http://www.androidsnippets.com/encrypt-decrypt-between-android-and-php to send a String encrypted by PHP back to my Android client where I want to decrypt it again. The encryption/decryption part is running like a charm on my PHP Server and I’m also able to deliver the encrypted String to my Android Client, but I can’t figure out how to decrypt the String in Android… all I got are some cryptic (haha) signs…

problem description:
I’m sending the IV and Encryption Key I generated on the Android Client via REST Api to my PHP Server which is processing some database queries and encrypting a String with the given IV and Encrytpion Key which is then returned to the Android client.
The Client is able to read out the returned value and to get the encrypted String, BUT the encryption is not acting as awaited…

I followed the upper tutorial strictly but I can’t figure out what the problem would be….

here’s the code for encryption on PHP:

class MCrypt {
private $iv;
private $key;
private $mode;

function __construct() {
    $this->mode = 'cbc';
}

public function setIV($iv) {
    $this->iv = $iv;
}

public function setKey($key) {
    //$this->key = $this->hex2bin($key);
    $this->key = $key;
}

public function getIV() {
    return $this->iv;
}

public function getKey() {
    return $this->key;
}

public function encrypt($value) {
    $iv = $this->iv;
    $td = mcrypt_module_open('rijndael-128', '', $this->mode, $iv);

    mcrypt_generic_init($td, $this->key, $iv);

    $encrypted = mcrypt_generic($td, $value);

    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);

    return bin2hex($encrypted);
}


public function decrypt($value) {
    $value = $this->hex2bin($value);
    $iv = $this->iv;

    $td = mcrypt_module_open('rijndael-128', '', $this->mode, $iv);

    mcrypt_generic_init($td, $this->key, $iv);
    $decrypted = mdecrypt_generic($td, $value);

    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);

    return utf8_encode(trim($decrypted));
}


protected function hex2bin($hexdata) {
    $bindata = '';

    for($i = 0; $i < strlen($hexdata); $i += 2) {
        $bindata .= chr(hexdec(substr($hexdata, $i, 2)));
    }

    return $bindata;
}

}

and here’s how I implemented it:

$value = "some data I want to read out";
// create new MCrypt object
$mcrypt = new MCrypt();
// set IV to hash
$mcrypt->setIV($data['iv']);
// set key to salt
$mcrypt->setKey($data['key']);
// encrypt the key
$enc = $mcrypt->encrypt($value);

return array("data"=>$enc);

So, this is returning the correctly encoded String (tested with the PHP decrypt function, which is decoding the String to the awaited result).

Here’s what the JAVA implementation looks like:
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import android.util.Log;

public class MCrypt {
private static final String TAG = MCrypt.class.getSimpleName();

private String iv;
private String key;
private IvParameterSpec mIvParameterSpec;
private SecretKeySpec mSecretKeySpec;
private Cipher mCipher;

public MCrypt(String iv, String key) {
    Log.v(TAG, "IV Bytes.length=" + iv.getBytes().length);
    this.iv = cut(iv, 16);
    Log.i(TAG, "IV = " + this.iv + ", Bytelength=" + this.iv.getBytes().length);
    this.key = key;

    mIvParameterSpec = new IvParameterSpec(this.iv.getBytes());
    mSecretKeySpec = new SecretKeySpec(this.key.getBytes(), "AES");

    try {
        mCipher = Cipher.getInstance("AES/CBC/NoPadding");
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, "Got Exception while initializing mCipher: " + e.toString(), e);
    } catch (NoSuchPaddingException e) {
        Log.e(TAG, "Got Exception while initializing mCipher: " + e.toString(), e);
    }
}

public String getIV() {
    return this.iv;
}

public byte[] decrypt(String code) throws Exception {
    if(code == null || code.length() == 0) {
        throw new Exception("Emtpy string given");
    }

    byte[] decrypted = null;

    try {
        mCipher.init(Cipher.DECRYPT_MODE, mSecretKeySpec, mIvParameterSpec);
        decrypted = mCipher.doFinal(hexToBytes(code));
    } catch(Exception e) {
        throw new Exception("[decrypt] " + e.getMessage());
    }

    return decrypted;
}

private 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++) {
                buffer[i] = (byte) Integer.parseInt(str.substring(i*2,i*2+2),16);
        }
        return buffer;
    }
}

private String cut(String s, int n) {
    byte[] sBytes = s.getBytes();

    if(sBytes.length < n) {
        n = sBytes.length;
    }

    int n16 = 0;
    boolean extraLong = false;

    int i = 0;

    while(i < n) {
        n16 += (extraLong) ? 2 : 1;
        extraLong = false;

        if((sBytes[i] & 0x80) == 0) {
            i += 1;
        }
        else if((sBytes[i] & 0xC0) == 0x80) {
            i += 2;
        }
        else if((sBytes[i] & 0xE0) == 0xC0) {
            i += 3;
        } else {
            i += 4;
            extraLong = true;
        }
    }
    return s.substring(0, n16);
}
}

If I want now to en/decrypt a String (e.g. “Hello World”) I get this String in return: af8d89fa962794d5b945b74c4b6fd9b6, which is decoded by the PHP implementation to “Hello World”, but JAVA just gives some funny signs…

I know that this is a lot of code but I’d appreciate any help here on this issue!

Thanks in advance for your patience and time to read the thread 😉


So, what I’ve come up so far is that these ‘cryptic’ signs I got instead of the expected decrypted output are actually the address of the byte array itself, even if I try to create a new String from this byte array by using String str = new String(byteArray); I get an output which looks like [B@44e8c0c8… what’s going on here? Any ideas??

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T14:34:33+00:00Added an answer on May 31, 2026 at 2:34 pm

    So, after a long research and (finally) a restart of my computer I found the solution for my problem which I want to share with you:

    first, I changed my hex2Bin(String str) function to the following:

    private byte[] hex2ByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                                 + Character.digit(s.charAt(i+1), 16));
        }
        return data;
    }
    

    after that, I still got the same error over and over again, Android would only show the address of the byte array instead of the decrypted String so I consulted Harry Potter and he told me the magic to be able to get this sorted out, and now I want to share this with you… the most important thing is…. RESTART YOUR COMPUTER if you’re working with Eclipse/Motodev Studio more than a few hours a day – it will save you some time and money, for sure 😉

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to include Core Location and I'm trying to follow this tutorial: http://www.mobileorchard.com/hello-there-a-corelocation-tutorial/
I am follow google's listview tutorial (http://developer.android.com/resources/tutorials/views/hello-listview.html) and I'm trying to ad an adview
CODE HERE: http://jsfiddle.net/B7Y43/ Hello fello programmers, I have the following situation: My PHP-script generates
hello fellow android programmers, I'm constantly running into the same problem over and over
Hello fellow programmers, I have made a function that looks up the database if
Hello fellow programmers, got a few problem here. I am adding a user control
Hello fellow programmers! Recently, I started learning Git, and pretty quickly discovered the amazing
Hello Again my fellow programmers out there, I'm designing and programming from scratch a
Hello fellow developers, I am trying to achieve something in Android and I would
Hello fellow programmers. I have a SQL Server 2005 query that is taking a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.