14 Replies - 6662 Views - Last Post: 19 October 2013 - 11:06 PM Rate Topic: -----

#1 rd_wingman  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 28
  • Joined: 07-May 08

RSA Encryption and Decryption

Posted 05 March 2012 - 09:28 PM

I am trying to encrypt and decrypt a file using RSA keys. My code creates a blank decrypted file and i cannot figure out why. Everything compiles and runs but the decrypted file is wrong. Can someone please help? I am using Eclipse.


import java.io.*;
import java.math.BigInteger;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import javax.crypto.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class RSA {
	public static void main(String[] args){
//	Create an instance of KeyPairGenerator suitable for generating RSA keys;
//	Initialize the generator, telling it the bit length of the modulus that we require (see below);
//	Call genKeyPair(), which eventually returns a KeyPair object;
//	Call getPublic() and getPrivate() on the latter to pull out the public and private keys.
		System.out.println("start rsa");
try{
	
		generateKeys();
		rsaEncrypt("test.txt","encrypted.txt");
		rsaDecrypt("encrypted.txt", "decrypted.txt");
	}
catch(Exception e){}
	}
	
	public static void generateKeys() throws NoSuchAlgorithmException, InvalidKeySpecException, IOException{
		KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
		kpg.initialize(2048);
		KeyPair kp = kpg.genKeyPair();
		PublicKey publicKey = kp.getPublic();
		PrivateKey privateKey = kp.getPrivate();
		
		System.out.println("keys created");
		
		KeyFactory fact = KeyFactory.getInstance("RSA");
		RSAPublicKeySpec pub = fact.getKeySpec(publicKey,RSAPublicKeySpec.class);
		RSAPrivateKeySpec priv = fact.getKeySpec(privateKey,RSAPrivateKeySpec.class);

		saveToFile("public.key", pub.getModulus(),pub.getPublicExponent());
		saveToFile("private.key", priv.getModulus(),priv.getPrivateExponent());
		
		System.out.println("keys saved");
	}
	
	// Save the encryption keys to a file
	public static void saveToFile(String fileName, BigInteger mod, BigInteger exp) throws IOException {
		ObjectOutputStream fileOut = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(fileName)));
		  try {
			 fileOut.writeObject(mod);
			 fileOut.writeObject(exp);
		  } 
		  catch (Exception e) {
			  throw new IOException("Unexpected error");
		  } 
		  finally {
			 fileOut.close();
		  }
	}
	
	// Return the saved key
	static PublicKey readKeyFromFile(String keyFileName) throws IOException { 
		InputStream in = new FileInputStream(keyFileName);
		ObjectInputStream oin = new ObjectInputStream(new BufferedInputStream(in));
		  try {
		    BigInteger m = (BigInteger) oin.readObject();
		    BigInteger e = (BigInteger) oin.readObject();
		    RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);
		    KeyFactory fact = KeyFactory.getInstance("RSA");
		    PublicKey pubKey = fact.generatePublic(keySpec);
		    return pubKey;
		  } 
		  catch (Exception e) {
		    throw new RuntimeException("Spurious serialisation error", e);
		  } 
		  finally {
		    oin.close();
		  }
	}
	
	// Use this PublicKey object to initialize a Cipher and encrypt some data	
	public static void rsaEncrypt(String file_loc, String file_des) throws Exception {
		byte[] data = new byte[32];
		int i;
		
		System.out.println("start encyption");
		
		PublicKey pubKey = readKeyFromFile("public.key");
		Cipher cipher = Cipher.getInstance("RSA");
		cipher.init(Cipher.ENCRYPT_MODE, pubKey);
		
		FileInputStream fileIn = new FileInputStream(file_loc);
		FileOutputStream fileOut = new FileOutputStream(file_des);
		CipherOutputStream cipherOut = new CipherOutputStream(fileOut, cipher);
		 
		// Read in the data from the file and encrypt it
		while ((i = fileIn.read(data)) != -1) {
			cipherOut.write(data, 0, i);
		 }
		
		// Close the encrypted file
		cipherOut.close();
		
		System.out.println("encrypted file created");
	}
	
	// Use this PublicKey object to initialize a Cipher and decrypt some data	
	public static void rsaDecrypt(String file_loc, String file_des) throws Exception {
		byte[] data = new byte[32];
		int i;
		
		System.out.println("start decyption");
		
		PublicKey priKey = readKeyFromFile("private.key");
		Cipher cipher = Cipher.getInstance("RSA");
		cipher.init(Cipher.DECRYPT_MODE, priKey);
		
		FileInputStream fileIn = new FileInputStream(file_loc);
		CipherInputStream cipherIn = new CipherInputStream(fileIn, cipher);
		FileOutputStream fileOut = new FileOutputStream(file_des);
		
		// Write data to new file
		while ((i = cipherIn.read(data)) != -1) {
			fileOut.write(data, 0, i);
		 }
		
		// Close the file
		cipherIn.close();
		fileOut.close();		

		System.out.println("decrypted file created");	
	
	}
}



Is This A Good Question/Topic? 0
  • +

Replies To: RSA Encryption and Decryption

#2 blackcompe  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1155
  • View blog
  • Posts: 2,536
  • Joined: 05-May 05

Re: RSA Encryption and Decryption

Posted 05 March 2012 - 09:57 PM

// Read in the data from the file and encrypt it
        while ((i = fileIn.read(data)) != -1) {
            cipherOut.write(data, 0, i);
        }

        // Close the encrypted file
        cipherOut.close();



In your rsaEncrypt I put the following and nothing prints, so the cipher stream isn't reading data.

// Write data to new file
        while ((i = cipherIn.read(data)) != -1) {
            System.out.println("i = "+i);
            fileOut.write(data, 0, i);
        }


This post has been edited by blackcompe: 05 March 2012 - 10:06 PM

Was This Post Helpful? 0
  • +
  • -

#3 blackcompe  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1155
  • View blog
  • Posts: 2,536
  • Joined: 05-May 05

Re: RSA Encryption and Decryption

Posted 05 March 2012 - 10:10 PM

I want to say the problem is because your trying to use a PublicKey as a private key. In rsaDecrypt you have:

PublicKey priKey = readKeyFromFile("private.key");


And in readFromFile your return a public key when you should be returning a Key.

Try something like this in readFromFile

try {
    BigInteger m = (BigInteger) oin.readObject();
    BigInteger e = (BigInteger) oin.readObject();
    KeyFactory fact = KeyFactory.getInstance("RSA");
    if (keyFileName.startsWith("public")) 
        return fact.generatePublic(new RSAPublicKeySpec(m, e));
    else
        return fact.generatePrivate(new RSAPrivateKeySpec(m, e));
}


This post has been edited by blackcompe: 05 March 2012 - 10:15 PM

Was This Post Helpful? 0
  • +
  • -

#4 rd_wingman  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 28
  • Joined: 07-May 08

Re: RSA Encryption and Decryption

Posted 05 March 2012 - 10:17 PM

I changed it and still nothing
Was This Post Helpful? 0
  • +
  • -

#5 blackcompe  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1155
  • View blog
  • Posts: 2,536
  • Joined: 05-May 05

Re: RSA Encryption and Decryption

Posted 05 March 2012 - 10:18 PM

Did you try my latest updated code? I just changed it, not even a minute ago.

This post has been edited by blackcompe: 05 March 2012 - 10:19 PM

Was This Post Helpful? 0
  • +
  • -

#6 rd_wingman  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 28
  • Joined: 07-May 08

Re: RSA Encryption and Decryption

Posted 05 March 2012 - 10:20 PM

I changed it and still nothing
Was This Post Helpful? 0
  • +
  • -

#7 blackcompe  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1155
  • View blog
  • Posts: 2,536
  • Joined: 05-May 05

Re: RSA Encryption and Decryption

Posted 05 March 2012 - 10:20 PM

Run this:

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigInteger;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.KeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;

class Test {

    public static void main(String[] args) throws Exception {
        generateKeys();
        rsaEncrypt("test.txt", "encrypted.txt");
        rsaDecrypt("encrypted.txt", "decrypted.txt");
    }

    public static void generateKeys() throws Exception {
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        kpg.initialize(2048);
        KeyPair kp = kpg.genKeyPair();
        PublicKey publicKey = kp.getPublic();
        PrivateKey privateKey = kp.getPrivate();

        System.out.println("keys created");

        KeyFactory fact = KeyFactory.getInstance("RSA");
        RSAPublicKeySpec pub = fact.getKeySpec(publicKey,
                RSAPublicKeySpec.class);
        RSAPrivateKeySpec priv = fact.getKeySpec(privateKey,
                RSAPrivateKeySpec.class);

        saveToFile("public.key", pub.getModulus(), pub.getPublicExponent());
        saveToFile("private.key", priv.getModulus(), priv.getPrivateExponent());

        System.out.println("keys saved");
    }

    public static void saveToFile(String fileName, BigInteger mod,
            BigInteger exp) throws IOException {
        ObjectOutputStream fileOut = new ObjectOutputStream(
                new BufferedOutputStream(new FileOutputStream(fileName)));
        try {
            fileOut.writeObject(mod);
            fileOut.writeObject(exp);
        } catch (Exception e) {
            throw new IOException("Unexpected error");
        } finally {
            fileOut.close();
            System.out.println("Closed writing file.");
        }
    }

    // Return the saved key
    static Key readKeyFromFile(String keyFileName) throws IOException {
        InputStream in = new FileInputStream(keyFileName);
        ObjectInputStream oin = new ObjectInputStream(new BufferedInputStream(
                in));
        try {
            BigInteger m = (BigInteger) oin.readObject();
            BigInteger e = (BigInteger) oin.readObject();
            KeyFactory fact = KeyFactory.getInstance("RSA");
            if (keyFileName.startsWith("public"))
                return fact.generatePublic(new RSAPublicKeySpec(m, e));
            else
                return fact.generatePrivate(new RSAPrivateKeySpec(m, e));
        } catch (Exception e) {
            throw new RuntimeException("Spurious serialisation error", e);
        } finally {
            oin.close();
            System.out.println("Closed reading file.");
        }
    }

    // Use this PublicKey object to initialize a Cipher and encrypt some data
    public static void rsaEncrypt(String file_loc, String file_des)
            throws Exception {
        byte[] data = new byte[32];
        int i;

        System.out.println("start encyption");

        Key pubKey = readKeyFromFile("public.key");
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);

        FileInputStream fileIn = new FileInputStream(file_loc);
        FileOutputStream fileOut = new FileOutputStream(file_des);
        CipherOutputStream cipherOut = new CipherOutputStream(fileOut, cipher);

        // Read in the data from the file and encrypt it
        while ((i = fileIn.read(data)) != -1) {
            cipherOut.write(data, 0, i);
        }

        // Close the encrypted file
        cipherOut.close();
        fileIn.close();

        System.out.println("encrypted file created");
    }

    // Use this PublicKey object to initialize a Cipher and decrypt some data
    public static void rsaDecrypt(String file_loc, String file_des)
            throws Exception {
        byte[] data = new byte[32];
        int i;

        System.out.println("start decyption");

        Key priKey = readKeyFromFile("private.key");
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, priKey);

        FileInputStream fileIn = new FileInputStream(file_loc);
        CipherInputStream cipherIn = new CipherInputStream(fileIn, cipher);
        FileOutputStream fileOut = new FileOutputStream(file_des);

        // Write data to new file
        while ((i = cipherIn.read()) != -1) {
            fileOut.write(i);
        }

        // Close the file
        fileIn.close();
        cipherIn.close();
        fileOut.close();

        System.out.println("decrypted file created");

    }
}



Was This Post Helpful? 0
  • +
  • -

#8 rd_wingman  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 28
  • Joined: 07-May 08

Re: RSA Encryption and Decryption

Posted 05 March 2012 - 10:23 PM

added your code. didn't see it when i replied. thanks
Was This Post Helpful? 0
  • +
  • -

#9 blackcompe  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1155
  • View blog
  • Posts: 2,536
  • Joined: 05-May 05

Re: RSA Encryption and Decryption

Posted 05 March 2012 - 10:24 PM

No problem.
Was This Post Helpful? 0
  • +
  • -

#10 faiz10  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 19-October 13

Re: RSA Encryption and Decryption

Posted 19 October 2013 - 01:02 AM

excuse me sir
how can I get the path of the file created in
code]saveToFile("public.key", pub.getModulus(), pub.getPublicExponent());[/code]
and is it possible to read the content of that file too ?
Was This Post Helpful? 0
  • +
  • -

#11 faiz10  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 19-October 13

Re: RSA Encryption and Decryption

Posted 19 October 2013 - 02:23 AM

Hello sir
I manged to change the path of the encrypted.txt file to check the file after encryption but suprisingly, the file appeard empty and of the size 0byte as there is no cipher text within it >>
can you help clarifying this matter please ?
Was This Post Helpful? 0
  • +
  • -

#12 blackcompe  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1155
  • View blog
  • Posts: 2,536
  • Joined: 05-May 05

Re: RSA Encryption and Decryption

Posted 19 October 2013 - 06:04 AM

Quote

excuse me sir
how can I get the path of the file created in
code]saveToFile("public.key", pub.getModulus(), pub.getPublicExponent());[/code]
and is it possible to read the content of that file too ?


I'm not sure I understand what's being asked. The path of the file where the key resides is "public.key" in the working directory. Can you read the file? Programmatically? Yes, after it's been generated. The key files are serialized objects, so they won't be human readable if you open them in a text editor.

Quote

I manged to change the path of the encrypted.txt file to check the file after encryption but suprisingly, the file appeard empty and of the size 0byte as there is no cipher text within it >>
can you help clarifying this matter please ?


Unless you post the code that causes this behavior, I can't help you.

This post has been edited by blackcompe: 19 October 2013 - 06:05 AM

Was This Post Helpful? 0
  • +
  • -

#13 faiz10  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 19-October 13

Re: RSA Encryption and Decryption

Posted 19 October 2013 - 08:36 PM

this is the latest version of code modified by you to solve the problem of getting an empty encrypted file right ?!
in my case, i run this code but still getting empty encrypted file ...
I assume this code is producing an encryption file but still something missing since i stil get encrypted.txt empty !
btw, is this code limited to certain file extension and certain file size ?



View Postblackcompe, on 05 March 2012 - 10:20 PM, said:

Run this:

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigInteger;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.KeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;

class Test {

    public static void main(String[] args) throws Exception {
        generateKeys();
        rsaEncrypt("test.txt", "encrypted.txt");
        rsaDecrypt("encrypted.txt", "decrypted.txt");
    }

    public static void generateKeys() throws Exception {
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        kpg.initialize(2048);
        KeyPair kp = kpg.genKeyPair();
        PublicKey publicKey = kp.getPublic();
        PrivateKey privateKey = kp.getPrivate();

        System.out.println("keys created");

        KeyFactory fact = KeyFactory.getInstance("RSA");
        RSAPublicKeySpec pub = fact.getKeySpec(publicKey,
                RSAPublicKeySpec.class);
        RSAPrivateKeySpec priv = fact.getKeySpec(privateKey,
                RSAPrivateKeySpec.class);

        saveToFile("public.key", pub.getModulus(), pub.getPublicExponent());
        saveToFile("private.key", priv.getModulus(), priv.getPrivateExponent());

        System.out.println("keys saved");
    }

    public static void saveToFile(String fileName, BigInteger mod,
            BigInteger exp) throws IOException {
        ObjectOutputStream fileOut = new ObjectOutputStream(
                new BufferedOutputStream(new FileOutputStream(fileName)));
        try {
            fileOut.writeObject(mod);
            fileOut.writeObject(exp);
        } catch (Exception e) {
            throw new IOException("Unexpected error");
        } finally {
            fileOut.close();
            System.out.println("Closed writing file.");
        }
    }

    // Return the saved key
    static Key readKeyFromFile(String keyFileName) throws IOException {
        InputStream in = new FileInputStream(keyFileName);
        ObjectInputStream oin = new ObjectInputStream(new BufferedInputStream(
                in));
        try {
            BigInteger m = (BigInteger) oin.readObject();
            BigInteger e = (BigInteger) oin.readObject();
            KeyFactory fact = KeyFactory.getInstance("RSA");
            if (keyFileName.startsWith("public"))
                return fact.generatePublic(new RSAPublicKeySpec(m, e));
            else
                return fact.generatePrivate(new RSAPrivateKeySpec(m, e));
        } catch (Exception e) {
            throw new RuntimeException("Spurious serialisation error", e);
        } finally {
            oin.close();
            System.out.println("Closed reading file.");
        }
    }

    // Use this PublicKey object to initialize a Cipher and encrypt some data
    public static void rsaEncrypt(String file_loc, String file_des)
            throws Exception {
        byte[] data = new byte[32];
        int i;

        System.out.println("start encyption");

        Key pubKey = readKeyFromFile("public.key");
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);

        FileInputStream fileIn = new FileInputStream(file_loc);
        FileOutputStream fileOut = new FileOutputStream(file_des);
        CipherOutputStream cipherOut = new CipherOutputStream(fileOut, cipher);

        // Read in the data from the file and encrypt it
        while ((i = fileIn.read(data)) != -1) {
            cipherOut.write(data, 0, i);
        }

        // Close the encrypted file
        cipherOut.close();
        fileIn.close();

        System.out.println("encrypted file created");
    }

    // Use this PublicKey object to initialize a Cipher and decrypt some data
    public static void rsaDecrypt(String file_loc, String file_des)
            throws Exception {
        byte[] data = new byte[32];
        int i;

        System.out.println("start decyption");

        Key priKey = readKeyFromFile("private.key");
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, priKey);

        FileInputStream fileIn = new FileInputStream(file_loc);
        CipherInputStream cipherIn = new CipherInputStream(fileIn, cipher);
        FileOutputStream fileOut = new FileOutputStream(file_des);

        // Write data to new file
        while ((i = cipherIn.read()) != -1) {
            fileOut.write(i);
        }

        // Close the file
        fileIn.close();
        cipherIn.close();
        fileOut.close();

        System.out.println("decrypted file created");

    }
}



Was This Post Helpful? 0
  • +
  • -

#14 blackcompe  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1155
  • View blog
  • Posts: 2,536
  • Joined: 05-May 05

Re: RSA Encryption and Decryption

Posted 19 October 2013 - 08:58 PM

Quote

this is the latest version of code modified by you to solve the problem of getting an empty encrypted file right ?!


I've confirmed that code still works. You need to create a file in the working directory called test.txt with some text you want to encrypt. Is that why your're having trouble? If so, you should have seen the runtime error stating that 'test.txt' could not be found. I have no clue what you're saying about getting an empty encrypted file.

Compile the code, create test.txt, run the Main class and whallah! The contents of test.txt is encrypted and written to encrypted.txt, and then the contents of encrypted.txt are read, decrypted, and written to decrypted.txt.

This post has been edited by blackcompe: 19 October 2013 - 08:59 PM

Was This Post Helpful? 0
  • +
  • -

#15 faiz10  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 19-October 13

Re: RSA Encryption and Decryption

Posted 19 October 2013 - 11:06 PM

sorry for troubling you sir ..
I figured out why it is giving empty encrypted file ... I made a file with smaller size and it run well, but why it is not giving any exception when the size of the file is large ?!
and what if i wana encrypt large file ?! is there way to do so ?!


View Postblackcompe, on 19 October 2013 - 08:58 PM, said:

Quote

this is the latest version of code modified by you to solve the problem of getting an empty encrypted file right ?!


I've confirmed that code still works. You need to create a file in the working directory called test.txt with some text you want to encrypt. Is that why your're having trouble? If so, you should have seen the runtime error stating that 'test.txt' could not be found. I have no clue what you're saying about getting an empty encrypted file.

Compile the code, create test.txt, run the Main class and whallah! The contents of test.txt is encrypted and written to encrypted.txt, and then the contents of encrypted.txt are read, decrypted, and written to decrypted.txt.

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1