2013-04-11 161 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; 
    }