0

Any suggestions / code examples for Encryption/Decryption of files(any file format) in java.
command line args -

Edited by happygeek: re-closed thread

5
Contributors
7
Replies
20
Views
7 Years
Discussion Span
Last Post by peter_budo
1

Any suggestions / code examples for Encryption/Decryption of files(any file format) in java.
command line args - <inputfilename> <outputfilename>

Show us what you have tried first please.

Votes + Comments
Well said
0
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;

import javax.crypto.Cipher;

public class encNew {

protected static final String ALGORITHM = "RSA";
static PrivateKey privKey;
static PublicKey pubKey;



/* public static KeyPair generateKey() throws NoSuchAlgorithmException
{
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
keyGen.initialize(1024);
KeyPair key = keyGen.generateKeyPair();
return key;
}*/

public static void encryptFile(String srcFileName, String destFileName, PublicKey key) throws Exception
{
	encryptDecryptFile(srcFileName,destFileName, key, Cipher.ENCRYPT_MODE);
}

/**
* Decrypt file using 1024 RSA encryption
*
* @param srcFileName Source file name
* @param destFileName Destination file name
* @param key The key. For encryption this is the Private Key and for decryption this is the public key
* @param cipherMode Cipher Mode
* @throws Exception
*/
public static void decryptFile(String srcFileName, String destFileName, PrivateKey key) throws Exception
{
	encryptDecryptFile(srcFileName,destFileName, key, Cipher.DECRYPT_MODE);
}

/**
* Encrypt and Decrypt files using 1024 RSA encryption
*
* @param srcFileName Source file name
* @param destFileName Destination file name
* @param key The key. For encryption this is the Private Key and for decryption this is the public key
* @param cipherMode Cipher Mode
* @throws Exception
*/
public static void encryptDecryptFile(String srcFileName, String destFileName, Key key, int cipherMode) throws Exception
{
	OutputStream outputWriter = null;
	InputStream inputReader = null;
	System.out.println("srcFileName ----- "+srcFileName);
	System.out.println("destFileName ----- "+destFileName);
	try
	{
		Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
		String textLine = null;
		
		byte[] buf = cipherMode == Cipher.ENCRYPT_MODE? new byte[100] : new byte[128];
		int bufl;
		// init the Cipher object for Encryption...
		cipher.init(cipherMode, key);
		
		// start FileIO
		outputWriter = new FileOutputStream(destFileName);
		inputReader = new FileInputStream(srcFileName);
		while ( (bufl = inputReader.read(buf)) != -1)
		{
			System.out.println("hi sale");
			byte[] encText = null;
			if (cipherMode == Cipher.ENCRYPT_MODE)
				encText = encrypt(copyBytes(buf,bufl),(PublicKey)key);
			else
				encText = decrypt(copyBytes(buf,bufl),(PrivateKey)key);
			System.out.println("encText ----------- "+encText);
			outputWriter.write(encText);
		}
		outputWriter.flush();
	}
	catch (Exception e)
	{
		throw e;
	}
	finally
	{
		try
		{
			if (outputWriter != null)
				outputWriter.close();
			if (inputReader != null)
				inputReader.close();
		}
		catch (Exception e)
		{} 
	}
}

public static byte[] copyBytes(byte[] arr, int length)
{
	byte[] newArr = null;
	if (arr.length == length)
		newArr = arr;
	else
	{
		newArr = new byte[length];
		for (int i = 0; i < length; i++)
		{
			newArr[i] = (byte) arr[i];
		}
	}
	System.out.println("newArr -- "+new String(newArr));
	return newArr;
}

public static byte[] encrypt(byte[] text, PublicKey key) throws Exception
{
	byte[] cipherText = null;
	try
	{
		// get an RSA cipher object and print the provider
		Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
		
		// encrypt the plaintext using the public key
		cipher.init(Cipher.ENCRYPT_MODE, key );
		cipherText = cipher.doFinal(text);
	}
	catch (Exception e)
	{
		throw e;
	}
	return cipherText;
}


public static byte[] decrypt(byte[] text, PrivateKey key) throws Exception
{
	byte[] dectyptedText = null;
	try
	{
		// decrypt the text using the private key
		Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
		cipher.init(Cipher.DECRYPT_MODE, key);
		try {
			dectyptedText = cipher.doFinal(text);
		} catch (Exception e) {
			System.out.println("Exception ======== "+e);
			e.printStackTrace();
		}
		
		System.out.println("dectyptedText ----------- "+dectyptedText);
	}
	catch (Exception e)
	{
		throw e;
	}
	return dectyptedText;
}

public static void main(String args[]) throws NoSuchProviderException{
	String srcFileName = "blob";
	String destFileName = "Transcriptview";

	try {
	KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
	SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
	keyGen.initialize(1024, random);
	//keyGen.initialize(1024);
	KeyPair key = keyGen.generateKeyPair();
	privKey = key.getPrivate(); 
	pubKey = key.getPublic();
	} 
	catch (NoSuchAlgorithmException nsae){}

	try{
		System.out.println("in try block of main");
	decryptFile(srcFileName,destFileName,privKey);
	}catch (Exception e){

	}
	} 
}

Encryption is working fine..
Decryption not working...code shown above is for decryption.
Error encountered :
javax.crypto.BadPaddingException: Data must start with zero
at sun.security.rsa.RSAPadding.unpadV15(Unknown Source)
at sun.security.rsa.RSAPadding.unpad(Unknown Source)
at com.sun.crypto.provider.RSACipher.a(DashoA13*..)
at com.sun.crypto.provider.RSACipher.engineDoFinal(DashoA13*..)
at javax.crypto.Cipher.doFinal(DashoA13*..)
at encNew.decrypt(encNew.java:156)
at encNew.encryptDecryptFile(encNew.java:86)
at encNew.decryptFile(encNew.java:48)
at encNew.main(encNew.java:188)

Edited by Ashwin1985: n/a

0

I think the exception is caused because for each execution of the program a new private key is generated which is than used for decryption.
Since decryption requires the private key it must be the same that was generated when encryption process

Try this. Save the private key that was generated when encrypting in a file and use that while decrypting

Save the private key after encryption as,

encryptFile(srcFileName,destFileName,pubKey);
//Save the private key of the keypair used when encrypting the file
byte[] key = privKey.getEncoded();
FileOutputStream keyfos = new FileOutputStream("privkey");
keyfos.write(key);
keyfos.close();

Now use this saved private key while decrypting

FileInputStream keyfis = new FileInputStream("privkey");
byte[] encKey = new byte[keyfis.available()];
keyfis.read(encKey);
keyfis.close();

PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(encKey);

KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
PrivateKey privKeyNew = keyFactory.generatePrivate(privKeySpec);
		
decryptFile(srcFileName,destFileName,privKeyNew);
0

I think the exception is caused because for each execution of the program a new private key is generated which is than used for decryption.
Since decryption requires the private key it must be the same that was generated when encryption process

Try this. Save the private key that was generated when encrypting in a file and use that while decrypting

Save the private key after encryption as,

encryptFile(srcFileName,destFileName,pubKey);
//Save the private key of the keypair used when encrypting the file
byte[] key = privKey.getEncoded();
FileOutputStream keyfos = new FileOutputStream("privkey");
keyfos.write(key);
keyfos.close();

Now use this saved private key while decrypting

FileInputStream keyfis = new FileInputStream("privkey");
byte[] encKey = new byte[keyfis.available()];
keyfis.read(encKey);
keyfis.close();

PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(encKey);

KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
PrivateKey privKeyNew = keyFactory.generatePrivate(privKeySpec);
		
decryptFile(srcFileName,destFileName,privKeyNew);

hey parry.. thanks for the suggestion...it worked..
But it requires a new file for the private key to be created for every encryption cycle run. Only this key can be used to decrypt the encrypted file.
Can i make it asynchronous? (independent of private key file ?? )

Or is there any other Encryption Algorithm implementation which i can use to serve this purpose?

0

You can generate the public and private key once and store them in file with something like this,

import java.io.FileOutputStream;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyFactory;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
 
import javax.crypto.Cipher;
 
public class encNewKeygen {
 
protected static final String ALGORITHM = "RSA";
static PrivateKey privKey;
static PublicKey pubKey;
 
 
 
public static void main(String args[]) throws NoSuchProviderException{
	 
	try {
	KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
	SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
	keyGen.initialize(1024, random);	
	KeyPair key = keyGen.generateKeyPair();
	privKey = key.getPrivate(); 	
	pubKey = key.getPublic();
	} 
	catch (NoSuchAlgorithmException nsae){}
 
	try{
		//Save the public and private key of the keypair used when encrpting the file
		byte[] key = pubKey.getEncoded();
        FileOutputStream keyfos = new FileOutputStream("pubkey");
        keyfos.write(key);
        keyfos.close();

		key = privKey.getEncoded();
        keyfos = new FileOutputStream("privkey");
        keyfos.write(key);
        keyfos.close();
		
	}catch (Exception e){
		e.printStackTrace();
	}
	} 
}

Then each time you want to encypt or decrypt the files, instead of generating keys in the main method, read the keys stored in the file and proceed. You can read the keys as,

.......

//Read the public and private keys
		KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);

		FileInputStream keyfis = new FileInputStream("pubkey");
		byte[] encKey = new byte[keyfis.available()];
		keyfis.read(encKey);
		keyfis.close();

		X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(encKey);
		pubKey = keyFactory.generatePublic(pubKeySpec);

		keyfis = new FileInputStream("privkey");
		encKey = new byte[keyfis.available()];
		keyfis.read(encKey);
		keyfis.close();

		PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(encKey);	
		privKey = keyFactory.generatePrivate(privKeySpec);


.......

If public key encryption is not required, you can go for encryption with DES and will require only one keyfile

Also there is a nice library called JASYPT
http://www.jasypt.org/
See if it solves your requirement

-2

please give me java code for encrypting a text file and to decrypt it, the codes for both is needed separately...... if anybody knows please help me out....

Votes + Comments
thread hijacker, zombie master, homework kiddo. One downvote doesn't begin to punish the naughtiness
Hijacking someone else post with your question because you lazy, bad!
1

please give me java code for encrypting a text file and to decrypt it, the codes for both is needed separately...... if anybody knows please help me out....

If you still want an answer then create new thread as this one is closed.

PS: Read the rules before you post again.