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

白昼怎懂夜的黑 提交于 2019-12-05 02:51:59

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.

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

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.

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