7 Replies - 3439 Views - Last Post: 16 March 2012 - 10:21 AM 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 of .doc files

Posted 15 March 2012 - 01:04 PM

I am trying to encrypt and decrypt .doc files. I will also need to be able to encrypt and decrypt .pdf, .docx, etc. I am currently testing my code with .doc files but it is not working. Data is detected but none is encrypted and decrypted. Here is my code.


//****************RSA Ecryption/Decryption****************
// In order to run the file you must do the following
// 1) Call genertateKeys()
//		This will generate the keys of the desired length
//		defines KEYLENGTH
// 2) To encrypt, you must call rsaEncrypt() and give the 
//		file to be encypted along with a name for the new
//		encypted file
// 3) To decrypt,and give the 
//		file to be dencypted along with a name for the new
//		dencypted file

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){
//	
		System.out.println("start rsa");
try{
	
		generateKeys();
		rsaEncrypt("test.doc","encrypted.doc");
		rsaDecrypt("encrypted.doc", "decrypted.doc");
	}
catch(Exception e){}
	}
	//********************generateKeys*******************
	// This fuction generates the key files for encyption
	// and decryption.
	//	Create an instance of KeyPairGenerator suitable for generating RSA keys;
	//	Initialize the generator, telling it the bit length of the modulus that we require
	//	Call genKeyPair(), which eventually returns a KeyPair object;
	//	Call getPublic() and getPrivate() on the latter to pull out the public and private keys.
	// Input: None
	// Output: None
	//
	public static void generateKeys() throws NoSuchAlgorithmException, InvalidKeySpecException, IOException{
		//  KEYLENGHT is the length of the keys to be generated. There are two normal formats, 1024 or 2048
		//	1024 RSA key length is sufficient for many medium-security purposes such as web site logins
		//	2048 RSA key length is for  high-security applications1 or for data that needs to remain confidential for more than a few years
		// 	Key lenght > 2048 is used keep data confidential for more than the next two decades, RSA recommends a key size larger than 2048 bits
		//	Key length data gathered from http://www.javamex.com/tutorials/cryptography/rsa_key_length.shtml
	
		int KEYLENTGH = 2048;
		
		KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
		kpg.initialize(KEYLENTGH);
		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");
	}
	
//********************saveToFile*******************
// This fuction is used to save the keys to a file
// Input: File name to be saved, modulus and esponent
//		  for encypting keys
// Output: Key files
//
	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();
		  }
	}
	
//********************readKeyFromFile*******************
// This fuction returns the key files
// Input: File name to be read
// Output: The desired key file
//
	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();
		  }
	}
	
//********************rsaEncrypt***********************
// This fuction encypyts the file using the public key
// Input:  File to be encrypted and name of encrypted
//		   file
// Output: An encrypted file
//	
	public static void rsaEncrypt(String file_loc, String file_des) throws Exception {
		byte[] data = new byte[52428800];	// 50 Megebytes
		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) {
			System.out.println(" i:"+ i);
			cipherOut.write(data, 0, i);
		 }
		
		// Close the encrypted file
		cipherOut.close();
		
		System.out.println("encrypted file created");
	}
//********************rsaEncrypt***********************
// This fuction decypyts the file using the pivate key
// Input:  File to be decypyts and name of decrypted
//		   file
// Output: An decrypted file
//
	public static void rsaDecrypt(String file_loc, String file_des) throws Exception {
		byte[] data = new byte[52428800];	// 50 Megebytes
		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(data)) != -1) {
			System.out.println(" i:"+ i);
			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 of .doc files

#2 g00se  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 2110
  • View blog
  • Posts: 8,777
  • Joined: 20-September 08

Re: RSA Encryption and Decryption of .doc files

Posted 15 March 2012 - 01:17 PM

Works for me
Was This Post Helpful? 0
  • +
  • -

#3 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 of .doc files

Posted 15 March 2012 - 01:59 PM

my new files are being created with zero data
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 of .doc files

Posted 15 March 2012 - 05:16 PM

I need to encrypt and decrypt large files with numerous extensions such as .doc, .pdf, etc. I have created a RSA encryption and decryption program but it is not working for large files. Can someone please suggest a way to go about this. Possibly show some example code to follow. Thank you.
Was This Post Helpful? 0
  • +
  • -

#5 blackcompe  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1009
  • View blog
  • Posts: 2,186
  • Joined: 05-May 05

Re: RSA Encryption and Decryption of .doc files

Posted 15 March 2012 - 06:28 PM

Quote

I need to encrypt and decrypt large files with numerous extensions such as .doc, .pdf, etc. I have created a RSA encryption and decryption program but it is not working for large files.


You were able to get the code working (on small files) from this post? As of now, it doesn't even work for small files. If you did get it working, post it, so I can test it.

This post has been edited by blackcompe: 15 March 2012 - 06:33 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 of .doc files

Posted 15 March 2012 - 07:44 PM

it works for a small txt file. My test.txt contains the following "This is a test. This is only a test." and it correctly encrypts and decrypts it. It fails when I attempt to use a larger it fails. I use the code from that link for my test file. I am not sure if I need to use an ASE encryption/decryption algorithm for the files.

The difference is that I use .txt files and not .doc files.


rsaEncrypt("test.txt","encrypted.txt");
rsaDecrypt("encrypted.txt", "decrypted.txt");



This post has been edited by rd_wingman: 15 March 2012 - 07:48 PM

Was This Post Helpful? 0
  • +
  • -

#7 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 9032
  • View blog
  • Posts: 33,508
  • Joined: 27-December 08

Re: RSA Encryption and Decryption of .doc files

Posted 15 March 2012 - 08:17 PM

Duplicate threads merged. Please avoid duplicate posting.
Was This Post Helpful? 0
  • +
  • -

#8 blackcompe  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1009
  • View blog
  • Posts: 2,186
  • Joined: 05-May 05

Re: RSA Encryption and Decryption of .doc files

Posted 16 March 2012 - 10:21 AM

I'm using the AES code you had for your topic that was closed.

1. You must print your exceptions. You've code that just makes the program exit when an exception occurs and doesn't say anything as to why it exited.

2. If you did print your exceptions you'd know that you're using an illegal key size. The default security provider doesn't support 256-bit keys, use 128-bits, or change to the Bouncy Castle provider.

3. You need to close all your streams. You're closing the cipher output streams but not the file input streams. Even if it's an input stream, where you might not see weird behavior if you don't close it, you still need to close it. Otherwise, you'll eat up resources and possibly cause leaks.

Using a 128-bit key fixes the error, and you can encrypt/decrypt .doc files. I think the reason why encrypting was failing in the code where you used RSA, is because RSA only encrypts one block, whereas AES encrypts them all. The cipher stream wasn't processing all the input, and therefore nothing was written to the file.

I found this discussion quite useful. Choosing AES to encrypt your data and RSA to encrypt the key is the a common security practice (at least for network traffic).
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1