Why encoding a string in php and in java is different from each other?



function encrypt($string) 
        $key_para = "AIBL_#0#[email protected]";
        $result = '';
        $test = "";
        for($i=0; $i<strlen($string); $i++) 
            $char = substr($string, $i, 1);                     
            $a = ($i % strlen($key_para))-1;
            $keychar = substr($key_para, $a, 1);

            $inte = ord($char)+ord($keychar); 
            echo $i.'=';
            echo $inte;
            echo '</br>';                  
            $char = chr($inte);

    echo '</br>';
    echo $result;
    $base64t = base64_encode($result);
    $res = urlencode($base64t);
    $f_data = str_replace("%", "_", $res);

    return $f_data;


public static String encrypt(String str) throws UnsupportedEncodingException
    String key_para= "AIBL_#0#[email protected]";
    String result ="";
    for(int i=0; i < str.length(); i++)
        char ch = str.charAt(i);
        int a = (i % key_para.length()) -1 ;
        char keyChar ;
        if(a < 0) {
            keyChar = key_para.charAt(key_para.length()+a);
            } else if(a > 0) {
            keyChar = key_para.charAt(a);
            } else {
            keyChar = key_para.charAt(0);
        int temp = ((int) ch + (int) keyChar);
        ch = (char) temp;
        result += ch;
    String enc=java.util.Base64.getEncoder().encodeToString(result.getBytes());
    String res = URLEncoder.encode(enc, "UTF-8");
    String f_data = res.replace('%','_') ;
    return f_data;

String to be encrypted:


Output should be:


Java Output:


The logic in both the languages is same but their output is different.
What am I doing wrong?




Your code works well, except for one thing: you're calling without argument:

Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.

That's why my output was different than yours.

To fix this, you need to specify the encoding of the bytes. If you specify the ISO 8859-1 charset, it'll work as expected.


If you want to avoid encoding problems, you'd better use bytes instead of characters. A character is in fact a different concept, and needs its own encoding to be represented in bytes. So you could replaceString result byList<Byte> or other form of byte buffer.

People are also looking for solutions to the problem: php - Cannot read image files, css and script libraries using absolute and relative url


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.