Base64: java.lang.IllegalArgumentException: Illegal character









up vote
8
down vote

favorite
1












I'm trying to send a confirmation email after user registration. I'm using the JavaMail library for this purpose and the Java 8 Base64 util class.



I'm encoding user emails in the following way:



byte encodedEmail = Base64.getUrlEncoder().encode(user.getEmail().getBytes(StandardCharsets.UTF_8));
Multipart multipart = new MimeMultipart();
InternetHeaders headers = new InternetHeaders();
headers.addHeader("Content-type", "text/html; charset=UTF-8");
String confirmLink = "Complete your registration by clicking on following"+ "n<a href='" + confirmationURL + encodedEmail + "'>link</a>";
MimeBodyPart link = new MimeBodyPart(headers,
confirmLink.getBytes("UTF-8"));
multipart.addBodyPart(link);


where confirmationURL is:



private final static String confirmationURL = "http://localhost:8080/project/controller?command=confirmRegistration&ID=";


And then decoding this in ConfirmRegistrationCommand in such way:



 String encryptedEmail = request.getParameter("ID");

String decodedEmail = new String(Base64.getUrlDecoder().decode(encryptedEmail), StandardCharsets.UTF_8);

RepositoryFactory repositoryFactory = RepositoryFactory
.getFactoryByName(FactoryType.MYSQL_REPOSITORY_FACTORY);
UserRepository userRepository = repositoryFactory.getUserRepository();
User user = userRepository.find(decodedEmail);

if (user.getEmail().equals(decodedEmail))
user.setActiveStatus(true);
return Path.WELCOME_PAGE;
else
return Path.ERROR_PAGE;



And when I'm trying to decode:



http://localhost:8080/project/controller?command=confirmRegistration&ID=[B@6499375d


I'm getting java.lang.IllegalArgumentException: Illegal base64 character 5b.



I tried to use basic Encode/Decoder (not URL ones) with no success.



SOLVED:



The problem was the next - in the line:



 String confirmLink = "Complete your registration by clicking on following"+ "n<a href='" + confirmationURL + encodedEmail + "'>link</a>";


I'm calling toString on an array of bytes, so I should do the following:



String encodedEmail = new String(Base64.getEncoder().encode(
user.getEmail().getBytes(StandardCharsets.UTF_8)));


Thanks to Jon Skeet and ByteHamster.










share|improve this question



















  • 1




    Out of curiosity, why .getBytes(StandardCharsets.UTF_8) and .getBytes("UTF-8") in the same function ? Seems like a lack of consistency to me :|
    – Andrea Ligios
    Feb 18 '15 at 12:49







  • 3




    Hint: you're calling toString() on a byte. You don't want to do that.
    – Jon Skeet
    Feb 18 '15 at 12:50










  • @JonSkeet yes ! I think it causes the problem. How should I change it ?
    – marknorkin
    Feb 18 '15 at 12:54










  • @JonSkeet probably I should just call new String(encodedEmail)
    – marknorkin
    Feb 18 '15 at 12:55










  • Or better, use a base64 API that encodes to a string, not a byte. The library at iharder.net/base64 is pretty good...
    – Jon Skeet
    Feb 18 '15 at 12:59














up vote
8
down vote

favorite
1












I'm trying to send a confirmation email after user registration. I'm using the JavaMail library for this purpose and the Java 8 Base64 util class.



I'm encoding user emails in the following way:



byte encodedEmail = Base64.getUrlEncoder().encode(user.getEmail().getBytes(StandardCharsets.UTF_8));
Multipart multipart = new MimeMultipart();
InternetHeaders headers = new InternetHeaders();
headers.addHeader("Content-type", "text/html; charset=UTF-8");
String confirmLink = "Complete your registration by clicking on following"+ "n<a href='" + confirmationURL + encodedEmail + "'>link</a>";
MimeBodyPart link = new MimeBodyPart(headers,
confirmLink.getBytes("UTF-8"));
multipart.addBodyPart(link);


where confirmationURL is:



private final static String confirmationURL = "http://localhost:8080/project/controller?command=confirmRegistration&ID=";


And then decoding this in ConfirmRegistrationCommand in such way:



 String encryptedEmail = request.getParameter("ID");

String decodedEmail = new String(Base64.getUrlDecoder().decode(encryptedEmail), StandardCharsets.UTF_8);

RepositoryFactory repositoryFactory = RepositoryFactory
.getFactoryByName(FactoryType.MYSQL_REPOSITORY_FACTORY);
UserRepository userRepository = repositoryFactory.getUserRepository();
User user = userRepository.find(decodedEmail);

if (user.getEmail().equals(decodedEmail))
user.setActiveStatus(true);
return Path.WELCOME_PAGE;
else
return Path.ERROR_PAGE;



And when I'm trying to decode:



http://localhost:8080/project/controller?command=confirmRegistration&ID=[B@6499375d


I'm getting java.lang.IllegalArgumentException: Illegal base64 character 5b.



I tried to use basic Encode/Decoder (not URL ones) with no success.



SOLVED:



The problem was the next - in the line:



 String confirmLink = "Complete your registration by clicking on following"+ "n<a href='" + confirmationURL + encodedEmail + "'>link</a>";


I'm calling toString on an array of bytes, so I should do the following:



String encodedEmail = new String(Base64.getEncoder().encode(
user.getEmail().getBytes(StandardCharsets.UTF_8)));


Thanks to Jon Skeet and ByteHamster.










share|improve this question



















  • 1




    Out of curiosity, why .getBytes(StandardCharsets.UTF_8) and .getBytes("UTF-8") in the same function ? Seems like a lack of consistency to me :|
    – Andrea Ligios
    Feb 18 '15 at 12:49







  • 3




    Hint: you're calling toString() on a byte. You don't want to do that.
    – Jon Skeet
    Feb 18 '15 at 12:50










  • @JonSkeet yes ! I think it causes the problem. How should I change it ?
    – marknorkin
    Feb 18 '15 at 12:54










  • @JonSkeet probably I should just call new String(encodedEmail)
    – marknorkin
    Feb 18 '15 at 12:55










  • Or better, use a base64 API that encodes to a string, not a byte. The library at iharder.net/base64 is pretty good...
    – Jon Skeet
    Feb 18 '15 at 12:59












up vote
8
down vote

favorite
1









up vote
8
down vote

favorite
1






1





I'm trying to send a confirmation email after user registration. I'm using the JavaMail library for this purpose and the Java 8 Base64 util class.



I'm encoding user emails in the following way:



byte encodedEmail = Base64.getUrlEncoder().encode(user.getEmail().getBytes(StandardCharsets.UTF_8));
Multipart multipart = new MimeMultipart();
InternetHeaders headers = new InternetHeaders();
headers.addHeader("Content-type", "text/html; charset=UTF-8");
String confirmLink = "Complete your registration by clicking on following"+ "n<a href='" + confirmationURL + encodedEmail + "'>link</a>";
MimeBodyPart link = new MimeBodyPart(headers,
confirmLink.getBytes("UTF-8"));
multipart.addBodyPart(link);


where confirmationURL is:



private final static String confirmationURL = "http://localhost:8080/project/controller?command=confirmRegistration&ID=";


And then decoding this in ConfirmRegistrationCommand in such way:



 String encryptedEmail = request.getParameter("ID");

String decodedEmail = new String(Base64.getUrlDecoder().decode(encryptedEmail), StandardCharsets.UTF_8);

RepositoryFactory repositoryFactory = RepositoryFactory
.getFactoryByName(FactoryType.MYSQL_REPOSITORY_FACTORY);
UserRepository userRepository = repositoryFactory.getUserRepository();
User user = userRepository.find(decodedEmail);

if (user.getEmail().equals(decodedEmail))
user.setActiveStatus(true);
return Path.WELCOME_PAGE;
else
return Path.ERROR_PAGE;



And when I'm trying to decode:



http://localhost:8080/project/controller?command=confirmRegistration&ID=[B@6499375d


I'm getting java.lang.IllegalArgumentException: Illegal base64 character 5b.



I tried to use basic Encode/Decoder (not URL ones) with no success.



SOLVED:



The problem was the next - in the line:



 String confirmLink = "Complete your registration by clicking on following"+ "n<a href='" + confirmationURL + encodedEmail + "'>link</a>";


I'm calling toString on an array of bytes, so I should do the following:



String encodedEmail = new String(Base64.getEncoder().encode(
user.getEmail().getBytes(StandardCharsets.UTF_8)));


Thanks to Jon Skeet and ByteHamster.










share|improve this question















I'm trying to send a confirmation email after user registration. I'm using the JavaMail library for this purpose and the Java 8 Base64 util class.



I'm encoding user emails in the following way:



byte encodedEmail = Base64.getUrlEncoder().encode(user.getEmail().getBytes(StandardCharsets.UTF_8));
Multipart multipart = new MimeMultipart();
InternetHeaders headers = new InternetHeaders();
headers.addHeader("Content-type", "text/html; charset=UTF-8");
String confirmLink = "Complete your registration by clicking on following"+ "n<a href='" + confirmationURL + encodedEmail + "'>link</a>";
MimeBodyPart link = new MimeBodyPart(headers,
confirmLink.getBytes("UTF-8"));
multipart.addBodyPart(link);


where confirmationURL is:



private final static String confirmationURL = "http://localhost:8080/project/controller?command=confirmRegistration&ID=";


And then decoding this in ConfirmRegistrationCommand in such way:



 String encryptedEmail = request.getParameter("ID");

String decodedEmail = new String(Base64.getUrlDecoder().decode(encryptedEmail), StandardCharsets.UTF_8);

RepositoryFactory repositoryFactory = RepositoryFactory
.getFactoryByName(FactoryType.MYSQL_REPOSITORY_FACTORY);
UserRepository userRepository = repositoryFactory.getUserRepository();
User user = userRepository.find(decodedEmail);

if (user.getEmail().equals(decodedEmail))
user.setActiveStatus(true);
return Path.WELCOME_PAGE;
else
return Path.ERROR_PAGE;



And when I'm trying to decode:



http://localhost:8080/project/controller?command=confirmRegistration&ID=[B@6499375d


I'm getting java.lang.IllegalArgumentException: Illegal base64 character 5b.



I tried to use basic Encode/Decoder (not URL ones) with no success.



SOLVED:



The problem was the next - in the line:



 String confirmLink = "Complete your registration by clicking on following"+ "n<a href='" + confirmationURL + encodedEmail + "'>link</a>";


I'm calling toString on an array of bytes, so I should do the following:



String encodedEmail = new String(Base64.getEncoder().encode(
user.getEmail().getBytes(StandardCharsets.UTF_8)));


Thanks to Jon Skeet and ByteHamster.







java base64 javamail registration






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited May 29 '17 at 11:16









Matthias Braun

12.9k875107




12.9k875107










asked Feb 18 '15 at 12:47









marknorkin

1,47462452




1,47462452







  • 1




    Out of curiosity, why .getBytes(StandardCharsets.UTF_8) and .getBytes("UTF-8") in the same function ? Seems like a lack of consistency to me :|
    – Andrea Ligios
    Feb 18 '15 at 12:49







  • 3




    Hint: you're calling toString() on a byte. You don't want to do that.
    – Jon Skeet
    Feb 18 '15 at 12:50










  • @JonSkeet yes ! I think it causes the problem. How should I change it ?
    – marknorkin
    Feb 18 '15 at 12:54










  • @JonSkeet probably I should just call new String(encodedEmail)
    – marknorkin
    Feb 18 '15 at 12:55










  • Or better, use a base64 API that encodes to a string, not a byte. The library at iharder.net/base64 is pretty good...
    – Jon Skeet
    Feb 18 '15 at 12:59












  • 1




    Out of curiosity, why .getBytes(StandardCharsets.UTF_8) and .getBytes("UTF-8") in the same function ? Seems like a lack of consistency to me :|
    – Andrea Ligios
    Feb 18 '15 at 12:49







  • 3




    Hint: you're calling toString() on a byte. You don't want to do that.
    – Jon Skeet
    Feb 18 '15 at 12:50










  • @JonSkeet yes ! I think it causes the problem. How should I change it ?
    – marknorkin
    Feb 18 '15 at 12:54










  • @JonSkeet probably I should just call new String(encodedEmail)
    – marknorkin
    Feb 18 '15 at 12:55










  • Or better, use a base64 API that encodes to a string, not a byte. The library at iharder.net/base64 is pretty good...
    – Jon Skeet
    Feb 18 '15 at 12:59







1




1




Out of curiosity, why .getBytes(StandardCharsets.UTF_8) and .getBytes("UTF-8") in the same function ? Seems like a lack of consistency to me :|
– Andrea Ligios
Feb 18 '15 at 12:49





Out of curiosity, why .getBytes(StandardCharsets.UTF_8) and .getBytes("UTF-8") in the same function ? Seems like a lack of consistency to me :|
– Andrea Ligios
Feb 18 '15 at 12:49





3




3




Hint: you're calling toString() on a byte. You don't want to do that.
– Jon Skeet
Feb 18 '15 at 12:50




Hint: you're calling toString() on a byte. You don't want to do that.
– Jon Skeet
Feb 18 '15 at 12:50












@JonSkeet yes ! I think it causes the problem. How should I change it ?
– marknorkin
Feb 18 '15 at 12:54




@JonSkeet yes ! I think it causes the problem. How should I change it ?
– marknorkin
Feb 18 '15 at 12:54












@JonSkeet probably I should just call new String(encodedEmail)
– marknorkin
Feb 18 '15 at 12:55




@JonSkeet probably I should just call new String(encodedEmail)
– marknorkin
Feb 18 '15 at 12:55












Or better, use a base64 API that encodes to a string, not a byte. The library at iharder.net/base64 is pretty good...
– Jon Skeet
Feb 18 '15 at 12:59




Or better, use a base64 API that encodes to a string, not a byte. The library at iharder.net/base64 is pretty good...
– Jon Skeet
Feb 18 '15 at 12:59












4 Answers
4






active

oldest

votes

















up vote
12
down vote



accepted










Your encoded text is [B@6499375d. That is not Base64, something went wrong while encoding. That decoding code looks good.



Use this code to convert the byte to a String before adding it to the URL:



String encodedEmailString = new String(encodedEmail, "UTF-8");
// ...
String confirmLink = "Complete your registration by clicking on following"
+ "n<a href='" + confirmationURL + encodedEmailString + "'>link</a>";





share|improve this answer






















  • as Jon Skeet pointed out i'm calling toString on array of bites. this is the cause
    – marknorkin
    Feb 18 '15 at 12:54







  • 9




    I hate to be that guy, but since this is a technical forum: base64 isn't encryption, it's encoding.
    – apottere
    Jun 20 '17 at 14:37

















up vote
6
down vote













I encountered this error since my encoded image started with data:image/png;base64,iVBORw0....



This answer led me to the solution:



String partSeparator = ",";
if (data.contains(partSeparator)
String encodedImg = data.split(partSeparator)[1];
byte decodedImg = Base64.getDecoder().decode(encodedImg.getBytes(StandardCharsets.UTF_8));
Path destinationFile = Paths.get("/path/to/imageDir", "myImage.jpg");
Files.write(destinationFile, decodedImg);






share|improve this answer





























    up vote
    2
    down vote













    Just use the below code to resolve this:



    JsonObject obj = Json.createReader(new ByteArrayInputStream(Base64.getDecoder().decode(accessToken.split("\.")[1].
    replace('-', '+').replace('_', '/')))).readObject();


    In the above code replace('-', '+').replace('_', '/') did the job. For more details see the https://jwt.io/js/jwt.js. I understood the problem from the part of the code got from that link:



    function url_base64_decode(str) 
    var output = str.replace(/-/g, '+').replace(/_/g, '/');
    switch (output.length % 4)
    case 0:
    break;
    case 2:
    output += '==';
    break;
    case 3:
    output += '=';
    break;
    default:
    throw 'Illegal base64url string!';

    var result = window.atob(output); //polifyll https://github.com/davidchambers/Base64.js
    try
    return decodeURIComponent(escape(result));
    catch (err)
    return result;







    share|improve this answer





























      up vote
      0
      down vote













      The Base64.Encoder.encodeToString method automatically uses the ISO-8859-1 character set.



      For an encryption utility I am writing, I took the input string of cipher text and Base64 encoded it for transmission, then reversed the process. Relevant parts shown below. NOTE: My file.encoding property is set to ISO-8859-1 upon invocation of the JVM so that may also have a bearing.



      static String getBase64EncodedCipherText(String cipherText) 
      byte cText = cipherText.getBytes();
      // return an ISO-8859-1 encoded String
      return Base64.getEncoder().encodeToString(cText);


      static String getBase64DecodedCipherText(String encodedCipherText) throws IOException
      return new String((Base64.getDecoder().decode(encodedCipherText)));


      public static void main(String args)
      try
      String cText = getRawCipherText(null, "Hello World of Encryption...");

      System.out.println("Text to encrypt/encode: Hello World of Encryption...");
      // This output is a simple sanity check to display that the text
      // has indeed been converted to a cipher text which
      // is unreadable by all but the most intelligent of programmers.
      // It is absolutely inhuman of me to do such a thing, but I am a
      // rebel and cannot be trusted in any way. Please look away.
      System.out.println("RAW CIPHER TEXT: " + cText);
      cText = getBase64EncodedCipherText(cText);
      System.out.println("BASE64 ENCODED: " + cText);
      // There he goes again!!
      System.out.println("BASE64 DECODED: " + getBase64DecodedCipherText(cText));
      System.out.println("DECODED CIPHER TEXT: " + decodeRawCipherText(null, getBase64DecodedCipherText(cText)));
      catch (Exception e)
      e.printStackTrace();





      The output looks like:



      Text to encrypt/encode: Hello World of Encryption...
      RAW CIPHER TEXT: q$;�C�l��<8��U���X[7l
      BASE64 ENCODED: HnEPJDuhQ+qDbInUCzw4gx0VDqtVwef+WFs3bA==
      BASE64 DECODED: q$;�C�l��<8��U���X[7l``
      DECODED CIPHER TEXT: Hello World of Encryption...





      share|improve this answer






















      • Basically trying to display encrypted data as text does not work because there are byte values that do not have a printable representation. In this case the "�" characters. For this reason encrypted data is best display in hexadecimal.
        – zaph
        Feb 20 '16 at 16:25











      • @zaph That's just debug code, but displaying encrypted data as text works just fine if your encryption output is already printable characters. In this case they are not all printable, but it is also irrelevant.
        – guitarpicva
        Feb 20 '16 at 20:11










      • What makes you think I don't understand encodings? It's simply a sanity check output to see if it got encrypted, and as such, the unprintable characters are a better representation of that than neatly formatted %02x characters. The output is for me alone, the only developer.
        – guitarpicva
        Feb 23 '16 at 22:56






      • 1




        In light of that lame retort, I have added comments to my source code.
        – guitarpicva
        Feb 25 '16 at 18:50










      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













       

      draft saved


      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f28584080%2fbase64-java-lang-illegalargumentexception-illegal-character%23new-answer', 'question_page');

      );

      Post as a guest






























      4 Answers
      4






      active

      oldest

      votes








      4 Answers
      4






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      12
      down vote



      accepted










      Your encoded text is [B@6499375d. That is not Base64, something went wrong while encoding. That decoding code looks good.



      Use this code to convert the byte to a String before adding it to the URL:



      String encodedEmailString = new String(encodedEmail, "UTF-8");
      // ...
      String confirmLink = "Complete your registration by clicking on following"
      + "n<a href='" + confirmationURL + encodedEmailString + "'>link</a>";





      share|improve this answer






















      • as Jon Skeet pointed out i'm calling toString on array of bites. this is the cause
        – marknorkin
        Feb 18 '15 at 12:54







      • 9




        I hate to be that guy, but since this is a technical forum: base64 isn't encryption, it's encoding.
        – apottere
        Jun 20 '17 at 14:37














      up vote
      12
      down vote



      accepted










      Your encoded text is [B@6499375d. That is not Base64, something went wrong while encoding. That decoding code looks good.



      Use this code to convert the byte to a String before adding it to the URL:



      String encodedEmailString = new String(encodedEmail, "UTF-8");
      // ...
      String confirmLink = "Complete your registration by clicking on following"
      + "n<a href='" + confirmationURL + encodedEmailString + "'>link</a>";





      share|improve this answer






















      • as Jon Skeet pointed out i'm calling toString on array of bites. this is the cause
        – marknorkin
        Feb 18 '15 at 12:54







      • 9




        I hate to be that guy, but since this is a technical forum: base64 isn't encryption, it's encoding.
        – apottere
        Jun 20 '17 at 14:37












      up vote
      12
      down vote



      accepted







      up vote
      12
      down vote



      accepted






      Your encoded text is [B@6499375d. That is not Base64, something went wrong while encoding. That decoding code looks good.



      Use this code to convert the byte to a String before adding it to the URL:



      String encodedEmailString = new String(encodedEmail, "UTF-8");
      // ...
      String confirmLink = "Complete your registration by clicking on following"
      + "n<a href='" + confirmationURL + encodedEmailString + "'>link</a>";





      share|improve this answer














      Your encoded text is [B@6499375d. That is not Base64, something went wrong while encoding. That decoding code looks good.



      Use this code to convert the byte to a String before adding it to the URL:



      String encodedEmailString = new String(encodedEmail, "UTF-8");
      // ...
      String confirmLink = "Complete your registration by clicking on following"
      + "n<a href='" + confirmationURL + encodedEmailString + "'>link</a>";






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Nov 9 at 15:17

























      answered Feb 18 '15 at 12:52









      ByteHamster

      4,05692747




      4,05692747











      • as Jon Skeet pointed out i'm calling toString on array of bites. this is the cause
        – marknorkin
        Feb 18 '15 at 12:54







      • 9




        I hate to be that guy, but since this is a technical forum: base64 isn't encryption, it's encoding.
        – apottere
        Jun 20 '17 at 14:37
















      • as Jon Skeet pointed out i'm calling toString on array of bites. this is the cause
        – marknorkin
        Feb 18 '15 at 12:54







      • 9




        I hate to be that guy, but since this is a technical forum: base64 isn't encryption, it's encoding.
        – apottere
        Jun 20 '17 at 14:37















      as Jon Skeet pointed out i'm calling toString on array of bites. this is the cause
      – marknorkin
      Feb 18 '15 at 12:54





      as Jon Skeet pointed out i'm calling toString on array of bites. this is the cause
      – marknorkin
      Feb 18 '15 at 12:54





      9




      9




      I hate to be that guy, but since this is a technical forum: base64 isn't encryption, it's encoding.
      – apottere
      Jun 20 '17 at 14:37




      I hate to be that guy, but since this is a technical forum: base64 isn't encryption, it's encoding.
      – apottere
      Jun 20 '17 at 14:37












      up vote
      6
      down vote













      I encountered this error since my encoded image started with data:image/png;base64,iVBORw0....



      This answer led me to the solution:



      String partSeparator = ",";
      if (data.contains(partSeparator)
      String encodedImg = data.split(partSeparator)[1];
      byte decodedImg = Base64.getDecoder().decode(encodedImg.getBytes(StandardCharsets.UTF_8));
      Path destinationFile = Paths.get("/path/to/imageDir", "myImage.jpg");
      Files.write(destinationFile, decodedImg);






      share|improve this answer


























        up vote
        6
        down vote













        I encountered this error since my encoded image started with data:image/png;base64,iVBORw0....



        This answer led me to the solution:



        String partSeparator = ",";
        if (data.contains(partSeparator)
        String encodedImg = data.split(partSeparator)[1];
        byte decodedImg = Base64.getDecoder().decode(encodedImg.getBytes(StandardCharsets.UTF_8));
        Path destinationFile = Paths.get("/path/to/imageDir", "myImage.jpg");
        Files.write(destinationFile, decodedImg);






        share|improve this answer
























          up vote
          6
          down vote










          up vote
          6
          down vote









          I encountered this error since my encoded image started with data:image/png;base64,iVBORw0....



          This answer led me to the solution:



          String partSeparator = ",";
          if (data.contains(partSeparator)
          String encodedImg = data.split(partSeparator)[1];
          byte decodedImg = Base64.getDecoder().decode(encodedImg.getBytes(StandardCharsets.UTF_8));
          Path destinationFile = Paths.get("/path/to/imageDir", "myImage.jpg");
          Files.write(destinationFile, decodedImg);






          share|improve this answer














          I encountered this error since my encoded image started with data:image/png;base64,iVBORw0....



          This answer led me to the solution:



          String partSeparator = ",";
          if (data.contains(partSeparator)
          String encodedImg = data.split(partSeparator)[1];
          byte decodedImg = Base64.getDecoder().decode(encodedImg.getBytes(StandardCharsets.UTF_8));
          Path destinationFile = Paths.get("/path/to/imageDir", "myImage.jpg");
          Files.write(destinationFile, decodedImg);







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited May 23 '17 at 11:54









          Community

          11




          11










          answered Oct 22 '16 at 19:11









          Matthias Braun

          12.9k875107




          12.9k875107




















              up vote
              2
              down vote













              Just use the below code to resolve this:



              JsonObject obj = Json.createReader(new ByteArrayInputStream(Base64.getDecoder().decode(accessToken.split("\.")[1].
              replace('-', '+').replace('_', '/')))).readObject();


              In the above code replace('-', '+').replace('_', '/') did the job. For more details see the https://jwt.io/js/jwt.js. I understood the problem from the part of the code got from that link:



              function url_base64_decode(str) 
              var output = str.replace(/-/g, '+').replace(/_/g, '/');
              switch (output.length % 4)
              case 0:
              break;
              case 2:
              output += '==';
              break;
              case 3:
              output += '=';
              break;
              default:
              throw 'Illegal base64url string!';

              var result = window.atob(output); //polifyll https://github.com/davidchambers/Base64.js
              try
              return decodeURIComponent(escape(result));
              catch (err)
              return result;







              share|improve this answer


























                up vote
                2
                down vote













                Just use the below code to resolve this:



                JsonObject obj = Json.createReader(new ByteArrayInputStream(Base64.getDecoder().decode(accessToken.split("\.")[1].
                replace('-', '+').replace('_', '/')))).readObject();


                In the above code replace('-', '+').replace('_', '/') did the job. For more details see the https://jwt.io/js/jwt.js. I understood the problem from the part of the code got from that link:



                function url_base64_decode(str) 
                var output = str.replace(/-/g, '+').replace(/_/g, '/');
                switch (output.length % 4)
                case 0:
                break;
                case 2:
                output += '==';
                break;
                case 3:
                output += '=';
                break;
                default:
                throw 'Illegal base64url string!';

                var result = window.atob(output); //polifyll https://github.com/davidchambers/Base64.js
                try
                return decodeURIComponent(escape(result));
                catch (err)
                return result;







                share|improve this answer
























                  up vote
                  2
                  down vote










                  up vote
                  2
                  down vote









                  Just use the below code to resolve this:



                  JsonObject obj = Json.createReader(new ByteArrayInputStream(Base64.getDecoder().decode(accessToken.split("\.")[1].
                  replace('-', '+').replace('_', '/')))).readObject();


                  In the above code replace('-', '+').replace('_', '/') did the job. For more details see the https://jwt.io/js/jwt.js. I understood the problem from the part of the code got from that link:



                  function url_base64_decode(str) 
                  var output = str.replace(/-/g, '+').replace(/_/g, '/');
                  switch (output.length % 4)
                  case 0:
                  break;
                  case 2:
                  output += '==';
                  break;
                  case 3:
                  output += '=';
                  break;
                  default:
                  throw 'Illegal base64url string!';

                  var result = window.atob(output); //polifyll https://github.com/davidchambers/Base64.js
                  try
                  return decodeURIComponent(escape(result));
                  catch (err)
                  return result;







                  share|improve this answer














                  Just use the below code to resolve this:



                  JsonObject obj = Json.createReader(new ByteArrayInputStream(Base64.getDecoder().decode(accessToken.split("\.")[1].
                  replace('-', '+').replace('_', '/')))).readObject();


                  In the above code replace('-', '+').replace('_', '/') did the job. For more details see the https://jwt.io/js/jwt.js. I understood the problem from the part of the code got from that link:



                  function url_base64_decode(str) 
                  var output = str.replace(/-/g, '+').replace(/_/g, '/');
                  switch (output.length % 4)
                  case 0:
                  break;
                  case 2:
                  output += '==';
                  break;
                  case 3:
                  output += '=';
                  break;
                  default:
                  throw 'Illegal base64url string!';

                  var result = window.atob(output); //polifyll https://github.com/davidchambers/Base64.js
                  try
                  return decodeURIComponent(escape(result));
                  catch (err)
                  return result;








                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited May 15 '17 at 14:30

























                  answered May 15 '17 at 14:26









                  Esakkiappan .E

                  414




                  414




















                      up vote
                      0
                      down vote













                      The Base64.Encoder.encodeToString method automatically uses the ISO-8859-1 character set.



                      For an encryption utility I am writing, I took the input string of cipher text and Base64 encoded it for transmission, then reversed the process. Relevant parts shown below. NOTE: My file.encoding property is set to ISO-8859-1 upon invocation of the JVM so that may also have a bearing.



                      static String getBase64EncodedCipherText(String cipherText) 
                      byte cText = cipherText.getBytes();
                      // return an ISO-8859-1 encoded String
                      return Base64.getEncoder().encodeToString(cText);


                      static String getBase64DecodedCipherText(String encodedCipherText) throws IOException
                      return new String((Base64.getDecoder().decode(encodedCipherText)));


                      public static void main(String args)
                      try
                      String cText = getRawCipherText(null, "Hello World of Encryption...");

                      System.out.println("Text to encrypt/encode: Hello World of Encryption...");
                      // This output is a simple sanity check to display that the text
                      // has indeed been converted to a cipher text which
                      // is unreadable by all but the most intelligent of programmers.
                      // It is absolutely inhuman of me to do such a thing, but I am a
                      // rebel and cannot be trusted in any way. Please look away.
                      System.out.println("RAW CIPHER TEXT: " + cText);
                      cText = getBase64EncodedCipherText(cText);
                      System.out.println("BASE64 ENCODED: " + cText);
                      // There he goes again!!
                      System.out.println("BASE64 DECODED: " + getBase64DecodedCipherText(cText));
                      System.out.println("DECODED CIPHER TEXT: " + decodeRawCipherText(null, getBase64DecodedCipherText(cText)));
                      catch (Exception e)
                      e.printStackTrace();





                      The output looks like:



                      Text to encrypt/encode: Hello World of Encryption...
                      RAW CIPHER TEXT: q$;�C�l��<8��U���X[7l
                      BASE64 ENCODED: HnEPJDuhQ+qDbInUCzw4gx0VDqtVwef+WFs3bA==
                      BASE64 DECODED: q$;�C�l��<8��U���X[7l``
                      DECODED CIPHER TEXT: Hello World of Encryption...





                      share|improve this answer






















                      • Basically trying to display encrypted data as text does not work because there are byte values that do not have a printable representation. In this case the "�" characters. For this reason encrypted data is best display in hexadecimal.
                        – zaph
                        Feb 20 '16 at 16:25











                      • @zaph That's just debug code, but displaying encrypted data as text works just fine if your encryption output is already printable characters. In this case they are not all printable, but it is also irrelevant.
                        – guitarpicva
                        Feb 20 '16 at 20:11










                      • What makes you think I don't understand encodings? It's simply a sanity check output to see if it got encrypted, and as such, the unprintable characters are a better representation of that than neatly formatted %02x characters. The output is for me alone, the only developer.
                        – guitarpicva
                        Feb 23 '16 at 22:56






                      • 1




                        In light of that lame retort, I have added comments to my source code.
                        – guitarpicva
                        Feb 25 '16 at 18:50














                      up vote
                      0
                      down vote













                      The Base64.Encoder.encodeToString method automatically uses the ISO-8859-1 character set.



                      For an encryption utility I am writing, I took the input string of cipher text and Base64 encoded it for transmission, then reversed the process. Relevant parts shown below. NOTE: My file.encoding property is set to ISO-8859-1 upon invocation of the JVM so that may also have a bearing.



                      static String getBase64EncodedCipherText(String cipherText) 
                      byte cText = cipherText.getBytes();
                      // return an ISO-8859-1 encoded String
                      return Base64.getEncoder().encodeToString(cText);


                      static String getBase64DecodedCipherText(String encodedCipherText) throws IOException
                      return new String((Base64.getDecoder().decode(encodedCipherText)));


                      public static void main(String args)
                      try
                      String cText = getRawCipherText(null, "Hello World of Encryption...");

                      System.out.println("Text to encrypt/encode: Hello World of Encryption...");
                      // This output is a simple sanity check to display that the text
                      // has indeed been converted to a cipher text which
                      // is unreadable by all but the most intelligent of programmers.
                      // It is absolutely inhuman of me to do such a thing, but I am a
                      // rebel and cannot be trusted in any way. Please look away.
                      System.out.println("RAW CIPHER TEXT: " + cText);
                      cText = getBase64EncodedCipherText(cText);
                      System.out.println("BASE64 ENCODED: " + cText);
                      // There he goes again!!
                      System.out.println("BASE64 DECODED: " + getBase64DecodedCipherText(cText));
                      System.out.println("DECODED CIPHER TEXT: " + decodeRawCipherText(null, getBase64DecodedCipherText(cText)));
                      catch (Exception e)
                      e.printStackTrace();





                      The output looks like:



                      Text to encrypt/encode: Hello World of Encryption...
                      RAW CIPHER TEXT: q$;�C�l��<8��U���X[7l
                      BASE64 ENCODED: HnEPJDuhQ+qDbInUCzw4gx0VDqtVwef+WFs3bA==
                      BASE64 DECODED: q$;�C�l��<8��U���X[7l``
                      DECODED CIPHER TEXT: Hello World of Encryption...





                      share|improve this answer






















                      • Basically trying to display encrypted data as text does not work because there are byte values that do not have a printable representation. In this case the "�" characters. For this reason encrypted data is best display in hexadecimal.
                        – zaph
                        Feb 20 '16 at 16:25











                      • @zaph That's just debug code, but displaying encrypted data as text works just fine if your encryption output is already printable characters. In this case they are not all printable, but it is also irrelevant.
                        – guitarpicva
                        Feb 20 '16 at 20:11










                      • What makes you think I don't understand encodings? It's simply a sanity check output to see if it got encrypted, and as such, the unprintable characters are a better representation of that than neatly formatted %02x characters. The output is for me alone, the only developer.
                        – guitarpicva
                        Feb 23 '16 at 22:56






                      • 1




                        In light of that lame retort, I have added comments to my source code.
                        – guitarpicva
                        Feb 25 '16 at 18:50












                      up vote
                      0
                      down vote










                      up vote
                      0
                      down vote









                      The Base64.Encoder.encodeToString method automatically uses the ISO-8859-1 character set.



                      For an encryption utility I am writing, I took the input string of cipher text and Base64 encoded it for transmission, then reversed the process. Relevant parts shown below. NOTE: My file.encoding property is set to ISO-8859-1 upon invocation of the JVM so that may also have a bearing.



                      static String getBase64EncodedCipherText(String cipherText) 
                      byte cText = cipherText.getBytes();
                      // return an ISO-8859-1 encoded String
                      return Base64.getEncoder().encodeToString(cText);


                      static String getBase64DecodedCipherText(String encodedCipherText) throws IOException
                      return new String((Base64.getDecoder().decode(encodedCipherText)));


                      public static void main(String args)
                      try
                      String cText = getRawCipherText(null, "Hello World of Encryption...");

                      System.out.println("Text to encrypt/encode: Hello World of Encryption...");
                      // This output is a simple sanity check to display that the text
                      // has indeed been converted to a cipher text which
                      // is unreadable by all but the most intelligent of programmers.
                      // It is absolutely inhuman of me to do such a thing, but I am a
                      // rebel and cannot be trusted in any way. Please look away.
                      System.out.println("RAW CIPHER TEXT: " + cText);
                      cText = getBase64EncodedCipherText(cText);
                      System.out.println("BASE64 ENCODED: " + cText);
                      // There he goes again!!
                      System.out.println("BASE64 DECODED: " + getBase64DecodedCipherText(cText));
                      System.out.println("DECODED CIPHER TEXT: " + decodeRawCipherText(null, getBase64DecodedCipherText(cText)));
                      catch (Exception e)
                      e.printStackTrace();





                      The output looks like:



                      Text to encrypt/encode: Hello World of Encryption...
                      RAW CIPHER TEXT: q$;�C�l��<8��U���X[7l
                      BASE64 ENCODED: HnEPJDuhQ+qDbInUCzw4gx0VDqtVwef+WFs3bA==
                      BASE64 DECODED: q$;�C�l��<8��U���X[7l``
                      DECODED CIPHER TEXT: Hello World of Encryption...





                      share|improve this answer














                      The Base64.Encoder.encodeToString method automatically uses the ISO-8859-1 character set.



                      For an encryption utility I am writing, I took the input string of cipher text and Base64 encoded it for transmission, then reversed the process. Relevant parts shown below. NOTE: My file.encoding property is set to ISO-8859-1 upon invocation of the JVM so that may also have a bearing.



                      static String getBase64EncodedCipherText(String cipherText) 
                      byte cText = cipherText.getBytes();
                      // return an ISO-8859-1 encoded String
                      return Base64.getEncoder().encodeToString(cText);


                      static String getBase64DecodedCipherText(String encodedCipherText) throws IOException
                      return new String((Base64.getDecoder().decode(encodedCipherText)));


                      public static void main(String args)
                      try
                      String cText = getRawCipherText(null, "Hello World of Encryption...");

                      System.out.println("Text to encrypt/encode: Hello World of Encryption...");
                      // This output is a simple sanity check to display that the text
                      // has indeed been converted to a cipher text which
                      // is unreadable by all but the most intelligent of programmers.
                      // It is absolutely inhuman of me to do such a thing, but I am a
                      // rebel and cannot be trusted in any way. Please look away.
                      System.out.println("RAW CIPHER TEXT: " + cText);
                      cText = getBase64EncodedCipherText(cText);
                      System.out.println("BASE64 ENCODED: " + cText);
                      // There he goes again!!
                      System.out.println("BASE64 DECODED: " + getBase64DecodedCipherText(cText));
                      System.out.println("DECODED CIPHER TEXT: " + decodeRawCipherText(null, getBase64DecodedCipherText(cText)));
                      catch (Exception e)
                      e.printStackTrace();





                      The output looks like:



                      Text to encrypt/encode: Hello World of Encryption...
                      RAW CIPHER TEXT: q$;�C�l��<8��U���X[7l
                      BASE64 ENCODED: HnEPJDuhQ+qDbInUCzw4gx0VDqtVwef+WFs3bA==
                      BASE64 DECODED: q$;�C�l��<8��U���X[7l``
                      DECODED CIPHER TEXT: Hello World of Encryption...






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Nov 18 '16 at 14:54

























                      answered Feb 20 '16 at 14:41









                      guitarpicva

                      957




                      957











                      • Basically trying to display encrypted data as text does not work because there are byte values that do not have a printable representation. In this case the "�" characters. For this reason encrypted data is best display in hexadecimal.
                        – zaph
                        Feb 20 '16 at 16:25











                      • @zaph That's just debug code, but displaying encrypted data as text works just fine if your encryption output is already printable characters. In this case they are not all printable, but it is also irrelevant.
                        – guitarpicva
                        Feb 20 '16 at 20:11










                      • What makes you think I don't understand encodings? It's simply a sanity check output to see if it got encrypted, and as such, the unprintable characters are a better representation of that than neatly formatted %02x characters. The output is for me alone, the only developer.
                        – guitarpicva
                        Feb 23 '16 at 22:56






                      • 1




                        In light of that lame retort, I have added comments to my source code.
                        – guitarpicva
                        Feb 25 '16 at 18:50
















                      • Basically trying to display encrypted data as text does not work because there are byte values that do not have a printable representation. In this case the "�" characters. For this reason encrypted data is best display in hexadecimal.
                        – zaph
                        Feb 20 '16 at 16:25











                      • @zaph That's just debug code, but displaying encrypted data as text works just fine if your encryption output is already printable characters. In this case they are not all printable, but it is also irrelevant.
                        – guitarpicva
                        Feb 20 '16 at 20:11










                      • What makes you think I don't understand encodings? It's simply a sanity check output to see if it got encrypted, and as such, the unprintable characters are a better representation of that than neatly formatted %02x characters. The output is for me alone, the only developer.
                        – guitarpicva
                        Feb 23 '16 at 22:56






                      • 1




                        In light of that lame retort, I have added comments to my source code.
                        – guitarpicva
                        Feb 25 '16 at 18:50















                      Basically trying to display encrypted data as text does not work because there are byte values that do not have a printable representation. In this case the "�" characters. For this reason encrypted data is best display in hexadecimal.
                      – zaph
                      Feb 20 '16 at 16:25





                      Basically trying to display encrypted data as text does not work because there are byte values that do not have a printable representation. In this case the "�" characters. For this reason encrypted data is best display in hexadecimal.
                      – zaph
                      Feb 20 '16 at 16:25













                      @zaph That's just debug code, but displaying encrypted data as text works just fine if your encryption output is already printable characters. In this case they are not all printable, but it is also irrelevant.
                      – guitarpicva
                      Feb 20 '16 at 20:11




                      @zaph That's just debug code, but displaying encrypted data as text works just fine if your encryption output is already printable characters. In this case they are not all printable, but it is also irrelevant.
                      – guitarpicva
                      Feb 20 '16 at 20:11












                      What makes you think I don't understand encodings? It's simply a sanity check output to see if it got encrypted, and as such, the unprintable characters are a better representation of that than neatly formatted %02x characters. The output is for me alone, the only developer.
                      – guitarpicva
                      Feb 23 '16 at 22:56




                      What makes you think I don't understand encodings? It's simply a sanity check output to see if it got encrypted, and as such, the unprintable characters are a better representation of that than neatly formatted %02x characters. The output is for me alone, the only developer.
                      – guitarpicva
                      Feb 23 '16 at 22:56




                      1




                      1




                      In light of that lame retort, I have added comments to my source code.
                      – guitarpicva
                      Feb 25 '16 at 18:50




                      In light of that lame retort, I have added comments to my source code.
                      – guitarpicva
                      Feb 25 '16 at 18:50

















                       

                      draft saved


                      draft discarded















































                       


                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f28584080%2fbase64-java-lang-illegalargumentexception-illegal-character%23new-answer', 'question_page');

                      );

                      Post as a guest














































































                      Popular posts from this blog

                      Darth Vader #20

                      How to how show current date and time by default on contact form 7 in WordPress without taking input from user in datetimepicker

                      Ondo