How to convert sun.misc.BASE64Encoder to org.apache.commons.codec.binary.Base64

天涯浪子 提交于 2019-12-22 04:19:20

问题


I have the following code for sun.misc.BASE64Encoder:

BASE64Decoder decoder = new BASE64Decoder();
byte[] saltArray = decoder.decodeBuffer(saltD);
byte[] ciphertextArray = decoder.decodeBuffer(ciphertext);

and would like to convert it to org.apache.commons.codec.binary.Base64. I've gone through the APIs, the docs, etc., but I can't find something that seems to match and give the same resulting values.


回答1:


It's actually almost the exact same:

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

For decoding:

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

This last one was tougher because you use "toString" at the end.




回答2:


You can use decodeBase64(byte[] base64Data) or decodeBase64(String base64String) methods. For example:

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

Here is a short example:

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"));
    }
}



回答3:


Instead of these two class(import sun.misc.BASE64Encoder; import sun.misc.BASE64Decoder), you can use java.util.Base64 class.Now change encode and decode method as below. For encoding :

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

For decoding:

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

Here ciphertext is the encoded password in encoding method .

Now everything is done, you can save your program and run. It will run without showing any error.



来源:https://stackoverflow.com/questions/16026918/how-to-convert-sun-misc-base64encoder-to-org-apache-commons-codec-binary-base64

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!