2014-10-17 38 views
0

我得到了一些編碼的日誌信息,鑄造成一個字符串用於傳輸的目的(演員可能是醜陋的,但它的工作原理)。Base 64解碼字節[]鑄造成一個字符串

我試圖將它轉換回一個byte []爲了解碼它,但它不工作:

byte[] encodedBytes = android.util.Base64.encode((login + ":" + password).getBytes(), NO_WRAP); 
String encoded = "Authentification " + encodedBytes; 

String to_decode = encoded.substring(17); 
byte[] cast1 = to_decode;   // error 
byte[] cast2 = (byte[]) to_decode; // error 
byte[] cast3 = to_decode.getBytes(); 
// no error, but i get something totally different from encodedBytes (the array is even half the size of encodedBytes) 
// and when i decode it i got an IllegalArgumentException 

這3種類型轉換不工作,任何想法?

+1

你不能只是將字符串轉換爲字節[] ...你也不能只是設置它。最後一個將字符串轉換爲字節,但不是來自基本的64位表示。 – Doomsknight 2014-10-17 12:22:58

+0

是的,我知道這是我的問題。即時嘗試讓我的字符串回到基礎的64個表示,所以我可以解碼它。 – 2014-10-17 12:33:40

回答

4

這裏有很多問題。

在一般情況下,你需要使用Base64.decode爲了扭轉Base64.encode結果:

byte[] data = android.util.Base64.decode(to_decode, DEFAULT); 

在一般情況下,你應該總是問自己「我怎麼從X型進行轉換,以Y型? 「當弄清楚如何從Y類型恢復到X類型時。

請注意,您的代碼中也存在拼寫錯誤 - 「身份驗證」應爲「身份驗證」。

但是,你也您的編碼問題 - 你正在創建一個byte[],並使用字符串連接帶,將調用toString()字節數組,這是你想要的東西上。您應該撥打encodeToString。這是一個完整的例子:

String prefix = "Authentication "; // Note fix here... 
// TODO: Don't use basic authentication; it's horribly insecure. 
// Note the explicit use of ASCII here and later, to avoid any ambiguity. 
byte[] rawData = (login + ":" + password).getBytes(StandardCharsets.US_ASCII); 
String header = prefix + Base64.encodeToString(rawData, NO_WRAP); 

// Now to validate... 
String toDecode = header.substring(prefix.length()); 
byte[] decodedData = Base64.decode(toDecode, DEFAULT); 
System.out.println(new String(decodedData, StandardCharsets.US_ASCII)); 
+0

它不工作,這樣做似乎是一樣的:byte [] data = android ... decode(to_decode.getBytes(),DEFAULT); – 2014-10-17 12:30:25

+0

@TheoJouret:它確實*工作。你怎麼確定它沒有? (我強烈建議*不要*調用'to_decode.getBytes()',但我希望這個版本也可以,因爲你調用Base64.decode。) – 2014-10-17 12:31:58

+0

to_decode.getBytes()給我與我最初編碼的字節完全不同,當我嘗試解碼它時,我得到一個IllegalArgumentException。 – 2014-10-17 12:41:02