0

Hi all, I'm kind of new in Java MIDlet, and i'm having some troubles.
Let say i got a MIDlet project, named APP.java, and the MIDlet project runs smooth without any problem.
And i have another java application, named testing.java, and the java code runs smooth as well.
But when i try to combine testing.java inside MIDlet project, lots of errors shown.
Is it anything to deal with the package? Because my MIDlet project does not have a package.
I'm still working on in, any help would be appreciated! :)

Regards,
Keo

3
Contributors
17
Replies
18
Views
9 Years
Discussion Span
Last Post by peter_budo
Featured Replies
  • 1

    You forgot to give it an instance to which the method should be called [code] Main kpge = new Main(); KeyPair kp = [COLOR="Red"]kpge[/COLOR].generateKeyPair(999); PublicKey pubKey = kp.getPublic();[/code] However with your current code you just complicating your life. Do it like this [code=Java] public class Generator { public PublicKey getPublicKey() … Read More

  • 1

    You can do it in MIDlet, but I will say keep it in another class as that way your code would be easier to manage. Scrolling down hundred of lines is unpleasant sport Read More

0

Hi keofua and welcome to DaniWeb :)

Can you post the error messages that you are getting please? That might help us to identify the problem.

Regards,
d

0

Here are the error messages.

D:\My Documents\NetBeansProjects\PKI\src\PKI\Generator.java:8: cannot find symbol
symbol : class KeyPair
location: package java.security
import java.security.KeyPair;
D:\My Documents\NetBeansProjects\PKI\src\PKI\Generator.java:9: cannot find symbol
symbol : class KeyPairGenerator
location: package java.security
import java.security.KeyPairGenerator;
D:\My Documents\NetBeansProjects\PKI\src\PKI\Generator.java:11: cannot find symbol
symbol : class PrivateKey
location: package java.security
import java.security.PrivateKey;
D:\My Documents\NetBeansProjects\PKI\src\PKI\Generator.java:12: cannot find symbol
symbol : class SecureRandom
location: package java.security
import java.security.SecureRandom;
D:\My Documents\NetBeansProjects\PKI\src\PKI\Generator.java:13: cannot find symbol
symbol : class Security
location: package java.security
import java.security.Security;
D:\My Documents\NetBeansProjects\PKI\src\PKI\Generator.java:22: cannot find symbol
symbol : class KeyPair
location: class pki.Generator
public KeyPair generateKeyPair(long seed)throws Exception {
D:\My Documents\NetBeansProjects\PKI\src\PKI\Generator.java:23: cannot access java.security.Provider
class file for java.security.Provider not found
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
D:\My Documents\NetBeansProjects\PKI\src\PKI\Generator.java:23: cannot find symbol
symbol : variable Security
location: class pki.Generator
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
D:\My Documents\NetBeansProjects\PKI\src\PKI\Generator.java:24: cannot find symbol
symbol : class KeyPairGenerator
location: class pki.Generator
KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("DSA");
D:\My Documents\NetBeansProjects\PKI\src\PKI\Generator.java:24: cannot find symbol
symbol : variable KeyPairGenerator
location: class pki.Generator
KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("DSA");
D:\My Documents\NetBeansProjects\PKI\src\PKI\Generator.java:25: cannot find symbol
symbol : class SecureRandom
location: class pki.Generator
SecureRandom rng = SecureRandom.getInstance("SHA1PRNG", "SUN");
D:\My Documents\NetBeansProjects\PKI\src\PKI\Generator.java:25: cannot find symbol
symbol : variable SecureRandom
location: class pki.Generator
SecureRandom rng = SecureRandom.getInstance("SHA1PRNG", "SUN");
D:\My Documents\NetBeansProjects\PKI\src\PKI\Generator.java:32: cannot find symbol
symbol : class Main
location: class pki.Generator
Main kpge = new Main();
D:\My Documents\NetBeansProjects\PKI\src\PKI\Generator.java:32: cannot find symbol
symbol : class Main
location: class pki.Generator
Main kpge = new Main();
D:\My Documents\NetBeansProjects\PKI\src\PKI\Generator.java:33: cannot find symbol
symbol : class KeyPair
location: class pki.Generator
KeyPair kp = kpge.generateKeyPair(999);
D:\My Documents\NetBeansProjects\PKI\src\PKI\Generator.java:42: cannot find symbol
symbol : class PrivateKey
location: class pki.Generator
PrivateKey priKey = kp.getPrivate();
16 errors

0

Compress your NetBeans project into ZIP file add at it as attachment to your next post. I will try to have look at it as soon as possible. But from above messages it seems you are missing some declarations of various types. Look like you did not merge these two projects properly

0

This are my codes. The whole project is too big to be uploaded.
SIPDemo.java

Generator.java

Attachments
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package pki;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PublicKey;
import java.security.PrivateKey;
import java.security.SecureRandom;
import java.security.Security;


/**
 *
 * @author pin86
 */
public class Generator {

    public KeyPair generateKeyPair(long seed)throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("DSA");
    SecureRandom rng = SecureRandom.getInstance("SHA1PRNG", "SUN");
    rng.setSeed(seed);
    keyGenerator.initialize(1024, rng);

    return (keyGenerator.generateKeyPair());
  }
    public static void main(String[] args) throws Exception {
    Main kpge = new Main();
    KeyPair kp = kpge.generateKeyPair(999);

    System.out.println("-- Public Key ----");
    PublicKey pubKey = kp.getPublic();
    System.out.println("   Algorithm=" + pubKey.getAlgorithm());
    System.out.println("   Encoded=" + pubKey.getEncoded());
    System.out.println("   Format=" + pubKey.getFormat());

    System.out.println("\n-- Private Key ----");
    PrivateKey priKey = kp.getPrivate();
    System.out.println("   Algorithm=" + priKey.getAlgorithm());
    System.out.println("   Encoded=" + priKey.getEncoded());
    System.out.println("   Format=" + priKey.getFormat());
  }

}
package pki;

import java.io.*;
import java.util.*;
import javax.microedition.pki.*;
import javax.microedition.securityservice.*;
import java.security.spec.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.sip.*;


public class SIPDemo extends MIDlet implements CommandListener {
    private static final String appTitle = "SIP Demo";
    private String sipAddress = "Somebody@127.0.0.1";
    private int portReceive = 5070;
    private int portSend = 5070;
    private String message = "Some Message Body";
    private String msgSubject = "Test Message";
    private String signature = "Signature";
    private String signcheck = "check";
    private Display display;
    private Form form = new Form(appTitle);
    private List list;
    private Command goCommand = new Command("Go", Command.ITEM, 1);
    private Command exitCommand = new Command("Exit", Command.EXIT, 0);
    private Command sendCommand = new Command("Send", Command.OK, 1);
    private Command receiveCommand = new Command("Receive", Command.OK, 1);
    private Command signCommand = new Command("Sign", Command.OK, 1);
    private Command signedCommand = new Command("Send", Command.OK, 1);
    private TextField tfAddress;
    private TextField tfPort;
    private TextField tfSubject;
    private TextField tfMessage;
    private TextField tfSign;
    private SipClientConnection sc = null;
    private SipConnectionNotifier scn = null;
    private SipServerConnection ssc = null;
    private byte[] signed = null;

    public SIPDemo() {
        super();
        display = Display.getDisplay(this);
        initList();
        display.setCurrent(list);
    }

     private void initList() {
        list = new List(appTitle, Choice.IMPLICIT);
        list.append("Send Message", null);
        list.append("Receive Message", null);

        list.addCommand(exitCommand);
        list.addCommand(goCommand);
        list.setCommandListener(this);
    }

    private void composeMessage() {
        tfAddress = new TextField("Address ", sipAddress, 50, TextField.LAYOUT_LEFT);
        tfPort = new TextField("Port ", String.valueOf(portSend), 6, TextField.LAYOUT_LEFT);
        tfSubject = new TextField("Subject ", msgSubject, 50, TextField.LAYOUT_LEFT);
        tfMessage = new TextField("Message Body ", message, 150, TextField.LAYOUT_LEFT);
        form.append(tfAddress);
        form.append(tfPort);
        form.append(tfSubject);
        form.append(tfMessage);

        form.addCommand(sendCommand);
        form.addCommand(signCommand);
        form.addCommand(exitCommand);
        form.setCommandListener(this);
        display.setCurrent(form);
    }

    public void receiveMessage() {
        tfPort = new TextField("Port ", String.valueOf(portReceive), 6, TextField.LAYOUT_LEFT);
        form.append(tfPort);
        form.addCommand(receiveCommand);
        form.addCommand(exitCommand);
        form.setCommandListener(this);
        display.setCurrent(form);
    }

    public void signMessage() {
        tfSign = new TextField("Signature", signature, 50, TextField.LAYOUT_LEFT);

        form.append(tfSign);
        form.addCommand(signedCommand);
        form.addCommand(exitCommand);
        form.setCommandListener(this);
        display.setCurrent(form);
    }

    public void receiveTextMessage() {
        Thread receiveThread = new ReceiveThread();
        receiveThread.start();
    }

    public void commandAction(Command c, Displayable s) {
        if (c == exitCommand) {
            destroyApp(true);
            notifyDestroyed();
        } else if (((s == list) && (c == List.SELECT_COMMAND)) || (c == goCommand)) {
            int i = list.getSelectedIndex();

            if (i == 0) { // Send Msg
                composeMessage();
            } else if (i == 1) { // Receive Msg
                receiveMessage();
            }
        } else if (s == form) {
            if (c == sendCommand) {
                message = tfMessage.getString();
                msgSubject = tfSubject.getString();
                sipAddress = tfAddress.getString();
                signcheck = "Normal";
                portSend = getPort(tfPort.getString());

                if (portSend == -1) {
                    return;
                }

                sendTextMessage(message);
            }
            else if (c == signedCommand) {
                message = tfMessage.getString();
                msgSubject = tfSubject.getString();
                sipAddress = tfAddress.getString();
                signcheck = "Signed";
                portSend = getPort(tfPort.getString());
                signature = tfSign.getString();

                if (portSend == -1) {
                    return;
                }

                sendTextMessage(message);
            }
            else if (c == receiveCommand) {
                portReceive = getPort(tfPort.getString());

                if (portReceive == -1) {
                    return;
                }

                form.deleteAll();
                form.removeCommand(receiveCommand);
                receiveTextMessage();
            }

            else if (c == signCommand) {
                signed = null;
                String[] caName = null;

                /*form.deleteAll();
                form.removeCommand(sendCommand);
                form.removeCommand(signCommand);
                signMessage();*/
            }
        }
    }

    /**
     * Converts ASCII to int and ensures a positive number.
     * -1 indicates an error.
     */
    public int getPort(String s) {
        int i = -1;

        try {
            i = Integer.valueOf(s).intValue();
        } catch (NumberFormatException nfe) {
            // don't do anything, the number will be -1
        }

        if (i < 0) {
            Alert alert = new Alert("Error");
            alert.setType(AlertType.ERROR);
            alert.setTimeout(3000); // display the alert for 3 secs
            alert.setString("The port is not a positive number.\n" +
                "Please enter a valid port number.");
            display.setCurrent(alert);

            return -1;
        }

        return i;
    }

    public void startApp() {
        System.out.println("Starting SIP Demo...\n");
    }

    public void sendTextMessage(String msg) {
        SendThread sendThread = new SendThread();
        sendThread.start();
    }

    public void destroyApp(boolean b) {
        System.out.println("Destroying app...\n");

        try {
            if (sc != null) {
                System.out.println("Closing Client Connection...");
                sc.close();
            }

            if (ssc != null) {
                System.out.println("Closing Server Connection...");
                ssc.close();
            }

            if (scn != null) {
                System.out.println("Closing Notifier Connection...");
                scn.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            notifyDestroyed();
        }
    }

    public void pauseApp() {
        System.out.println("Paused...\n");
    }

    /** Send Message Thread */
    class SendThread extends Thread implements SipClientConnectionListener {
        private int recTimeout = 0; // do not wait, just poll

        public void notifyResponse(SipClientConnection sc) {
            try {
                sc.receive(recTimeout);
                form.append("Response received: " + sc.getStatusCode() + " " +
                    sc.getReasonPhrase());
                sc.close();
            } catch (Exception ex) {
                form.append("MIDlet: exception " + ex.getMessage());
                ex.printStackTrace();
            }
        }

        public void run() {
            try {
                sc = (SipClientConnection)Connector.open("sip:" + sipAddress + ":" + portSend);
                sc.setListener(this);

                sc.initRequest("MESSAGE", null);
                sc.setHeader("From", "sip:" + sipAddress);
                sc.setHeader("Subject", msgSubject);
                sc.setHeader("Content-Type", "text/plain");
                sc.setHeader("Signature", signature);
                sc.setHeader("check", signcheck);
                sc.setHeader("Content-Length", Integer.toString(message.length()));

                OutputStream os = sc.openContentOutputStream();
                os.write(message.getBytes());

                os.close(); // close the stream and send the message

                form.deleteAll();
                form.removeCommand(sendCommand);
                form.removeCommand(signCommand);
                form.removeCommand(signedCommand);
                form.append("Message sent...\n");
            } catch (IllegalArgumentException iae) {
                Alert alert = new Alert("Error");
                alert.setType(AlertType.ERROR);
                alert.setTimeout(3000); // display the alert for 3 secs
                alert.setString("Some of the submitted data is invalid.\n" +
                    "Please enter valid information.");
                display.setCurrent(alert);
            } catch (Exception ex) {
                form.append("MIDlet: exception " + ex.getMessage());
                ex.printStackTrace();
            }
        }
    }

      /** Receive Message Thread */
    class ReceiveThread extends Thread {
        private byte[] buffer = new byte[0xFF];

        public void run() {
            try {
                scn = (SipConnectionNotifier)Connector.open("sip:" + portReceive);
                form.append("Listening at " + portReceive + "...");

                // block and wait for incoming request.
                // SipServerConnection is established and returned
                // when a new request is received.
                ssc = scn.acceptAndOpen();

                if (ssc.getMethod().equals("MESSAGE")) {
                    String contentType = ssc.getHeader("Content-Type");

                    if ((contentType != null) && contentType.equals("text/plain")) {
0

My apologies for late reply, but I had some problems with my pc which need it to be sorted before attending to your problem.

Your problems lays with use of packages that are not supported by Microedition. As you can see from JME API there is nothing such as java.security package as we know it from Java SE API. Therefore different approach is need it.

As I do not know full scope of your project I can only point you in general direction. Understanding MIDP 2.0's Security Architecture article by by Jonathan Knudsen would be best place to start.

0

Thanks for the advise and sorry for late replying. I've already solve out the errors, it's the library problem.

Allow me to ask one more question. Lets say i have got one file that act as a random number generation, "Generator.java".
In a MIDlet file, "PKI.java", i want to take the number from "Generator.java" and use in "PKI.java", is it possible? How to do it?

0

Just provide public getter method as in any other Java coding and you are sorted, or create method that will have some return type if you need to pass arguments to generator

0

I see. Can you give some brief step by step coding or some example?
I can do it in C++, but in Java, is a bit difficult for me.
Thanks.

0

In Generator.java

public int generateNum(){
    int number;
    //your process of generating random number
    return number;
}
//OR with argument
public int generateNum(int numArgs){
    int number;
    //your process of generating random number with use of numArgs
    return number;
}

in PKI.java

// somewhere in the coding
Generator generator = new Generator();
int randomNum = generator.generateNum();
//OR
int randomNum = generator.generateNum(10);    // generate number between 0 and 10
0

Thanks for the guidance, i think i starting to have some idea on it.

So, for my case, this is the generator.java

public static void main(String[] args) throws Exception {
Generator kpge = new Generator();
KeyPair kp = kpge.generateKeyPair(999);
PublicKey pubKey = kp.getPublic();
System.out.println("   Algorithm=" + pubKey.getAlgorithm());
System.out.println("   Encoded=" + pubKey.getEncoded());
System.out.println("   Format=" + pubKey.getFormat());
}

Can I get the value of pubKey.getEncoded() inside the PKI.java?
How?

0

I have to tell you, yo are confusing me with jumping between MIDlet and traditional Java.
Can you again explain in detail what you doing as I do not see possible connection between MIDlet and console/GUI based application. You can have MIDlet to HTTP, Web Service or basic networking, but I never seen direct MIDlet to desktop application

0

Sorry for confusing. My concept is as below.

The PKI.java, is the MIDlet, which held the mobile simulator and perform SIP, which involve sending message from one simulator to another.

The Generator.java, is a java file that generate a public and private key for the simulator, the simulator then will receive the keys and do encryption and digital signature and certificate.

Is it possible to do so?

0

Your generator class should be ordinary class not the one with main() method in. Just simple calls with few methods that are called do some precessing and provide a return, something like

public class Generator{

    public Generator(){}

    public PublicKey getPublicKey(){
        KeyPair kp = kpge.generateKeyPair(999);
        PublicKey pubKey = kp.getPublic();
        System.out.println("   Algorithm=" + pubKey.getAlgorithm());
        System.out.println("   Encoded=" + pubKey.getEncoded());
        System.out.println("   Format=" + pubKey.getFormat());
        return pubKey;
    }
}

I did not included any import or try/catch statements, that is something you should be able to add.

PS: Are you working on something like this Nokia Digital signatures - PKIMIDLET example?

0

I see. So now i'm doing something like below:

public class Main {
    public KeyPair generateKeyPair(long seed)throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("DSA");
    SecureRandom rng = SecureRandom.getInstance("SHA1PRNG", "SUN");
    rng.setSeed(seed);
    keyGenerator.initialize(1024, rng);

    return (keyGenerator.generateKeyPair());
    }
    
    public PublicKey getPublicKey() {
    
        Main kpge = new Main();
        KeyPair kp = .generateKeyPair(999);
        PublicKey pubKey = kp.getPublic();
        System.out.println("-- Public Key ----");
        System.out.println("   Algorithm=" + pubKey.getAlgorithm());
        System.out.println("   Encoded=" + pubKey.getEncoded());
        System.out.println("   Format=" + pubKey.getFormat());
        return pubKey;

    }

but i'm getting an error on line 15, a java.lang.Exception error message, and i try/catch it but it was useless. I know i did something wrong. Please correct me.

1

You forgot to give it an instance to which the method should be called

Main kpge = new Main();
        KeyPair kp = kpge.generateKeyPair(999);
        PublicKey pubKey = kp.getPublic();

However with your current code you just complicating your life. Do it like this

public class Generator {
    
    public PublicKey getPublicKey() throws Exception{
    
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("DSA");
        SecureRandom rng = SecureRandom.getInstance("SHA1PRNG", "SUN");
        rng.setSeed(seed);
        keyGenerator.initialize(1024, rng);
        KeyPair kp = keyGenerator.generateKeyPair()
        PublicKey pubKey = kp.getPublic();
        System.out.println("-- Public Key ----");
        System.out.println("   Algorithm=" + pubKey.getAlgorithm());
        System.out.println("   Encoded=" + pubKey.getEncoded());
        System.out.println("   Format=" + pubKey.getFormat());
        return pubKey;
    }
}

When you call Generator method getPublicKey() make sure you do it inside try/catch statement and take care of any exceptions

PS: Please in mind I cannot guaranty that above code will work 100% as I just simplified code provided by you

Votes + Comments
Another very helpful thread by you :)
0

Thanks again. The code works.

Can i generate keypair inside MIDlet?
Or i need to have another java file to generate the keypairs then pass to the MIDlet?

1

You can do it in MIDlet, but I will say keep it in another class as that way your code would be easier to manage. Scrolling down hundred of lines is unpleasant sport

Votes + Comments
Helpful posts in this thread!
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.