Bouncy Casle in J2ME

Hi I have done encryptionin bouncycastle algorithm but it tells the following error:
ERROR:
java.lang.NoClassDefFoundError: java/security/SecureRandom: Cannot create class in system package
PROGRAM:
import java.math.BigInteger;
import java.security.SecureRandom;
import org.bouncycastle.crypto.AsymmetricBlockCipher;
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.crypto.encodings.PKCS1Encoding;
import org.bouncycastle.crypto.engines.RSAEngine;
import org.bouncycastle.crypto.generators.RSAKeyPairGenerator;
import org.bouncycastle.crypto.params.RSAKeyGenerationParameters;
import org.bouncycastle.crypto.params.RSAKeyParameters;
import org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class Encryption extends MIDlet implements CommandListener
     Form f = new Form("MyForm");
     Command okCmd = new Command("Ok",Command.OK,1);
     Command exitCmd = new Command("Exit",Command.EXIT,2);
     private RSAPrivateCrtKeyParameters _RSAPrivateKey;
     private RSAKeyParameters _RSAPublicKey;
     public void startApp()
          f.addCommand(okCmd);
          f.addCommand(exitCmd);
          f.setCommandListener(this);
          Display.getDisplay(this).setCurrent(f);
     public void pauseApp()
     public void destroyApp(boolean unconditional)
     public void commandAction(Command c, Displayable d)
          if (c == okCmd)
               functionCall();
          if (c == exitCmd)
               notifyDestroyed();
     void functionCall()
          String theStringBeforeEncryption = "String to encrypt";
          String theStringAfterEncryption = null;
          byte[] theEncryptedString;
          try
               System.out.println(theStringBeforeEncryption);
               generateRSAKeyPair();
               theEncryptedString = RSAEncrypt(theStringBeforeEncryption.getBytes());
               theStringAfterEncryption = new String(RSADecrypt(theEncryptedString));
               System.out.println(theStringAfterEncryption);
          catch (Exception e)
               // TODO Handle exception!
               e.printStackTrace();
     }//end of functionCall()
     private void generateRSAKeyPair () throws Exception
          SecureRandom theSecureRandom = new SecureRandom();
          BigInteger thePublicExponent = new BigInteger("10001", 16);
          RSAKeyGenerationParameters theRSAKeyGenParam =
               new RSAKeyGenerationParameters(thePublicExponent, theSecureRandom, 1024, 80);
          RSAKeyPairGenerator theRSAKeyPairGen = new RSAKeyPairGenerator();
          theRSAKeyPairGen.init(theRSAKeyGenParam);
          AsymmetricCipherKeyPair theKeyPair = theRSAKeyPairGen.generateKeyPair();
          _RSAPrivateKey = (RSAPrivateCrtKeyParameters) theKeyPair.getPrivate();
          _RSAPublicKey = (RSAKeyParameters) theKeyPair.getPublic();
     private byte [] RSAEncrypt (byte [] toEncrypt) throws Exception
          if (_RSAPublicKey == null)
               throw new Exception("Please generate RSA keys first in order to work");
          AsymmetricBlockCipher theEngine = new RSAEngine();
          theEngine = new PKCS1Encoding(theEngine);
          theEngine.init(true, _RSAPublicKey);
          return theEngine.processBlock(toEncrypt, 0, toEncrypt.length);
     private byte [] RSADecrypt (byte [] toDecrypt) throws Exception
          if (_RSAPrivateKey == null)
               throw new Exception("Please generate RSA keys first in order to work");
          AsymmetricBlockCipher theEngine = new RSAEngine();
          theEngine = new PKCS1Encoding(theEngine);
          theEngine.init(false, _RSAPrivateKey);
          return theEngine.processBlock(toDecrypt, 0, toDecrypt.length);
please Help me
Regards,
Nelson

There is no class by name "SecureRandom" in "java.security" package as far as CLDC/MIDP API's available for the application developer are concerned with.
May be you need to check out the alternative for SecureRandom class provided by the J2ME implementation of the BouncyCastle API.
~Mohan

Similar Messages

  • Encrypting data J2ME

    Hi
    I am developing a number of applications using J2ME. They run on mobile phones and need to be able to send data to a server. I need to encrypt this data as it contains personal information about the user. I cant use HTTPS because some of the applications use MIDP 1.0 and only support HTTP.
    So I want to encrypt the data myself and I was wondering if you could help me with my approach and answer some questions...
    I think the best way is to use RSA public/private keys in combination with a symmetric encrypting algorithm. So the mobile will have the public key part and the server will have the private key. The data will be encrypted using a symmetric algorithm. The key used in the encryption will then be encrypted using the public key. Both the encrypted key and the encrypted data will then be sent to the server. The server uses its private key to decrypt the key and then use the key to decrypt the data.
    How does that sound? I will be using Bouncy Castle crypto. What is the best way to generate a public/private key pair? I then need to somehow include the public key with the application. Should I randomly generate the symmetric key myself?
    Also what algorithm would you suggest for encrypting the data. Remember that it is on a resource constrained mobile device.
    If you have any other comments I would like to hear them. Thanks for your time.

    Thanks for the pointer. The thing is we changed our minds. We discovered strong encryption was not needed since our scheme is like the DVD encryption. The data is unencrypted by the application used by the person that does not have to know the data.
    We went with Rot13. jeje
    Thanks anyway.

  • Encryption in J2ME

    Hello all
    I have a j2EE application using Mysql database. I'm interested in providing an extension to the system so that data can be input using a mobile using J2ME. The midilet interacts with a http connection servelet which in turn updates the database. What I'm looking for is proper encryption of data send from/to the mobile. does J2ME support encryption(like triple DES). How do i do it? if this is not possible then what is the solution.
    thanks in advance.

    Hi,
    There are two ways to achieve this.
    one is either use bouncy castle, as mentioned in the previous replies, or you can also use the SATSA(security and trust services API), a crypto API for MIDP phones, which is an official JSR. (JSR-177)
    IT all depends on the phone capabilities. I would put my money on SATSA because it is faster than Bouncy castle, but since it is a JSR, your phone may / may not support it.

  • Md5 in j2me

    I'm building an j2me application and I want use md5 authentication.
    Is there a way to implement the encrypting of a string taken from a text box in md5?
    Thanks

    The bouncy castle api might help you with that: http://www.bouncycastle.org/
    Though maybe, basic base64 auth is much easyer to do..

  • Authentication in j2me..

    Hi all,
    I would need some info on how to authenticate user while workin with j2me mobile applications...Thanks

    The bouncy castle api might help you with that: http://www.bouncycastle.org/
    Though maybe, basic base64 auth is much easyer to do..

  • Bouncy castle???

    can v use bouncy castle api's in java????
    i have used it in j2me....can it also b used with standard edition???

    There must be some tutorial information on their website. I know they have an examples on http://www.bouncycastle.org/documentation.html. Basically, you can use it in two ways. One way is exclusively through the JCE. You use the same Java classes like Cipher, MessageDigest, Signature, etc, but you explicitly specify the provider in the getInstance method. Here is small code fragment example
    import java.io.*;
    import java.security.*;
    import javax.crypto.*;
    import org.bouncycastle.jce.provider.BouncyCastleProvider;
    public class BCastle1
        public static void main(String[] args) throws Exception
            Security.addProvider(new BouncyCastleProvider());
            // "BC" is the name of the BouncyCastle provider
            KeyGenerator keyGen = KeyGenerator.getInstance("DES", "BC");
            keyGen.init(new SecureRandom());
            Key key = keyGen.generateKey();
            Cipher encrypt = Cipher.getInstance("DES/CBC/PKCS5Padding", "BC");
            encrypt.init(Cipher.ENCRYPT_MODE, key);
            ByteArrayOutputStream bOut = new ByteArrayOutputStream();
            CipherOutputStream cOut = new CipherOutputStream(bOut, encrypt);
            // ... other stuff omitted ....
    }Another way is to use the lightweight API directly. You use the classes whose Javadocs are at http://www.bouncycastle.org/docs/docs1.5/index.html just like any other Java classes.

  • Send email from j2me through servlet

    Hi people,
    i hope you can help me because i am new in network programming.
    I am trying to send email from j2me to googlemail account I have 2 classes EmailMidlet (which has been tested with wireless Toolkit 2.5.2 and it works) and the second class is the servlet-class named EmailServlet:
    when i call the EmailServlet, i get on the console:
    Server: 220 mx.google.com ESMTP g28sm19313024fkg.21
    Server: 250 mx.google.com at your service
    this is the code of my EmailServlet
    import java.io.*;
    import java.net.Socket;
    import java.net.UnknownHostException;
    import java.text.*;
    import java.util.Date;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class EmailServlet extends HttpServlet {
       public void doPost(HttpServletRequest request, HttpServletResponse response)
             throws IOException, ServletException {
          System.out.println("____emailservlet.doPost");
          response.setContentType("text/plain");
          PrintWriter out = response.getWriter();
          System.out.println("______________________________");
          out.println();
          String to = request.getParameter("to");
          System.out.println("____________________________to" + to);
          String subject = request.getParameter("subject");
          String msg = request.getParameter("msg");
          // construct an instance of EmailSender
          System.out.println("servlet_to" + to);
          send("[email protected]", to, subject, msg);
          out.println("mail sent....");
       public void send(String from, String to, String subject, String msg) {
          Socket smtpSocket = null;
          DataOutputStream os = null;
          DataInputStream is = null;
          try {
             smtpSocket = new Socket("smtp.googlemail.com", 25);
             os = new DataOutputStream(smtpSocket.getOutputStream());
             is = new DataInputStream(smtpSocket.getInputStream());
          } catch (UnknownHostException e) {
             System.err.println("Don't know about host: hostname");
          } catch (IOException e) {
             System.err
                   .println("Couldn't get I/O for the connection to: hostname");
          if (smtpSocket != null && os != null && is != null) {
             try {
                os.writeBytes("HELO there" + "\r\n");
                os.writeBytes("MAIL FROM: " + from + "\r\n");
                os.writeBytes("RCPT TO: " + to + "\r\n");
                os.writeBytes("DATA\r\n");
                os.writeBytes("Date: " + new Date() + "\r\n"); // stamp the msg
                                                    // with date
                os.writeBytes("From: " + from + "\r\n");
                os.writeBytes("To: " + to + "\r\n");
                os.writeBytes("Subject: " + subject + "\r\n");
                os.writeBytes(msg + "\r\n"); // message body
                os.writeBytes(".\r\n");
                os.writeBytes("QUIT\r\n");
                // debugging
                String responseLine;
                while ((responseLine = is.readLine()) != null) {
                   System.out.println("Server: " + responseLine);
                   if (responseLine.indexOf("delivery") != -1) {
                      break;
                os.close();
                is.close();
                smtpSocket.close();
             } catch (UnknownHostException e) {
                System.err.println("Trying to connect to unknown host: " + e);
             } catch (IOException e) {
                System.err.println("IOException: " + e);
       } 1.when i print "to" in EmailServlet also:
      String to = request.getParameter("to");
          System.out.println("____________________________to" + to);  it show null on the console :confused:
    2. ist this right in case of googlemail.com?
      smtpSocket = new Socket("smtp.googlemail.com", 25);  I would be very grateful if somebody can help me.

    jackofall
    Please don't post in old threads that are long dead. When you have a question, please start a topic of your own. Feel free to provide a link to an old thread if relevant.
    I'm locking this thread now.
    db

  • J2me and java card, need help to communicate

    we are trying to put together a reader to read smartcards using j2me and we figure that it would be easiest if we could develop it to work with java cards rather than standard smart cards, the problem is we get garbage when we communicate to it, the chip sends us crap, any suggestions what might be wrong, any calls we might be missing, has anyone worked with j2me and java cards or smart cards, any help would be appreciated.
    einar

    .... reader app and the ME behind it .... smells like mobile ....
    First of all - if you want to have one mobile application running on this just make sure that whatever is written in ME can use drivers from the reader chip ....
    Workin on the PC is something completely different. There was one good example how to develop one host application in Java provided with the JCOP tools long ago ... I don't know if this is now in the new Eclipse tools.
    But - there was a small API provided that can give you good hints what to do - and - once you have it on the reader side - you can easily integrate ME methods with this ...

  • Image Processing in j2me

    Hi All,
    I want to do image processing in mobile application(j2me).
    But there are not enough java packages in mobile environment.
    How to do it please let me know if any body knows.
    Thanks.

    brightness: convert every RGB pixel to HSB -> increase luminance by constant value -> convert back to RGB
    contrast: convert every RGB pixel to HSB -> multiply luminance by constant value-> convert back to RGB
    You can also do both in one go.

  • UTF-8 encoding in J2ME

    Hello,
    I'm currently developing J2ME application for downloading bus schedules.
    The data that I download is in polish language (eg. bus directions, stop names etc). These are xml files generated by a php script encoded in UTF-8.
    The problem is that I don't know how to display that properly, so that all the polish characters are what they're supposed to be.
    Some of my code for downloading content:
    String getXML(String url)
            HttpConnection cn = null;
            InputStream str = null;
            //DataInputStream strd = null;
            StringBuffer sb = null;
            try
                int code;
                cn = (HttpConnection) Connector.open(url);
                code = cn.getResponseCode();
                if (code == HttpConnection.HTTP_OK)
                    str = cn.openInputStream();
                    // strd = new DataInputStream(str);
                    sb = new StringBuffer();
                    InputStreamReader r = new InputStreamReader(str, "UTF-8");
                    int total = 0;
                    int read = 0;
                    while ((read = r.read()) >= 0)
                        total++;
                        sb.append((char) read);
                    return sb.toString();
                else
                    throw new Exception("Nie udało się połączyć z serwerem");
            catch (Exception e)
                return null;
            finally
                try
                    if (str != null)
                        str.close();
                    if (cn != null)
                        cn.close();
                catch (Exception e)
        }And parsing it:
    InputStreamReader reader = null;
                    String xml = getScheduleXML(getSel_Line(), null, null);
                    ByteArrayInputStream stream = new ByteArrayInputStream(xml.getBytes());
                    reader = new InputStreamReader(stream, "UTF-8");
                    parser.setInput(reader);
                    while (parser.next() != KXmlParser.END_DOCUMENT)
                        if ((parser.getEventType() == KXmlParser.START_TAG) && (parser.getName().equalsIgnoreCase("direction")))
                                String d = (String) parser.getAttributeValue(0);
                                v.addElement(d);
                                String d2 = (String) parser.getAttributeValue(1);
                                v2.addElement(d2);
                    }What do I do wrong? What is missing?

    Problem solved. I had to add "UTF-8" parameter to getBytes method.

  • How to send sms from gsm modem(AT commands) to j2me application(not inbox)

    hi
    i want to send sms from gsm modem to a j2me application, for this to happen i have to send sms to a specific port in which j2me application is running.when i m trying to send sms from modem it doesnt go to application it goes to inbox.
    is it related to udh settings if yes then how do i set port no in settings?if no what are the other ways.

    Hi Vignesh,
    Might be you can call ActiveX or DLL objects of the software installed for modem from LabVIEW, if it is unblocked.
    Have a  look on the link > http://zone.ni.com/devzone/cda/tut/p/id/2983
    CLA 2014
    CCVID 2014

  • Problem with Display.setCurrentItem() using J2ME-Polish

    Hi,
    I am fairly new to J2ME-polish and have encountered a situation that I am having a problem with. I am loading a form with a number of String Items. When I display the form I would like to focus to the last String Item that has been placed on the form. I have been using Display.setCurrentItem() in J2ME but when I try using it in J2ME-Polish I receive this message :"de.enough.polish.ui.Screen (3022): Screen: unable to focus item (did not find it in the container or is not activatable ) "
    Below is a snippet of my code.
            // si14 in a StringItem defined earlier in the code
            // It is the last stringItem placed into the form
            form.append(si14);
            display = Display.getDisplay(this);
         display.setCurrent(form);
         display.setCurrentItem(form.get(0));Thanks

    http://forums.sun.com/thread.jspa?threadID=686256&messageID=10864566

  • How to get the Mobile information by using J2ME application

    hi all,
    I am lakshman.I am developing an application in j2me,I want my program compatible to all mobile devices.
    I want to know properties and the device information with the help of a j2me application.I got the information with the help of System.getProperty(String).I found some of the information like sms,videocapture,and some of the values and the variables ... in the following
    platform...null
    encoding...ISO-8859-1
    configuration...CLDC-1.0
    profile...MIDP-2.0
    locale...null
    fileconnection...1.0
    comport...null
    hostname...iwmc-07
    sms...null
    smartcard...null
    location version...null
    sip version...null
    m3gversion...null
    mms...null
    videocapture...false
    videoencoding...null
    snapshotencoding...encoding=png encoding=jpeg encoding=gif encoding=bmp
    audioencoding...null
    supaudcap...false
    suprecod...false
    supmixing...false
    mediaversion...1.1
    streamcont...null
    I want to know these are the only variables or is there are lot...
    Now my question is I want to get the information of the service provider and also the present location that the mobile was present.I think there was some method to get that ...I want to get what firmware it was using .
    Can anybody tell me that way and also the package to get the information
    thanks in advance
    lakshman

    hi all,
    I am lakshman,I found the answer for my question,By using the Location API(jsr179).It was not include in the WTK2.2.for that i have downloaded the WTK2.3 then i have implemented the location api in the application and it was working.
    And I have the following warning...
    Warning: To avoid potential deadlock, operations that may block, such as
    networking, should be performed in a different thread than the
    commandAction() handler.
    I am running the application from my Emulator(by using the default color phone).I have to check that in the device.
    Can any body please give me the way to fix that,i want to test my application from my emulator is that is possible if possible ...how?.what is the procedure to implement..
    thanks in advance

  • Sending an email through J2ME

    What is the easiest way to send an email to an email account using J2ME?
    I browsed google, and all of the results appeared very complex. Is there a simple way to do it (like you can with PHP)?
    Thanks!

    My phone doesn't have a mobile mailer.
    I can't believe emailing is so difficult!
    Would this solution work:
    import javax.microedition.lcdui.*;
    import javax.microedition.midlet.*;
    import javax.microedition.io.*;
    import java.io.*;
    import java.util.*;
    public class Emailer
         String url;
         String to;
         String from;
         String subj;
         String msg;
         HttpConnection conn;
         OutputStream output;
         public Emailer(String url, String to, String from, String password,
                                                String subj)
              this.url = url;
              this.to = to;
              this.from = from+"/"+password;
              this.subj = subj;
         public boolean sendEmail(String msg)
              this.msg = msg;
              try
                   StringBuffer buffer = new StringBuffer();
                   buffer.append("To: " + to);
                   buffer.append("From: " + from);
                   buffer.append("Subject: " + subj);
                   buffer.append("Message: " + msg);
                   conn = (HttpConnection) Connector.open(url);
                   conn.setRequestMethod(HttpConnection.POST);
                   output = conn.openOutputStream();
                   int i = 0;
                   char c;
                   while((c = buffer.charAt(i)) != 0)
                        output.write(c);
                        i++;
              catch (Exception e)
                   return false;
              return true;
    }I tried it, but I never got the email...
    Also, is there a simple way to read from .txt files?
    Thanks!

  • How to set up on device debuging with J2ME SDK 3.0 and window mobile 6.5?

    I got some infomation about setting up on device debuging in J2ME SDK 3.0 with real device(e.g samsung windown mobile B7330). When I start debuging on device, I got exception when open RMS
    javax.microedition.rms.RecordStoreException: error opening record store fileHere my code:
    public void saveProfile() {
            byte[] data = toByteArray();
            try {
                rs = RecordStore.openRecordStore("kunkunProfile", true);
                for (RecordEnumeration e = rs.enumerateRecords(null, null, false); e.hasNextElement();) {
                    int id = e.nextRecordId();
                    rs.deleteRecord(id);
                rs.addRecord(data, 0, data.length);
                rs.closeRecordStore();
            } catch (Exception ex) {
                System.out.println("Exception in OpenRecordStore..." + ex.getMessage());
                try {
                    rs.addRecord(data, 0, data.length);
                    rs.closeRecordStore();
                } catch (Exception e) {
                ex.printStackTrace();
        }Anybody help me? I am stuck here.

    Hi dominikg,
    At first, You can try to restart the device-manager from system tray.
    If it doesn't help, then try the following:
    - stop the device manager
    - Remove c:\Docement and Settings\<your User>\javame-sdk folder.
    - Ran the device manager from <SDK>/bin directory
    - try to debug again.
    Did you tried to change port 51307 to another.
    Early access build had some problems with device manager, I hope that final release will be better :)
    BR,
    Igor

Maybe you are looking for

  • Game Center nickname password question:

    My daughters each have their own nicknames for Game Center on their iPod Touches. Each nickname has its own password. My youngest can't remember her password. Since I updated her iOS, I have to log her back into her Game Center account. Is there a wa

  • Need the escaletion template in excel format

    Hi, Please send me the escalation template for which we need to prepare for customer post go live, sp that he can submit his cooncerns in that template and it can be addressed. Thanks, Manu

  • Why is my media formatted as data on my ipod

    My windows media files are downloaded to my ipod and it has totally filled up all my space. And I don't know how to remove them. Apparently it is saved on the ipod as data and I can't find the file. And i hav totally deleted the windows media program

  • Will Photoshop 6.0 be compatible with Windows 8?

    As Windows XP Pro is going to be obsolete after April 2014, I am wondering if my version of Photoshop 6.0 will be compatible with Windows 8? I was thinking of having my tech person install that version of Windows on a new system when spring rolls aro

  • InDesign CS6 Folio Builder Crashes Version 32.0.0

    Hi, I've only just installed the DPS Desktop Tools for InDesign CS6 and the installation worked perfectly although upon opening Folio Builder in InDesign it results in the program crashing... So far I've re installed InDesign I've tried a few other s