Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to decode a Base64 string in Scala or Java?

I have a string encoded in Base64:

eJx9xEERACAIBMBKJyKDcTzR_hEsgOxjAcBQFVVNvi3qEsrRnWXwbhHOmzWnctPHPVkPu-4vBQ==

How can I decode it in Scala language?

I tried to use:

val bytes1 = new sun.misc.BASE64Decoder().decodeBuffer(compressed_code_string)

But when I compare the byte array with the correct one that I generated in Python language, there is an error. Here is the command I used in python:

import base64
base64.urlsafe_b64decode(compressed_code_string)

The Byte Array in Scala is:

(120, -100, 125, -60, 65, 17, 0, 32, 8, 4, -64, 74, 39, 34, -125, 113, 60, -47, -2, 17, 44, -128, -20, 99, 1, -64, 80, 21, 85, 77, -66, 45, -22, 18, -54, -47, -99, 101, -16, 110, 17, -50, -101, 53, -89, 114, -45, -57, 61, 89, 15, -69, -2, 47, 5)

And the one generated in python is:

(120, -100, 125, -60, 65, 17, 0, 32, 8, 4, -64, 74, 39, 34, -125, 113, 60, -47, -2, 17, 44, -128, -20, 99, 1, -64, 80, 21, 85, 77, -66, 45, -22, 18, -54, -47, -99, 101, -16, 110, 17, -50, -101, 53, -89, 114, -45, -57, 61, 89, 15, -69, -18, 47, 5)

Note that there is a single difference in the end of the array

like image 967
Daniel Cukier Avatar asked Jan 23 '14 20:01

Daniel Cukier


People also ask

How do I decode a Base64 string?

To decode with base64 you need to use the --decode flag. With encoded string, you can pipe an echo command into base64 as you did to encode it. Using the example encoding shown above, let's decode it back into its original form. Provided your encoding was not corrupted the output should be your original string.

How do you decode a string in Java?

Decode Basic Base 64 format to Stringdecode(encodedString); String actualString= new String(actualByte); Explanation: In above code we called Base64. Decoder using getDecoder() and then decoded the string passed in decode() method as parameter then convert return value to string.

How do you check whether the string is Base64 encoded or not in Java?

Summary: IsBase64("string here") returns true if string here is Base64-encoded, and it returns false if string here was NOT Base64-encoded. Save this answer.


1 Answers

In Scala, Encoding a String to Base64 and decoding back to the original String using Java APIs:

import java.util.Base64
import java.nio.charset.StandardCharsets

scala> val bytes = "foo".getBytes(StandardCharsets.UTF_8)
bytes: Array[Byte] = Array(102, 111, 111)

scala> val encoded = Base64.getEncoder().encodeToString(bytes)
encoded: String = Zm9v

scala> val decoded = Base64.getDecoder().decode(encoded)
decoded: Array[Byte] = Array(102, 111, 111)

scala> val str = new String(decoded, StandardCharsets.UTF_8)
str: String = foo
like image 62
Garren S Avatar answered Oct 24 '22 03:10

Garren S