Tuesday, December 28, 2010

Base64 encode-decode in JavaMe

I want to start this post asking: why do you think you need to encode data? At first, I didn't have a specific answer, so I googled and found some interesting answers and now I can tell you: You want to encode, because you need to transfer binary data through a channel that is designed to deal with textual data. A common example is when you need to transfer an Image inside a JSON String or in a XML message.

We will use the Bouncy Castle library to Encode/Decode binary data in Base64 format. Although this library has a lot more and can be used for Encryption/Decryption using different methods, today we will focus on the Encoding/Decoding part. You can download the library using the following link:


Make sure you download the J2ME version. When you download this version, you'll get the full source code and when you build it, you get a 1.7MB library... which may be too much for a mobile application. Anyway, with the source code you can make a build of some classes and not of all of them. That's how I made a build with only the encoders packages and classes and is just about 14KB. If you need it, just ask for it you can download it using this link.

To work with Base64 in JavaMe (J2ME) the bouncy castle library comes with the org.bouncycastle.util.encoders.Base64 class. Next is how you can use it in your MIDlet:


import org.bouncycastle.util.encoders.Base64;

...
    /**
     * As an example, encodes a String and then it decodes it.
     * Prints to console the result of the encode/decode.
     */
    public void encodeDecodeExample() {
      
        String word = "New word to encode using Base64 also special "
                + "chars like Ñ and ó";
      
        System.out.println("Encoding: ");
        System.out.println(word);
      
        byte[] coded = Base64.encode(word.getBytes());
        String strCoded = new String(coded);
      
        //prints the encoded word
        System.out.println("Result: ");
        System.out.println(strCoded);

        System.out.println("Decoding: ");
        System.out.println(strCoded);
      
        byte[] decoded = Base64.decode(strCoded);
        String strDecoded = new String(decoded);

        //prints the decoded word
        System.out.println("Result: ");
        System.out.println(strDecoded);
    }
...

When the previous code is run, the console output shows the following:




Encoding: 
New word to encode using Base64 also special chars like Ñ and ó

Result: 
TmV3IHdvcmQgdG8gZW5jb2RlIHVzaW5nIEJhc2U2NCBhbHNvIHNwZWNpYWwgY2hhcnMgbGlrZSDRIGFuZCDz

Decoding: 
TmV3IHdvcmQgdG8gZW5jb2RlIHVzaW5nIEJhc2U2NCBhbHNvIHNwZWNpYWwgY2hhcnMgbGlrZSDRIGFuZCDz

Result: 
New word to encode using Base64 also special chars like Ñ and ó


You can see that first it prints the String varible called 'word' encoded, after that it decodes the encoded word and prints the decoded word. You only need to have the byte array of data and invoke the proper methods.

This library is pretty simple to use and it gives you the power of transmit binary data as text. As we mentioned before, if you need to send, for example, an Image as text (JSON String? XML?).

This is a small part of the bouncy castle library. It has many encryption/decryption method to be used in your mobile applications. In future posts we will explore some of these methods to add security to our mobile applications.

This concludes our introduction to Base64 in JavaMe (J2ME), wait for the next post where we will use it to send images from the server to the mobile client using, once again, JSON Strings.

see ya soon!


References:

Base64. 2010. Wikipedia [online].
Available on Internet: http://en.wikipedia.org/wiki/Base64
[accessed on December 28 2010].

The Legion of the Bouncy Castle. bouncycastle.org [online].
Available on Internet: http://www.bouncycastle.org/
[accessed on December 28 2010].

33 comments:

  1. Nice tutorial.. i wish you could post more about how Base64 can be used in J2ME to encode an image

    ReplyDelete
  2. Nice tutorial.. i wish you could post more about how Base64 can be used in J2ME to encode an image.
    My email is ell86bu@gmail.com

    ReplyDelete
  3. Sure, here is a link with more info about it:

    http://www.java-n-me.com/2011/01/servlet-gson-vs-jsonme-javame-iii.html

    There you can see how to send an Image in Base64 format from the server to the mobile client.

    I hope it helps!

    bye.

    ReplyDelete
  4. aw,man!
    i cant add that bouncy castle package to my j2me.
    i dunno why.
    can u tell me what should i do?
    thanks be4.

    ReplyDelete
  5. Hi dimitri, send me an email (my address is on my profile) so I can answer you with the library.
    bye.

    ReplyDelete
  6. hello MR. Alexis
    Advance thanks,
    as per you instruction i have download the jar file and attached this file into my application but i have face out one error when i build my application so please i need you help. here i paste that error so please help me to solve this

    Error preverifying class org.bouncycastle.asn1.ASN1GeneralizedTime
    VERIFIER ERROR org/bouncycastle/asn1/DERGeneralizedTime.(Ljava/util/Date;)V:
    Cannot find class java/util/SimpleTimeZone

    ReplyDelete
  7. Hi ShreelTInfo.
    I'm afraid you have downloaded the Java SE version of the library. Please note that the library for Java Me is labeled as J2ME. The direct link to the JavaMe version is:

    http://www.bouncycastle.org/download/lcrypto-j2me-146.zip

    hope it helps.

    ReplyDelete
  8. first, i'm sorry i can't speak english very well...
    advance thanks,
    I made application for French language learning, but the RMS database can't read the character é ê ç î for exercises and dictionary search. What should I do?

    ReplyDelete
  9. Hi Amir, I tried saving and retrieving a record store with the characters you put in the last comment, and It worked. Please send me an email so we can discuss this issue (check my profile to get my email).

    bye

    ReplyDelete
  10. i've already sent email to you...

    ReplyDelete
  11. hello sir
    I am doing a project where i have to send video over gprs network....we are using existing mobile handset which support gprs connection and going to program it using j2me...but i dont have any idea about j2me....can u help me????

    ReplyDelete
  12. Yogs, hello.
    Sure, tell me what you need. Check my email on my profile.

    bye

    ReplyDelete
  13. sir that code from bouncy castle library failed to work,
    plz give me your library

    my email : muzakki.ahmad29@gmail.com

    ReplyDelete
  14. This comment has been removed by the author.

    ReplyDelete
  15. Hi, Blog Informatika. I just sent you the library I used. Hope it works for you.

    ReplyDelete
  16. Dear Alexis
    I am new in J2ME and i am making an application in which user will be able to capture an image and send it to Server using HttpConnection,i saw your post and you have done very good there but the thing is i have copied and pasted your code in my applicaion but still i am facing some problem, first i would like u tell u the java class name for each file then it will be easy for you to tell me where i am missing.....
    ImageCanvas.java - No Problem
    ImageCaptureMidlet.java- Getting Problem ( String imageEncoded =
    encodeImage(imgCanvas.
    getImageBytes()); )
    VideoCanvas.java - No Problem
    and i also wanna ask what i need to do with Base64 file because with the utilisation of same file i am little bit confused have i make to separate file for Base64 or need to add bouncy castle library if yes so please tell me the url location from where i have to download the library.
    Thnx in advance.

    Your Wisher
    Amit

    ReplyDelete
    Replies
    1. Hi Amit, sure I can send you the library, but I don't see your email, please check my profile and email me so I can reply with the library.
      Regards

      Delete
    2. Dear Alexis Sir,
      Thnx for help, My email id is:-android.amitsuri@gmail.com

      Delete
    3. Dear Alexis Sir,
      I am still getting error in code,please see below:-

      cannot find symbol
      encodeImage(imgCanvas.
      symbol: method getImageBytes()
      location: variable imgCanvas of type ImageCanvas

      and i am little confused with working of Bouncy Castle Encoders, Please Mention some more steps in depth for me, i agree you have explained each and everything in your post but sir you know i am new in J2ME so it's possible with me to be confused sometime or somewhere in the program.

      Thnx Again to support me
      Your Wisher
      Amit Suri

      Delete
    4. Hi Amit. First, you need to add the Bouncy Castle library to your project. To do so:

      1. Right click on your project, select the Properties option.
      2. Click on Libraries and Resources
      3. Click on the button Add Jar/Zip. Select the Bouncy Castle library I sent you

      Next is the encodeImage method which is explained in this post:
      http://www.java-n-me.com/2011/02/taking-picture-base64-encoding-in.html


      /**
      * Encodes an array of bytes
      * @param imgBytes Array of bytes to encode
      * @return String representing the Base64 format of
      * the array parameter
      */
      public String encodeImage(byte[] imgBytes) {
      byte[] coded = Base64.encode(imgBytes);
      return new String(coded);
      }

      Delete
  17. Dear Alexis Sir,
    i am also trying to make an application for the user to save data directly into sqlserver database using j2me and to retrieve also.Please help me ASAP.I am also looking to work on Signature in this application user will be able to do sign using small device on a screen (in Textbox or other control)
    Thnx in advance.
    Your Wisher
    Amit

    ReplyDelete
    Replies
    1. Hi Amit.

      I recommend you to read the following post in order to transfer data between server and client (J2ME):
      http://www.java-n-me.com/2010/11/servlet-gson-vs-jsonme-javame.html

      You should define the classes you need to send information to the server and let the server to persist the data to the data base.

      Hope it helps.

      Delete
    2. Dear Alexis Sir,
      Thnx for the recommended link and i will definitely use this in another module but for now i need j2me connectivity with sql server 200, because i have already added all the records to same database.
      Now what i need by you and also requesting to help as usual:
      1. User will login if username and password will match then show more details about user like:- Contact number and Address, Once user will click on that details he/she will be able to edit their records as per need.

      Thnx in advance

      Your Wisher
      Amit Suri

      Delete
  18. Dear Alexis Sir, as usual please also help in above post to make that project ASAP.
    I need your help.
    Thnx in advance

    Your Wisher
    Amit Suri

    ReplyDelete
    Replies
    1. Amit, check this post:
      http://www.java-n-me.com/2010/11/servlet-gson-vs-jsonme-javame.html

      That way, you can send data to the server and the server can validate the information against the data base and persist the data...

      Regards

      Delete
  19. Thanks for the article, you can also check the following article

    Encode And Decode In Base64 Using
    Java

    ReplyDelete
  20. Hello, can you send me one also, sandylq@hotmail.com
    Thanks a lot

    ReplyDelete
    Replies
    1. Hello, please tell me exactly what you need. Regards.

      Delete
    2. Good day sir. can i ask for the build you made? My email is: darkravenxholywizard@gmail.com thanks!

      Delete
    3. Hi Anonymous, I sent you the link. Regards.

      Delete
  21. Hello ,

    I am new on j2me can You please tell me how to convert Image into base64 in j2m2

    ReplyDelete
    Replies
    1. Hi, I did something similar in the following post: http://www.java-n-me.com/2011/02/taking-picture-base64-encoding-in.html

      Delete