2013-04-16 23 views

回答

11

它實際上幾乎完全一樣:

Base64 decoder = new Base64(); 
byte[] saltArray = decoder.decode(saltD); 
byte[] ciphertextArray = decoder.decode(ciphertext); 

對於解碼:

String saltString = encoder.encodeToString(salt); 
String ciphertextString = encoder.encodeToString(ciphertext); 

這最後一個比較困難,因爲你使用「toStri ng「結尾。

+1

爲什麼我得到'方法encodeToString(byte [])未定義爲類型Base64'? – Danijel

+0

此方法僅適用於從commons-codec-1.4開始 – fabdouglas

6

您可以使用decodeBase64(byte[] base64Data)decodeBase64(String base64String)方法。例如:

byte[] result = Base64.decodeBase64(base64); 

下面是一個簡單的例子:

import java.io.IOException; 
import org.apache.commons.codec.binary.Base64; 
import sun.misc.BASE64Encoder; 
import sun.misc.BASE64Decoder; 

public class TestCodec { 

    public static void main(String[] args) throws IOException { 
     String test = "Test BASE64Encoder vs Base64"; 

//  String encoded = new BASE64Encoder().encode(test.getBytes("UTF-8")); 
//  byte[] result = new BASE64Decoder().decodeBuffer(encoded); 

     byte[] encoded = Base64.encodeBase64(test.getBytes("UTF-8")); 
     byte[] result = Base64.decodeBase64(encoded); 

     System.out.println(new String(result, "UTF-8")); 
    } 
} 
+0

鹽怎麼樣?這是我看起來無法工作的關鍵部分。 –

+0

@StephaneGrenier是'saltD'一個字符串?什麼不起作用? – tenorsax

2

而不是這兩個類(import sun.misc.BASE64Encoder; import sun.misc.BASE64Decoder),你可以使用java.util.Base64類。現在改變編碼和解碼方法如下。 對於編碼:

String ciphertextString = Base64.getEncoder().encodeToString(ciphertext); 

對於解碼:

final byte[] encryptedByteArray = Base64.getDecoder().decode(ciphertext); 

這裏密文是在編碼方法所編碼的密碼。

現在一切都完成了,你可以保存你的程序並運行。它將運行而不顯示任何錯誤。