Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encoding/decoding of data between PHP/Java for Android

I have to decode a base64 encoded data received from a PHP server.

The server uses 'base64_encode' to encode the data.

In my Android app, I use android.utils.Base64 class to do the decoding.

original encrypted data = "†+Ü]M(‡=ñö"
Base64 encoding data in PHP gives - "hisP3F1NBCgIAocQCD3x9g=="
Base64 encoding data in Android gives - "4oCgKw/DnF1NBCgIAuKAoRAIPcOxw7Y="

As you can see, the Java encoded string is longer than the PHP encoded string. I need to find out their default encoding formats.

How to get the same encoded string from both?

Java/Android code :

String encrypted = "†+Ü]M(‡=ñö";
byte[] encoded = Base64.encode(encrypted.getBytes(), Base64.DEFAULT);
String str = new String(encoded); //str = "4oCgKw/DnF1NBCgIAuKAoRAIPcOxw7Y="  
like image 317
Ronnie Avatar asked Mar 01 '13 11:03

Ronnie


1 Answers

Try this in Java: This will give you the long version of the string (UTF-8)

byte[] encoded = Base64.encode(encrypted.getBytes("UTF-8"), Base64.DEFAULT);
String str = new String(encoded, "UTF-8");

Updated:

Try this in Java: This will give you the short version of the string (CP1252)

// This should give the same results as in PHP
byte[] encoded = Base64.encode(encrypted.getBytes("CP1252"), Base64.DEFAULT);
String str = new String(encoded, "CP1252");

Alternatively try this PHP Script:

file: test.php

<?php

echo base64_encode($_GET['str'])." Default UTF-8 version<br />";
echo base64_encode(iconv("UTF-8","CP1252",$_GET['str']))." CP1252 Version <br />";

?>

usage: http://[SOMEDOMAIN]/test.php?str=†+Ü]M(‡=ñö
like image 62
Shehabic Avatar answered Sep 23 '22 13:09

Shehabic