Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top