473,415 Members | 1,547 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,415 software developers and data experts.

Problem Decrypting Binary File

I'm writing a small app to help me learn more about cryptography. All
it does is encrypt all of the files in directory A, and put the
encrypted versions of the files in directory B. It then decrypts the
files in directory B, and puts them in directory C. I'm getting some
exceptions when I try to decrypt a binary file though. Here's the
code:

//////////////////////////////////////////////////////////////////////
public class FileEncrypter
{
String PATH = "";

String JAR_FILE_NAME = "img.jar";

final String ENCRYPTED_FILES_DIRECTORY_NAME = "encrypted_files";
final String DECRYPTED_FILES_DIRECTORY_NAME = "decrypted_files";

SecretKeySpec specKey = null;
Cipher cipher = null;

// byte[] encryptedBytes;

public FileEncrypter( String path )
{
this.PATH = path;
try
{
init();
encryptFiles();
}
catch ( Exception ex )
{
ex.printStackTrace();
}
System.out.println( "done" );
}

private void init() throws NoSuchPaddingException,
NoSuchAlgorithmException, FileNotFoundException
{
//make directory for the encrypted files
File encryptedDirectory = new File( PATH + File.separator +
ENCRYPTED_FILES_DIRECTORY_NAME );
encryptedDirectory.mkdir();

//make directory for the decrypted files
File decryptedDirectory = new File( PATH + File.separator +
DECRYPTED_FILES_DIRECTORY_NAME );
decryptedDirectory.mkdir();

//initialize encryption objects
cipher = Cipher.getInstance( "Blowfish" );
KeyGenerator kgen = KeyGenerator.getInstance( "Blowfish" );
SecretKey secretKey = kgen.generateKey();
byte[] bytes = secretKey.getEncoded();

System.out.println("Key is: [" + new
sun.misc.BASE64Encoder().encode(bytes) + "]");

specKey = new SecretKeySpec( bytes, "Blowfish" );
}

private void encryptFiles()
{
//create an array of all the files in the file directory
File imgDir = new File( PATH );
String[] files = imgDir.list();

File originalFile = null;
File encryptedFile = null;
File decryptedFile = null;

//loop thru the array of file names
for ( int i = 0; i < files.length; i++ )
{
//create a file object from the current file name in the
array
originalFile = new File( PATH + File.separator + files[ i ]
);
//ignore directories
if ( !originalFile.isDirectory() )
{
//create an empty copy of the file and put it in the
encrypted files directory
encryptedFile = new File( originalFile.getParent() +
File.separator + ENCRYPTED_FILES_DIRECTORY_NAME, "encrypted_" + files[
i ] );
//create an empty copy of the file and put it in the
decrypted files directory
decryptedFile = new File( originalFile.getParent() +
File.separator + DECRYPTED_FILES_DIRECTORY_NAME, files[ i ] );

//encrypt the file
encryptFile( originalFile, encryptedFile );
//decrypt the file
decryptFile( encryptedFile, decryptedFile );
}
}
}

private void decryptFile(File encryptedFile, File fileToDecrypt )
{
FileOutputStream decryptedFileOutputStream = null;
FileInputStream fileInputStream = null;
try
{
fileInputStream = new FileInputStream( encryptedFile );
decryptedFileOutputStream = new FileOutputStream(
fileToDecrypt );

//set cipher to decrypt
cipher.init( Cipher.DECRYPT_MODE, specKey );
int fileByteSize = fileInputStream.available();//research
FileInputStream.available

//read in the encrypted bytes into a byte array
byte[] encryptedBytes = new byte[fileByteSize];
fileInputStream.read( encryptedBytes );

//decrypt the encrypted file bytes
//this line throws these
exceptions:javax.crypto.BadPaddingException: Given final block not
properly padded;
//javax.crypto.IllegalBlockSizeException: Input length (with
padding) not multiple of 8 bytes
byte[] decryptedBytes = cipher.doFinal( encryptedBytes );

//write the encrypted bytes into the file
decryptedFileOutputStream.write( decryptedBytes, 0,
fileByteSize );
}
catch ( Exception ex )
{
ex.printStackTrace();
}
finally
{
if( fileInputStream != null ) try{ fileInputStream.close(); }
catch( IOException ignore ){}
if( decryptedFileOutputStream != null ) try{
decryptedFileOutputStream.close(); } catch( IOException ignore ){}
}
}

private void encryptFile(File originalFile, File fileToEncrypt )
{
FileOutputStream encryptedFileOutputStream = null;
FileInputStream fileInputStream = null;
try
{
fileInputStream = new FileInputStream( originalFile );
encryptedFileOutputStream = new FileOutputStream(
fileToEncrypt );

//set cipher to encrypt
cipher.init( Cipher.ENCRYPT_MODE, specKey );
int fileByteSize = fileInputStream.available();//research
FileInputStream.available

//read in the original bytes into a byte array
byte[] originalBytes = new byte[fileByteSize];
fileInputStream.read( originalBytes );

//encrypt the original file bytes
byte[] encryptedBytes = cipher.doFinal( originalBytes );

//write the encrypted bytes into the file
encryptedFileOutputStream.write( encryptedBytes, 0,
fileByteSize );
}
catch ( Exception e )
{
e.printStackTrace();
}
finally
{
if ( fileInputStream != null ) try{ fileInputStream.close();
}catch( IOException ioe ){}
if ( encryptedFileOutputStream != null ) try{
encryptedFileOutputStream.close(); }catch( IOException ioe ){}
}
}
public static void main( String args[] )
{
String PATH = "C:" + File.separator + "java" + File.separator +
"projects" + File.separator + "Encryption" + File.separator + "img";
new FileEncrypter( PATH );
}
}
////////////////////////////////////////////////////////////////////////////

I think this has something to do with ASCII characters that are
created when the original binary is encrypted maybe? Thanks in advance
for any help. Chris
Jul 17 '05 #1
0 8216

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: | last post by:
I am rewriting a C++ application in C#. This file has a combination of Text and Binary data. I used CFile before to read the text. If I hit a certain string that denotes the following data is...
10
by: Alessandro Bottoni | last post by:
I know you will shake you head sadly but... I really have to perform such a suicidal task (even if for a short time and just for internal use). I have to send by email (over the open internet) a...
3
by: JW | last post by:
I can encrypt the contents of a memory stream with no problems, however when decrypting( I'm using the same key an IV ) I get an exception stating bad data. I'm at a lost. I'm actually creating...
11
by: Abhishek | last post by:
I have a problem transfering files using sockets from pocket pc(.net compact c#) to desktop(not using .net just mfc and sockets 2 API). The socket communication is not a issue and I am able to...
3
by: John R. Delaney | last post by:
I am running in debugging mode after a clean C++ compilation under .NET 2003. In a BIG loop (controlled many levels up in the call stack), I open a file with fopen using the "a" option. Then I write...
3
by: dfa_geko | last post by:
Hi All, I had a question about encrypting and decrypting XML files using asymmetric keys. I copied some sample code from MSDN, here are the samples: ...
5
by: Harb247 | last post by:
Hi Guys, First Post. Need some help decrypting a String / DB The company i manage recently had an argument with their lead programmer for their data base. However he has decided to have nothing...
0
by: Independent | last post by:
Python programmers may find the application to decoding an encrypted map image format known as Memory Map to produce a standard PNG image file interesting. Someone obviously very well versed in...
5
by: Neil Crighton | last post by:
I'm using the zipfile library to read a zip file in Windows, and it seems to be adding too many newlines to extracted files. I've found that for extracted text-encoded files, removing all instances...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.