need Help in RSA ENCRYPTION
<p>I have problem in below code. <br>
I have created two methods <code>ENCRYPT</code> and <code>DECRYPT</code> for RSA. To get public and private key, I used <code>keyGenerator</code> and <code>KeyPair</code> to generate keys. Our senior told me that <code>KeyPair</code> should be called where us use it, it should not be as declared before the methods.</p>

<p>I tried to create separate method for key generation but when I call that method in both methods( <code>ENCRYPT</code> and <code>DECRYPT</code> ), its going to generate two different keys which does not match hence decryption isn't  working.</p>

<p>I have been told to create constructor and then call it in the method. I don't know how exactly to call it and how it is going to work.</p>

<p>Please take a look at my code below and help me. Thank you.</p>

<pre><code>public class Encryption

{

static byte[] encrypted;    
public Encryption() throws NoSuchAlgorithmException, NoSuchProviderException
{
    KeyPair keypair;
    KeyPairGenerator keygenerator = KeyPairGenerator.getInstance("RSA");
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
    keygenerator.initialize(1024, random);
    keypair = keygenerator.generateKeyPair();
}

public String ENCRYPT(String Algorithm, String Data ) throws Exception
{
    String alg = Algorithm;
    String data=Data;
     if(alg.equals("RSA"))
    {   
        stack enc=new stack();
        //Don't know how to call constructor here
        PublicKey publicKey = keypair.getPublic();
        Cipher cipher;
        cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
         encrypted = cipher.doFinal(data.getBytes());
        System.out.println("Encrypted String -&gt; " + asHex(encrypted));
    }

     return asHex(encrypted);
}
public String DECRYPT(String Algorithm, String Data ) throws Exception
{   
String alg = Algorithm;
String Decrypted="";
if(alg.equals("RSA"))
{   
    //have to call constructor here to get keypair value
    PrivateKey privateKey = keypair.getPrivate();
    Cipher cipher;  
    cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.DECRYPT_MODE, privateKey);
    byte[] dec = cipher.doFinal(encrypted);
    Decrypted=new String(dec);
    System.out.println("Decrypted String[RSA] -&gt; " + Decrypted);

}

return Decrypted.toString();
}
public static String asHex (byte buf[])
{
    StringBuffer strbuf = new StringBuffer(buf.length * 2);
    int i;
    for (i = 0; i &lt; buf.length; i++) 
    {
    if (((int) buf[i] &amp; 0xff) &lt; 0x10)
    strbuf.append("0");
    strbuf.append(Long.toString((int) buf[i] &amp; 0xff, 16));
    }

    return strbuf.toString();
}

}
</code></pre>
