Problem when doing String Code and Discovery

Asked

Viewed 332 times

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;
}

As far as I’m concerned I’m doing it right, it wouldn’t just be reversing the order of the steps to achieve such an effect?

  • 1

    If you print long2str(str2long(String s)), he is equal to String s?

  • Exception in thread "main" java.lang.IllegalArgumentException: Illegal base64 character 5b I’m already investigating...

1 answer

2

Your method long2str is wrong:

    String s = Arrays.toString(chArray);

This then does not do what you want. For example:

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

Show that:

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

And that’s not a String valid base-64.

What you wanted is this:

    String s = new String(chArray);

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.