• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1201
  • Last Modified:

Too slow.What's the problem?

Dear ,
  Below is my encryption program:
InputStream cfis=new FileInputStream("gateway.cer");//gateway's cert
             CertificateFactory mycf=CertificateFactory.getInstance("X.509");
             X509Certificate cert=(X509Certificate)mycf.generateCertificate(cfis);
//extract the public key of the cert for encryption      
 PublicKey gatepubkey=cert.getPublicKey();
             System.out.println("gatewaypublickey get!");
             //encrypt to become the digital envelop
             cipher= Cipher.getInstance("RSA/ECB/PKCS1Padding", "ABA");
             byte[] temp1=prelop.getBytes("UTF8");
             byte[] tempraw1=cipher.doFinal(temp1);
             DEnvelop = encoder.encode(tempraw1);

However,each time when the program arrives the line
 cipher= Cipher.getInstance("RSA/ECB/PKCS1Padding", "ABA");
it will stop for nearly 100 seconds and then proceed on.Why so slow?
  • 5
  • 2
  • 2
  • +1
1 Solution
hpchong7Author Commented:
Sorry.It should be the line
byte[] tempraw1=cipher.doFinal(temp1);
cipher=Cipher.getInstance("RSA/ECB/PKCS1Padding", "ABA");

How can I make it faster?
hpchong7Author Commented:
May be I post the full code here:
import java.lang.*;
import java.net.*;
import java.io.*;
import java.util.*;
import java.io.*;
import java.security.*;
import java.security.cert.*;
import sun.misc.*;
import javax.crypto.*;

public class SendOIPI{
      public static boolean state=false;
      public static String base64epm;  //Encrypted Payment message
      public static String base64p;    //PI message digest
      public static String DualS;    //Dual signature
      public static String OI="<Ticket>5<Venue>Cultural Center";
      public static String DEnvelop;  //the digital envelop
      //public void sendoipi(PrintWriter out,Socket skt)
      public SendOIPI(String gatefile)throws Exception
      {  //get the oi and pi from wtab3 and wtab1 respectively
            String PI="Master,1111-1111-1111-1111,11/2000";
            String prelop;
            String base64o,base64c,base642,base643;
            String emessage;
            String alias="test";
            String store="client.store";
            String keypass="hpchong7";//keystore password
            Key key;
            Cipher cipher;
            char[] pwd=new char[keypass.length()];
            //message digest factory
            MessageDigest md=MessageDigest.getInstance("SHA-1");
            BASE64Encoder encoder = new BASE64Encoder();

            //message digest for payment information
            byte[] buffer1=new byte[8192];
            int len1=buffer1.length;
            byte[] raw1=md.digest();

            //message digest for order instruction
            byte[] buffer2=new byte[8192];
            int len2=buffer2.length;
            byte[] raw2=md.digest();

            //concat them
            String PIOI=base64p+base64o;
            //Hash PIOI
            byte[] buffer3=new byte[8192];
            int len3=buffer3.length;
            byte[] raw3=md.digest();

            //encrypt base64c using Alice's private key
            //load the keystore and get the private key first
            FileInputStream fisk=new FileInputStream(store);
        KeyStore ks = KeyStore.getInstance("JKS", "SUN");
            PrivateKey priv=(PrivateKey)ks.getKey(alias,pwd);
            cipher= Cipher.getInstance("RSA/ECB/PKCS1Padding", "ABA");
            cipher.init(Cipher.ENCRYPT_MODE,(Key)priv);//private key of the store
            //encrypt the PIOI digest base64c first
            byte[] stringBytesx=base64c.getBytes("UTF8");
            byte[] rawx=cipher.doFinal(stringBytesx);
            //encode it using the base64
            DualS = encoder.encode(rawx);
            System.out.println("Encoded Dual signature:"+DualS);  //dual signature

            //Get the randomly generated symmetric key
            //OI message digest:base64o
            //dual signature:DualS
            emessage=PI+"***"+DualS+"***"+base64o;  //prepare send to merchant then to payment gateway
            try { ObjectInputStream in = new ObjectInputStream(
                    new FileInputStream("ckey.ser"));
            catch (FileNotFoundException fnfe) {
            KeyGenerator generator = KeyGenerator.getInstance("DES");
            //generator.init(new SecureRandom());
            key = generator.generateKey();  //It is the encrypt symmetric key
            //jsut fore speed.Would be removed.
            ObjectOutputStream out = new ObjectOutputStream(
        new FileOutputStream("ckey.ser"));
            // encrypt the emessage to become the encrypted payment message
            cipher= Cipher.getInstance("DES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE,key);//key that already generated
            byte[] stringBytesy=emessage.getBytes("UTF8");
            byte[] rawy=cipher.doFinal(stringBytesy);
            base64epm = encoder.encode(rawy);
            System.out.println("Encoded-Encrypted Payment Message"+base64epm);
            //create the digial envelop(key + PI)
            //IN spec,though,account data,take it as payment information
            //for key,turn to bytes,then base64 encode
             byte[] keybyte=key.getEncoded();
             String ekeystring=encoder.encode(keybyte);
             prelop=ekeystring+"***"+PI;  //*** to separate key and PI
             //encrypt the pre-envelop(prelop) using the public key of gateway
             //1.read gateway's cert
             InputStream cfis=new FileInputStream("gateway.cer");//(filename[0]);  //gateway's cert
             CertificateFactory mycf=CertificateFactory.getInstance("X.509");
             X509Certificate cert=(X509Certificate)mycf.generateCertificate(cfis);
             PublicKey gatepubkey=cert.getPublicKey();
             System.out.println("gatewaypublickey get!");
             //encrypt to become the digital envelop
             cipher= Cipher.getInstance("RSA/ECB/PKCS1Padding", "ABA");
             byte[] temp1=prelop.getBytes("UTF8");
             //The line below if very slow
             byte[] tempraw1=cipher.doFinal(temp1);
             DEnvelop = encoder.encode(tempraw1);  //base64 encoding of Digital envelop
             System.out.println("All things okay!");
            //1.Encrypted message disgest:base64epm
            //2.PI message Digest:base64p
            //4.Daul signature:DualS
            //5.Digital envelop:DEnvelop
            //6.client cert,send later:client.cer
             System.out.println("Dual Signature:"+DualS);
             System.out.println("Digital Envelop:"+DEnvelop);
      public static String getEPM()
      { return base64epm;
      public static String getPIdigest()
      { return base64p;
      public static String getOI()
      { return OI;
      public static String getdualS()
      { return DualS;
      public static String getDEnvelop()
      { return DEnvelop;
      public static void setstate(boolean abc)
      public static boolean getstate()
            return state;

I don't know anything abt Java Cryptography .I have seen that u r very much working on this / interested ,as u have asked some questions on it ,but why don't u buy any good book like this?

even if u dont buy that ,download readymade code ,click on Examples ...

hope it helps u out.

I always like to go for O'Reilly Books.

A handy tip go to http://www.oreilly.com/catalog and search for topic and DOWNLOAD FREE Code.

Isn't it wonderful ?

Cloud Class® Course: MCSA MCSE Windows Server 2012

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).


what's the size of prelop (in bytes)  at "reach2" ?? Also, RSA encryption is always a bit slow(especially if you are using a high no. of bits for the key, like you do in certificates). So it will be a bit slow anyhow.
hpchong7Author Commented:
Dear Mbormann:Thanks for your tips.I always work on java crypto because my final year project requires me to do so.I've bought that book,but still remain many questions.Thanks for your help!

Dear Ash:thanks for your comment.So may be I cannot solve the bottle neck.

BTW,I want to write an article(in my report,about 500 words)why java is so slow.Can anyone give me some useful URL?
Check out this link


Jim CakalicSenior Developer/ArchitectCommented:
There are a number of good articles on JavaWorld about performance. Here are links to a few:

Basics of Java Platform Performance

The importance of getting on the right road to a fast Java

Performance problem or design problem?

Performance Programming, Part 1 -- Smart Object Management

Performance Programming, Part 2 -- The cost of Casting

Performance Programming, Part 3 -- Managing Collections

You might also try searching the security archives at javasoft

where you will find postings such as this:

--- begin quote ---
> I'm experimenting with generating DH key pairs for use
> with a KeyAgreement. I can generate DH key pairs for
> strengths of 64, 128, and 256, but 512 or higher seems
> to hang my machine.  (I suspect that it's not hanging,
> it's just taking a very long time.)  I have a Pentium 90.

Your machine is not hanging - it does take a long time!

Choosing a strong prime modulus "p" takes most of the time!

You can speed up the key generation by using pre-generated
Diffie-Hellman parameters (e.g., the ones defined by SKIP).

Usually, the Diffie-Hellman parameters are defined by some
central authority (which generated them once only), and are
not generated on a per-connection basis.

Try this, and you will see the difference!
--- end quote ---

Best regards,
Jim Cakalic
hpchong7Author Commented:
Adjusted points from 5 to 10
hpchong7Author Commented:
Dearjim cakalic, sorry  for grading it so late as I am now busying on my exam and final year project!
Jim CakalicSenior Developer/ArchitectCommented:
No problem. Glad you got a satisfactory answer.

Best regards and good luck!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

  • 5
  • 2
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now