0

In C#, I can pass a string to Convert.FromBase64String(String string), which returns a byte[]. Take, for example, the following code:

string key = "lRixPxNRmNOTxB2npoa5zCZR2I/GkuCndWtcRS/w4CI=";
byte[] KeyBytes = Convert.FromBase64String(key);
Console.WriteLine(KeyBytes.Length); //output 32

If I try the same thing in java using the java.util.Base64 library, it looks something like this:

String key = "lRixPxNRmNOTxB2npoa5zCZR2I/GkuCndWtcRS/w4CI=";
byte[] base64KeyBytes = Base64.getEncoder().encode(key.getBytes(UTF_8));
System.out.println(base64KeyBytes.length); //output 60

The Java encode method requires a type byte[] for the argument, and I think this is what my problem stems from.

Is there anyway a way in Java to produce the same output that I'm getting in C#?

2
  • 5
    Surely you want to decode here? Commented Dec 21, 2017 at 23:38
  • Maybe .net version uses platform default encoding that is different than utf-8 such as iso-8859. Commented Dec 21, 2017 at 23:40

2 Answers 2

1

The method Convert.FromBase64String in .NET is used for decoding base64-encoded strings back to plain text. And this is correct since your key string is base64-encoded.

In your Java code excerpt, on the opposite, you are attempting to encode your already-base64-encoded string using the encode method... when you should instead decode it. In order to do it, use the following code:

String key = "lRixPxNRmNOTxB2npoa5zCZR2I/GkuCndWtcRS/w4CI=";
byte[] base64KeyBytes = Base64.getDecoder().decode(key);
System.out.println(base64KeyBytes.length); // 32

You can alternatively use android.util.base64 as follows:

String key = "lRixPxNRmNOTxB2npoa5zCZR2I/GkuCndWtcRS/w4CI=";
byte[] base64KeyBytes = Base64.decode(key, Base64.DEFAULT);
System.out.println(base64KeyBytes.length); // 32
Sign up to request clarification or add additional context in comments.

Comments

0

It should be decode not encode

  String key = "lRixPxNRmNOTxB2npoa5zCZR2I/GkuCndWtcRS/w4CI=";
  byte[] base64KeyBytes  = Base64.getDecoder().decode(key);
  System.out.println(base64KeyBytes .length); //output 32

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.