1 Replies - 8476 Views - Last Post: 16 March 2012 - 05:58 AM Rate Topic: -----

#1 rd_wingman   User is offline

  • New D.I.C Head

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

Encryption/Decryption using AES and RSA

Posted 16 March 2012 - 12:40 AM

I am trying to encrypt and decrypt files. I need this work with multiple files extension and sizes. In my code, I generate an AES key to encrypt and decrypt the files. That AES key is encrypted and decrypted using RSA. My code generates all the keys and saves them but terminates when I try to perform the encryption and decryption of the test.txt file. In order for it to work properly you must save the ads key before encryption and read the key before decryption. That is done inside the functions. As soon as I try to read in the keys in gets terminated. I do not understand why.

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.io.OutputStream;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
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.PrivateKey;
import java.security.PublicKey;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class EncryptDecrypt {
	// Initate Globals
	public static final int AES_KEY_SIZE = 256;
	public static final int RSA_KEY_SIZE = 2048;
	static Cipher rsaCipher;
	static Cipher aesCipher;
	static byte[] aesKey;
	static SecretKeySpec aeskeySpec;
	public static void main(String[] args){
			System.out.println("start ecryption and decryption");
			aesDecrypt("encrypted.txt", "decrypted.txt");
	catch(Exception e){}
	public static void cipherInit() throws NoSuchAlgorithmException, NoSuchPaddingException{

		// Initate the AES cipher
	    aesCipher = Cipher.getInstance("AES");
	    // Initiate the RSA Cipher
		rsaCipher = Cipher.getInstance("RSA");
	public static void generateKeys() throws IOException, GeneralSecurityException{
		// Generates and saves RSA keys
		KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
		KeyPair kp = kpg.genKeyPair();
		PublicKey publicKey = kp.getPublic();
		PrivateKey privateKey = kp.getPrivate();
		System.out.println("rsa keys created");
		KeyFactory fact = KeyFactory.getInstance("RSA");
		RSAPublicKeySpec pub = fact.getKeySpec(publicKey,RSAPublicKeySpec.class);
		RSAPrivateKeySpec priv = fact.getKeySpec(privateKey,RSAPrivateKeySpec.class);

		saveRsaKeys("public.key", pub.getModulus(),pub.getPublicExponent());
		saveRsaKeys("private.key", priv.getModulus(),priv.getPrivateExponent());
		System.out.println("rsa keys saved");
	    // Generate AES Keys
		KeyGenerator kgen = KeyGenerator.getInstance("AES");
	    SecretKey key = kgen.generateKey();
	    aesKey = key.getEncoded();
	    aeskeySpec = new SecretKeySpec(aesKey, "AES");
	    System.out.println("aes keys created");	

// 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 saveRsaKeys(String fileName, BigInteger mod, BigInteger exp) throws IOException {
			ObjectOutputStream fileOut = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(fileName)));
			  try {
			  catch (Exception e) {
				  throw new IOException("Unexpected error");
			  finally {
// This fuction returns the key files
// Input: File name to be read
// Output: The desired key file
		static Key readRsaKey(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));
					return fact.generatePrivate(new RSAPrivateKeySpec(m, e));
				catch (Exception e) {
				   throw new RuntimeException("Spurious serialisation error", e);
			  finally {
	public static void saveAesKey(String file_name) throws IOException, GeneralSecurityException {
		// Load the RSA public key to encrypt the AES key
		Key pubKey = readRsaKey("public.key");
		rsaCipher = Cipher.getInstance("RSA");
		rsaCipher.init(Cipher.ENCRYPT_MODE, pubKey);
		CipherOutputStream cipherOut = new CipherOutputStream(new FileOutputStream(file_name), rsaCipher);
		// Save the key
		// Close the encrypted file
		System.out.println("aes keys saved");


	static Key readAesKey(String keyFileName) throws IOException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException { 
		// Load the private key to decrypt the AES key
		Key priKey = readRsaKey("private.key");
		rsaCipher = Cipher.getInstance("RSA");
		rsaCipher.init(Cipher.DECRYPT_MODE, priKey);
		// read AES key
		aesKey = new byte[AES_KEY_SIZE/8];
		CipherInputStream input = new CipherInputStream(new FileInputStream(keyFileName), rsaCipher);
		aeskeySpec = new SecretKeySpec(aesKey, "AES");
		System.out.println("aes keys loaded");
		return aeskeySpec;

	public static void aesEncrypt(String file_loc, String file_des) throws IOException, GeneralSecurityException {
		aesCipher.init(Cipher.ENCRYPT_MODE, aeskeySpec);
		FileInputStream input = new FileInputStream(file_loc);
		CipherOutputStream output = new CipherOutputStream(new FileOutputStream(file_des), aesCipher);
		// Create the encypted file
		streamCopy(input, output);
		// close the file
		System.out.println("files encrypted");
	public static void aesDecrypt(String file_loc, String file_des) throws IOException, GeneralSecurityException {
		System.out.println("aes keys read");
		aesCipher.init(Cipher.DECRYPT_MODE, aeskeySpec);
		CipherInputStream input = new CipherInputStream(new FileInputStream(file_loc), aesCipher);
		FileOutputStream output = new FileOutputStream(file_des);
		// Create the decrypted file
		streamCopy(input, output);
		// Close the files
		System.out.println("files decrypted");
	private static void streamCopy(InputStream input, OutputStream output) throws IOException {
		int i;
		byte[] data = new byte[1024];
		while((i=input.read(data))!=-1) {
			output.write(data, 0, i);

Is This A Good Question/Topic? 0
  • +

Replies To: Encryption/Decryption using AES and RSA

#2 macosxnerd101   User is online

  • Games, Graphs, and Auctions
  • member icon

Reputation: 12403
  • View blog
  • Posts: 45,544
  • Joined: 27-December 08

Re: Encryption/Decryption using AES and RSA

Posted 16 March 2012 - 05:58 AM

This is your fourth time opening a thread on the same topic. Please avoid duplicate posting.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1