1 Replies - 488 Views - Last Post: 15 March 2012 - 01:09 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 of .doc files

Posted 15 March 2012 - 01:08 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 modi123_1  Icon User is online

  • Suitor #2
  • member icon



Reputation: 8937
  • View blog
  • Posts: 33,473
  • Joined: 12-June 08

Re: RSA Encryption and Decryption of .doc files

Posted 15 March 2012 - 01:09 PM

Let's not create duplicate threads.. thanks!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1