2013-04-11 122 views
1

我试图编码byte[]String,然后解码该Stringbyte[],我的代码是:的Java使用Base64编码和解码

byte[] aaa = new byte[1]; 
aaa[0] = (byte) 153; 

String encoder = Base64.encodeBase64String(aaa); 
System.out.println("encoder <<>> " + encoder); 

// Decode the Base64 String.   
byte[] bytes = Base64.decodeBase64(encoder); 
String decoder = new String(bytes, "UTF08"); 
System.out.println("decoder <<>> " + decoder); 

结果是:

encoder <<>> mQ== 
decoder <<>> ? 

结果是不一样的。为什么会发生?

+3

当然它是不一样的。您正在将该字节解释为UTF-8,而您想要做的是打印出字节的值。 – nhahtdh 2013-04-11 04:29:01

+0

像nhatdh说的,只是做: System.out.println(“解码器<<>>”+ bytes [0]); – ebolyen 2013-04-11 04:31:44

+0

我试过了,打印字节的值,结果是-103,代码是: – TonyChou 2013-04-11 04:43:40

回答

1

试试这个:

byte[] aaa = new byte[1]; 
aaa[0] = (byte) 153; 
System.out.println("original bytes <<>> " + Arrays.toString(aaa)); 

// Encode the bytes to Base64 
String encoder = Base64.encodeBase64String(aaa); 
System.out.println("encoder <<>> " + encoder); 

// Decode the Base64 String to bytes 
byte[] bytes = Base64.decodeBase64(encoder); 
System.out.println("decoded bytes <<>> " + Arrays.toString(bytes)); 
+0

感谢您的快速响应,我试了一下,打印结果是:原始字节<<>> [-103] 编码器<<>> mQ == 解码字节<<>> [-103]我不知道为什么?我能为这个问题做些什么? – TonyChou 2013-04-11 04:45:41

+0

@TonyChou - 这其实是正确的。 Java字节总是带符号的数量。最大字节值是+127。当你将153转换为一个字节时,它会变为0x99。 (当数值在Java中溢出时,它们只是默默地在允许的范围内环绕。)最后,0x99在二进制补码中是-103。如果你需要看到一个正值,你需要做一些像'byteValue&0xff'。这会将'byteValue'提升为'int',然后屏蔽可能发生的任何符号扩展。 – 2013-04-11 04:51:28

+0

非常感谢你!它现在可以工作。 – TonyChou 2013-04-11 07:04:00

0

简单的静态实用方法来编码和解码给定的字符串。

import javax.crypto.Cipher; 
import javax.crypto.spec.SecretKeySpec; 
... 

private static byte[] key = { 
     0x74, 0x68, 0x69, 0x73, 0x49, 0x73, 0x41, 0x53, 0x65, 0x63, 0x72, 0x65, 0x74, 0x4b, 0x65, 0x79 
    }; // "ThisIsASecretKey"; 

    public static String encrypt(String stringToEncrypt) throws Exception { 
    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); 
     final SecretKeySpec secretKey = new SecretKeySpec(key, "AES"); 
     cipher.init(Cipher.ENCRYPT_MODE, secretKey); 
     final String encryptedString = Base64.encodeBase64String(cipher.doFinal(stringToEncrypt.getBytes())); 
     return encryptedString; 
    } 

    public static String decrypt(String stringToDecrypt) throws Exception { 
    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING"); 
     final SecretKeySpec secretKey = new SecretKeySpec(key, "AES"); 
     cipher.init(Cipher.DECRYPT_MODE, secretKey); 
     final String decryptedString = new String(cipher.doFinal(Base64.decodeBase64(stringToDecrypt))); 
     return decryptedString; 
    }