如何将sun.misc.BASE64Encoder转换为org.apache.commons.codec.binary.Base64

Ste*_*ier 9 java base64 apache-commons-codec

我有以下代码sun.misc.BASE64Encoder:

BASE64Decoder decoder = new BASE64Decoder();
byte[] saltArray = decoder.decodeBuffer(saltD);
byte[] ciphertextArray = decoder.decodeBuffer(ciphertext);
Run Code Online (Sandbox Code Playgroud)

并希望将其转换为org.apache.commons.codec.binary.Base64.我已经浏览了API,文档等,但我找不到似乎匹配的东西并给出相同的结果值.

Ste*_*ier 13

它实际上几乎完全相同:

Base64 decoder = new Base64();
byte[] saltArray = decoder.decode(saltD);
byte[] ciphertextArray = decoder.decode(ciphertext);
Run Code Online (Sandbox Code Playgroud)

用于解码:

String saltString = encoder.encodeToString(salt);
String ciphertextString = encoder.encodeToString(ciphertext);
Run Code Online (Sandbox Code Playgroud)

最后一个更难,因为你最后使用"toString".


ten*_*ica 7

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

byte[] result = Base64.decodeBase64(base64);
Run Code Online (Sandbox Code Playgroud)

这是一个简短的例子:

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"));
    }
}
Run Code Online (Sandbox Code Playgroud)