I'm having a trouble while I tried to encode a String in Java.
I have the follwing code in C#, and the string Bpz2Gjg01d7VfGfD8ZP1UA==, when I execute C# code I'm getting:
QnB6MkdqZzAxZDdWZkdmRDhaUDFVQT090
public static void Main(string[] args) { string strWord = "Bpz2Gjg01d7VfGfD8ZP1UA=="; byte[] encbuff = Encoding.UTF8.GetBytes(strWord); string strWordEncoded = HttpServerUtility.UrlTokenEncode(encbuff); Console.WriteLine(strWordEncoded); } I'm trying to replicate the previous code in Java, in the first attempt I used the javax.xml.bind.DatatypeConverter Class:
public static void main(String[] args) { String strWord = "Bpz2Gjg01d7VfGfD8ZP1UA=="; byte[] encbuff = strWord.getBytes(StandardCharsets.UTF_8); String strWordEncoded = DatatypeConverter.printBase64Binary(encbuff); System.out.println(strWordEncoded); } But I'm getting the following String ( missing the last zero compared to C# string):
QnB6MkdqZzAxZDdWZkdmRDhaUDFVQT09
In my second attempt I used the BouncyCastle Base64 encoder:
public static void main(String[] args) { String strWord = "Bpz2Gjg01d7VfGfD8ZP1UA=="; byte[] encbuff = strWord.getBytes(StandardCharsets.UTF_8); String strWordEncoded = new String(Base64.encode(encbuff)); System.out.println(strWordEncoded); } But I'm getting the exact same previous String( still missing the last zero):
QnB6MkdqZzAxZDdWZkdmRDhaUDFVQT09
Does anyone know what may be happening?
UrlTokenEncodemethod does some mapping of symbol chars from regular base64 encoding, so they can safely be used in urls, namely it replaces+with-and/with_. This mapping would also be necessary, if you need the exact functionality in Java. However, this does not apply in your case.Convert.ToBase64String(encbuff)method, it will NOT include the extra 0 at the end, thus being the same as the Java equivalents. It looks like theUrlTokenEncodemethod is adding it for some reason.