0

I do RSA encryption and having a problem. I want to encrypt a string.To convert the string, I already have the rsHex array to convert it.. I run the source code but it give me error say "the system cannot find the file specified" Here is my source code. How do I solve his? Thanks for helping me :)

import de.flexiprovider.api.keys.PrivateKey;
import de.flexiprovider.api.keys.PublicKey;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

public class RSA {

private String str, s;
private String chipertext;
private byte[] cipherData;


public RSA(String string) throws Exception {

    try {


        String input = string;
        FileReader read = new FileReader(input);
        BufferedReader reader = new BufferedReader(read);
        while ((s = reader.readLine()) != null) {
        byte[] theByteArray = s.getBytes();
           setUserinput(string);
            rsHex(theByteArray);
}


    } catch (Exception ex) {
        Logger.getLogger(RSA.class.getName()).log(Level.SEVERE, null, ex);
    }

     //Creating an RSA key pair in Java
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); //instance of KeyPairGenerator
            kpg.initialize(1024);//bit length of the modulus that  required
            KeyPair kp = kpg.genKeyPair();//returns a KeyPair object
            Key publicKey = kp.getPublic(); //pull out the public and private keys
            Key privateKey = kp.getPrivate();

            //Saving the public and private key
            //private key will be placed on our server, and the public key distributed to clients.
            KeyFactory fact = KeyFactory.getInstance("RSA");
            RSAPublicKeySpec pub = (RSAPublicKeySpec) fact.getKeySpec(publicKey, RSAPublicKeySpec.class);
            RSAPrivateKeySpec priv = (RSAPrivateKeySpec) fact.getKeySpec(privateKey, RSAPrivateKeySpec.class);

            // Save the file to local drive
            saveToFile("c:\\public.key", pub.getModulus(), pub.getPublicExponent());
            saveToFile("c:\\private.key", priv.getModulus(),priv.getPrivateExponent());

     }
private void rsHex(byte[] bytes) throws Exception {
    StringBuilder hex = new StringBuilder();
    for (byte b : bytes) {
        String hexString = Integer.toHexString(0x00FF & b);
        hex.append(hexString.length() == 1 ? "0" + hexString : hexString);
    }
 setChipertext(hex.toString());
 }

//save the moduli and exponents to file, we can just use boring old serialisation
public void saveToFile(String fileName, BigInteger mod, BigInteger exp) throws  IOException {
    FileOutputStream f = new FileOutputStream(fileName);
    ObjectOutputStream oos = new ObjectOutputStream(f);
    oos.writeObject(mod);
    oos.writeObject(exp);
    oos.close();
 }

////Encryption
//initialise the cipher with the public key that we previously saved to file.
   PublicKey readKeyFromFile(String keyFileName) throws IOException {
  PublicKey key = null;

  try {
    FileInputStream fin = new FileInputStream(keyFileName);
    ObjectInputStream ois = new ObjectInputStream(fin);
    BigInteger m = (BigInteger) ois.readObject();
    BigInteger e = (BigInteger) ois.readObject();
    RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(m, e);
    KeyFactory fact = KeyFactory.getInstance("RSA");
        java.security.PublicKey pubKey = fact.generatePublic(keySpec);
    ois.close();
  }
  catch (Exception e) {
   e.printStackTrace();
  }
 return key;
   } 


public void rsaEncrypt(String str)throws Exception {

PublicKey pubKey = readKeyFromFile(str);
  Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, pubKey);//initialise the cipher
    cipherData = cipher.doFinal(str.getBytes());//passing in the data to be encrypted


    rsHex(cipherData);


  }


 public String getUserinput() {
    return str;
  }

  public String getChipertext() {
     return chipertext;
  }

  public void setUserinput(String input) {
    this.str = input;
  }

  public void setChipertext(String chipertext) throws Exception {
    this.chipertext = chipertext;

   }



  }


     ----main Program------
  import java.util.Scanner;

 public class TWO{
  public static void main(String[] args) throws Exception{


    Scanner scan = new Scanner(System.in);

    System.out.println("Insert your string");
    String str = scan.nextLine();

            RSA two = new RSA(str);


    System.out.println("Encrypted: "+ two.getChipertext());



}
}
7
  • 1
    I see that for the actual RSA gubbinry you're using my suggested code from here javamex.com/tutorials/cryptography/rsa_encryption.shtml Which actual line are you getting the error on -- I imagine it's some local setup issue? Commented May 23, 2012 at 16:59
  • I already use the coding from that page. Now I facing the problem to read the input value Commented May 23, 2012 at 17:07
  • Yes, so perhaps you could post the Actual Exception that you're getting, and indicate which line in your posted code it occurs at. Commented May 23, 2012 at 17:10
  • here is the error... SEVERE: null java.io.FileNotFoundException: asd (The system cannot find the file specified) at java.io.FileInputStream.open(Native Method) at java.io.FileInputStream.<init>(FileInputStream.java:106) at java.io.FileInputStream.<init>(FileInputStream.java:66) at java.io.FileReader.<init>(FileReader.java:41) at RSA.<init>(RSA.java:45) at TWO.main(TWO.java:14) Commented May 23, 2012 at 17:20
  • @Neil Coffey~ thanks for the help. i still don't get the right answer.. i need to know what is the function of saveToFile(c://public.key). what is the value of c://public.key? Commented May 23, 2012 at 20:54

1 Answer 1

3

The problem is that you're taking an input string from the user, but then your code is treating this as though it was a filename by constructing a FileReader with that string.

Instead of all that nonsense with the FileReader and BufferedReader, is there any reason why you don't just use string.getBytes()?

You also seem to be making life awfully complicated for yourself: you're taking a string, converting into a byte array, then converting that into a string again (with hex representation), then converting that into a byte array again. That's an awful lot of messing about when you could really just take the byte representation of the original string (as given to you by getBytes()) and pass that directly to the RSA encryption.

Sign up to request clarification or add additional context in comments.

1 Comment

I already done the reading value part. Now the real problem is appear. The part of coding InputStream in =RSA.class.getResourceAsStream(keyFileName); System.out.println("Hello2"); ObjectInputStream oin = new ObjectInputStream(new BufferedInputStream(in)); System.out.println("Hello3"); Hello 3 cannot be print. Have can I solve the problem? Thank U.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.