472,778 Members | 2,519 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,778 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

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;
catch ( Exception ex )
System.out.println( "done" );

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

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

//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
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;
fileInputStream = new FileInputStream( encryptedFile );
decryptedFileOutputStream = new FileOutputStream(
fileToDecrypt );

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

//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 )
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;
fileInputStream = new FileInputStream( originalFile );
encryptedFileOutputStream = new FileOutputStream(
fileToEncrypt );

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

//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 )
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 8175

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

Similar topics

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...
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...
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...
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...
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...
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: ...
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...
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...
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...
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 2 August 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
by: erikbower65 | last post by:
Using CodiumAI's pr-agent is simple and powerful. Follow these steps: 1. Install CodiumAI CLI: Ensure Node.js is installed, then run 'npm install -g codiumai' in the terminal. 2. Connect to...
by: linyimin | last post by:
Spring Startup Analyzer generates an interactive Spring application startup report that lets you understand what contributes to the application startup time and helps to optimize it. Support for...
by: DJRhino1175 | last post by:
When I run this code I get an error, its Run-time error# 424 Object required...This is my first attempt at doing something like this. I test the entire code and it worked until I added this - If...
by: Rina0 | last post by:
I am looking for a Python code to find the longest common subsequence of two strings. I found this blog post that describes the length of longest common subsequence problem and provides a solution in...
by: DJRhino | last post by:
Private Sub CboDrawingID_BeforeUpdate(Cancel As Integer) If = 310029923 Or 310030138 Or 310030152 Or 310030346 Or 310030348 Or _ 310030356 Or 310030359 Or 310030362 Or...
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
by: Mushico | last post by:
How to calculate date of retirement from date of birth
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...

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.