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

3

9

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.

Torn answered 16/4, 2013 at 0:40 Comment(0)
T
15

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.

Torn answered 16/4, 2013 at 8:37 Comment(2)
Why am I getting The method encodeToString(byte[]) is undefined for the type Base64?Marzi
This method is only available starting from commons-codec-1.4Bowne
E
9

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"));
    }
}
Evonneevonymus answered 16/4, 2013 at 1:8 Comment(1)
What about the salt? This is a key part that I can't seem to get working.Torn
S
4

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.

Shipwright answered 14/3, 2017 at 14:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.