2

我正在尝试加密一条消息,该消息有效并将其作为字节数组返回。然后我将此字节数组转换为字符串,以便通过 tcp 网络消息发送。另一方面,我将字符串转换回字节数组,但是结果数组更大,我不知道为什么。我认为这可能与编码有关,就好像我使用“MacRoman”一样,我没有这个问题,但是程序需要能够在不支持这种编码的系统上运行,所以我决定使用 UTF -8。

        String message="222233332221";

        //Encrypt message
        byte[] encryptedMsg = encryptString(message, temp.loadCASPublicKey());
        System.out.println("ENCRYPTED MESSAGE byte Length: "+encryptedMsg.length);


        //Convert to String in order to send
        String stringMessage = new String(encryptedMsg);
        System.out.println("ENCRYPTED MESSAGE String Length: "+stringMessage.length());

        //Convert String back to Byte[] and decrpt
        byte[] byteMessage = stringMessage.getBytes("UTF-8");
        System.out.println("ENCRYPTED MESSAGE byte Length: "+byteMessage.length);

输出:

加密消息字节长度:256

加密消息字符串长度:235

加密消息字节长度:446

谁能指出我正确的方向,为什么结果字节数组是 446 字节而不是 256 字节。

encryptString 部分如下。我相信这会在 UTF-8 中返回一个字节数组?

private static byte[] encryptString(String message, Key publicKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);

    byte[] cipherData = cipher.doFinal(message.getBytes("UTF-8"));     
    return cipherData;
}
4

3 回答 3

4

设法使用 Base64 修复它。

        byte[] encryptedMsg = Base64.encodeBase64(encryptString(message, temp.loadCASPublicKey()));


        System.out.println("ENCRYPTED MESSAGE byte Length: "+encryptedMsg.length);


        //Convert to String in order to send
        String stringMessage = new String(encryptedMsg, "UTF-8");
        System.out.println("ENCRYPTED MESSAGE String Length: "+stringMessage.length());

        //Convert String back to Byte[] and decrpt
        byte[] byteMessage = Base64.decodeBase64(stringMessage.getBytes("UTF-8"));
        System.out.println("ENCRYPTED MESSAGE byte Length: "+byteMessage.length);
于 2012-04-24T14:19:16.857 回答
2

It's an encoding issue.

1) You have a byte array. It contains bytes
2) You convert it to a string. As soon as you do this, you have a UTF16 encoded String. So you have taken the bytes and changed them to characters.
3) You now convert those characters back to bytes. But if the original bytes were not UTF8 or UTF16, you might not have the same number of bytes. If the default encoding of the platform is MacRoman, then in step 3 you are translating your UTF16 String into bytes, but treating the characters as MacRoman.

于 2012-04-24T13:28:30.340 回答
0

我想手动进行加密是有充分理由的,但是以防万一……您考虑改用 SSLSocket 吗?

于 2012-04-24T14:08:18.990 回答