Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 605
Stephane Grenier Avatar asked Apr 16 '13 00:04

Stephane Grenier


3 Answers

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.

like image 136
PyDevSRS Avatar answered Oct 11 '22 10:10

PyDevSRS


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.

like image 15
Stephane Grenier Avatar answered Nov 04 '22 00:11

Stephane Grenier


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"));
    }
}
like image 8
tenorsax Avatar answered Nov 04 '22 01:11

tenorsax