8

I have Query parameter that was encoded by btoa javascript function. when url clicked, request function called inside java controller where i wanted to decode Query parameter (which is encoded from javascript btoa). i have tried BASE64Decoder and Base64.getDecoder() but not able to get proper value. is there any other way to do so?

Java Controller

@RequestMapping(value = "decode/{email}", method = RequestMethod.GET)
    public String decodeEmail(Model model, @PathVariable String email){
        Decode decode = new Decode();
        decode.setEmail(email);
        decodeService.save(decode);
        return "decode/List";
    }

JavaScript

var email = document.getElementById("email").value;
var encodedEmail = btoa(email);

Example

String to encode : demo@demo.com

Encoded String : ZGVtb0BkZW1vLmNvbQ==

Krupesh Kotecha
  • 2,396
  • 3
  • 21
  • 40

2 Answers2

27

Java 8 has a new Base64 package:

public void test() {
    String s = "demo@demo.com";
    String encoded = new String(Base64.getEncoder().encode(s.getBytes()));
    String decoded = new String(Base64.getDecoder().decode(encoded));
    System.out.println("S: " + s + " -> " + encoded + " -> " + decoded);
}

prints

S: demo@demo.com -> ZGVtb0BkZW1vLmNvbQ== -> demo@demo.com

There are also other encoder/decoder pairs - you may find the mime encoder appropriate to your needs.

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
  • Why always **new String** is required ? – Cjo Jun 22 '19 at 19:55
  • @OldCurmudgeon I tried String.valueOf() , it didn't work . Any reason ? – Cjo Jun 26 '19 at 06:48
  • 3
    `String encoded = new String(Base64.getEncoder().encode(s.getBytes()));` can be replaced with `String encoded = Base64.getEncoder().encodeToString(s.getBytes());` – Grayson Nov 25 '19 at 14:55
0

The answer for your question is here using apache library : Base64 Encoding in Java

otherwise the implementation from wiki definition will do : https://en.wikipedia.org/wiki/Base64#Sample_Implementation_in_Java

Community
  • 1
  • 1
sexybee
  • 24
  • 5