Problem when doing encode and decode of String

0

I would like to know why such methods do not behave in a way that:

  

long2str (str2long (String s)) == String s

   public long[] str2long(String s){
        final byte[] authBytes = s.getBytes(StandardCharsets.UTF_8);
        final String encoded = Base64.getEncoder().encodeToString(authBytes);
        long[] array = new long[encoded.length()];
        int i=0;
        for(char c: encoded.toCharArray()){
            array[i] = (long) c;
//             System.out.print(array[i] + " ");
             i++;
        }
        return array;
    }

// --------------------------------------------- -------------------

public String long2str(long[] array){
    char[] chArray = new char[array.length];
    int i=0;
    for(long c: array){
        chArray[i] = (char) c;
        i++;
    }
    String s = Arrays.toString(chArray);
    final byte[] decoded= Base64.getDecoder().decode(s);
    try {
        s = new String(decoded, "UTF-8");
        return s;
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(Encryption.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

What do I think I'm doing right, would not it just reverse the order of steps to achieve such an effect?

    
asked by anonymous 02.12.2014 / 11:02

1 answer

2

Your long2str method is wrong:

    String s = Arrays.toString(chArray);

That does not do what you want. For example:

    System.out.println(Arrays.toString(str2long("Hello World")));

Show this:

[83, 71, 86, 115, 98, 71, 56, 103, 86, 50, 57, 121, 98, 71, 81, 61]

And this is not a valid base-%% base.

What you wanted is this:

    String s = new String(chArray);

I tested here with this fix, and it worked perfectly.

    
02.12.2014 / 11:19