开发者

Conversion of byte[] into a String and then back to a byte[]

I am working on a proxy server. I am getting data in byte[] which I convert into a String to perform certain operations. Now when i convert this new String back into a byte[] it causes unknown problems.

So mainly its like I need to know how to correctly convert abyte[] into a String and then back into a byte[] again.

I tried to just convert the byte[] to String and then back to byte[] again (to make sure thats its not my operations that are causing problems).

So it's like:

// where reply is a byte[]

String str= new String(reply,0, bytesRead);
streamToClient.write(str.getBytes(), 0, bytesRead);

is not equivalent to

streamToClient.write(reply, 0, bytesRead);

my proxy works fine when开发者_StackOverflow I just send the byte[] without any conversion but when I convert it from byte[] to a String and then back to a byte[] its causes problems.

Can some one please help? =]


The best way to convert a byte[] to String and back into a byte[] is not to do it at all.

If you have to, you must know the encoding that was used to produce the byte[], otherwise the operation uses the platform default encoding, which can corrupt the data because not all encodings can encode all possible strings, and not all possible byte sequences are legal in all encodings. This is what's happening in your case.

As for how to find out the encoding, that depends:

  • If you're using HTTP, look at the Content-Type header
  • If your data is XML, you should be using an XML parser, which will handle the encoding for you
  • If your data is HTML pages, there might also be a <meta http-equiv> header

If there is no way to find out the encoding you have random garbage, not text data.


You will need to know the character encoding used, decode the bytes using that and re-encode using the same character encoding. For example:

String str = new String(reply, 0, Charset.forName("UTF-8"));
bytes[] out = str.getBytes(Charset.forName("UTF-8"));
streamToClient.write(bytes, 0, bytes.length);

If not specified, Java using a default character encoding, which is typically UTF-8 (it may even be mandated as such) but HTML will often be something else. I suspect that's your problem.


If its signed byte array then the simplest solution that I found was encode the byte array with BASE64EncoderStream which will convert it into unsigned bytes. Then you will have to use BASE64DecoderStream to decode the bytes to get back the original signed byte array.

POM Dependency for BASE64 : com.sun.mail javax.mail 1.4.4

public class EncryptionUtils {

private static String ALGO = "AES";
private static  Cipher cipher;




public static String encrypt(String message, String keyString) {
    cipher = Cipher.getInstance(ALGO);
        Key key = generateKey(keyString);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return new String(BASE64EncoderStream.encode(cipher.doFinal( message.getBytes())));
}

public static String decrypt(String message, String keyString)  {

       cipher = Cipher.getInstance(ALGO);
        Key key = generateKey(keyString);
        cipher.init(Cipher.DECRYPT_MODE, key);
        return new String(cipher.doFinal(BASE64DecoderStream.decode(message.getBytes()))); 

}

private static Key generateKey(String keyString) throws NoSuchAlgorithmException {
    byte[] keyBytes = BASE64DecoderStream.decode(keyString.getBytes());
    Key key = new SecretKeySpec(keyBytes, ALGO);
    return key;
}

public static void main(String args[]) {
    byte[] keyValue = new byte[16];
    new SecureRandom().nextBytes(keyValue);
    String key = new String(BASE64EncoderStream.encode(keyValue));
    String message = "test message";
    String enc = encrypt(message, key);
    String dec = decrypt(enc, key);
    System.out.println(dec);
}}


I have a similar problem when reading from a socket and sending to another, but my problem was that I was writing the output with a BufferedOutputStream, when I change this to Output stream it works. I think that there is a problem with the buffer ouput stream.

String mensaje ="what I want to send";
String ip = "192.168.161.165";
int port =  2042;
tpSocket = new Socket(ip, port);
os = tpSocket.getOutputStream();
byte[] myBytes= mensaje.getBytes();
ByteArrayInputStream byarris = new ByteArrayInputStream(myBytes);
int resulta =0;
byte[] bufferOutput= new byte[1];
while((resulta = byarris.read(bufferOutput))!= -1) {
    os.write(bufferOutput);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜