Java Forums

Main Menu
Home
Today's Posts
FAQ
Search
Contact Us

Java Network
Java Tips
Java Tips Blog

Sponsored Links





Welcome to the Java Forums.

You are currently viewing our boards as a guest which gives you limited access to view most discussions and access our other features. By joining our free community, you will:

  • have access to post topics
  • communicate privately with other members (PM)
  • not see advertisements between posts
  • have the possibility to earn one of our surprises if you are an active member
  • access many other special features that will be introduced later.

Registration is fast, simple and absolutely free so please, join our community today!

If you have any problems with the registration process or your account login, please contact us.

Reply
 
LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 01-15-2008, 01:38 AM
Member
 
Join Date: Jan 2008
Location: Portugal
Posts: 1
JoaoPe is on a distinguished road
DES algorithm (Read and Write bytes to file)
Hello everyone,

I'm trying to implement a DES (Data Encryption Standard) algorithm to encrypt and decrypt files. It's all implemented regarding encoding and decoding.

DES algorithm reads 64 bits from file each time and encode them (the process is repeat till the end of file) to the new encrypted file. The decoding process is the opposite but that doesn't matter for this problem.

My problem is the algorithm is all implemented treating bits (0's and 1's) as strings (it's easier I guess). I want to known how can I read, inside a loop, 8bytes (64bits) from file each time and convert them to a string of bits. At the end I want to convert that 64 bits string back to bytes to be able to write them to the encrypted file.

-----

Example code:

Code:
while (!EOF) { String my64bits = read64BitsFromFile(file.bin); encodeBitsString(my64Bits); // This is already done writeBitsStringToFile(my64Bits); }
-----

So anyone can give me an hint on how to read bytes to string (only 0's and 1's) and write them back as bytes? And do it till the EOF?

Thanks in advanced! Cheers
Bookmark Post in Technorati
Reply With Quote
Sponsored Links
  #2 (permalink)  
Old 01-15-2008, 11:16 AM
tim's Avatar
tim tim is offline
Senior Member
 
Join Date: Dec 2007
Location: South Africa
Posts: 334
tim is on a distinguished road
Try this
Hello JoaoPe

Try the code below. The methods can be used to read and write a file by using binary strings as you wanted. I just want to know: What do you intend to do with the bits that remain after you read x * 64 bits? What if the file is 72 bits or 9 bytes in size?

Code:
/* * Main.java * * Created on January 15, 2008, 9:35 AM */ package stringbits; import java.io.*; import java.util.*; /** * * @author tim */ public class Main { public static byte byteFromBitString(String bitString) throws Exception{ if (bitString.length() > 8) throw new Exception("Cannot create a byte from mare than 8 bits."); byte result = 0; int power = 0; for (int i = bitString.length() - 1; i >= 0; i--){ String bitChar = bitString.substring(i, i + 1); int bitValue = Integer.parseInt(bitChar); if ((bitValue != 0) && (bitValue != 1)) throw new Exception("bitString contains invalid chacters."); byte add = (byte)(bitValue * (int)(Math.pow(2d, (double)power))); result += add; power++; } return result; } public static String[] readBinaryStrings(File file, int bytes) throws Throwable{ boolean EOF = false; Vector<String> list = new Vector<String>(); FileInputStream input = new FileInputStream(file); BufferedInputStream buffer = new BufferedInputStream(input); String current = ""; do{ int next = buffer.read(); if (next != -1){ String add = Integer.toBinaryString(next); String before = ""; for (int i = 0; i < 8 - add.length(); i++){ before += "0"; } add = before + add; current += add; if (current.length() >= bytes * 8){ list.add(new String(current)); current = ""; } } else { if (current.equals("") == false) list.add(new String(current)); EOF = true; } } while (!EOF); buffer.close(); String[] result = new String[list.size()]; for (int i = 0; i < list.size(); i++){ result[i] = list.get(i); } return result; } public static void writeBinaryStrings(File file, String[] bitStrings) throws Throwable{ FileOutputStream output = new FileOutputStream(file); BufferedOutputStream buffer = new BufferedOutputStream(output); for (String string : bitStrings){ int bytes = string.length() / 8; for (int i = 0; i < bytes; i++){ int previousIndex = i * 8; int nextIndex = previousIndex + 8; String next = string.substring(previousIndex, nextIndex); buffer.write(byteFromBitString(next)); } } buffer.close(); } public static void main(String[] args) { try{ String[] bit64Strings = readBinaryStrings(new File("data.txt"), 8); for (String string : bit64Strings){ System.out.println(string); } writeBinaryStrings(new File("test.txt"), bit64Strings); } catch (Throwable e) { showError(e); } } public static void showError(Throwable e){ System.out.println("Problem: " + e.getMessage()); } }
Oh, and welcome to the forum!
__________________
If your ship has not come in yet then build a lighthouse.

Last edited by tim : 01-15-2008 at 11:20 AM.
Bookmark Post in Technorati
Reply With Quote
  #3 (permalink)  
Old 07-28-2008, 06:21 PM
Nicholas Jordan's Avatar
Senior Member
 
Join Date: Jun 2008
Location: Southwest
Posts: 581
Nicholas Jordan is on a distinguished road
Key issue here.
Quote:
Originally Posted by tim View Post
Hello JoaoPe

Try the code below. The methods can be used to read and write a file by using binary strings as you wanted. I just want to know: What do you intend to do with the bits that remain after you read x * 64 bits? What if the file is 72 bits or 9 bytes in size?
Tim, when you get him figured out:
http://java.sun.com/j2se/1.5.0/docs/...tml]DESKeySpec, the key length is not integral on powers of 2 ... poster calls getEncoded() or something on the key spec, doing that from raw key

( which is one of the names of one of the method calls somewhere in there )

does not seem to be implemented in a manner that expedites efficient design.

Method call for above cited class is:
Code:
byte[] getKey()
but there are a few intervening semicolons in a decent use of the class.

Original Poster, do not ever-ever try to generate your own keys. That is never-never land.

Use java dot security dot KeyGenerator, you will probably need Tim's assistance on actually using the byte array it generates.
__________________
Please provide your feedback on our
To view links or images in signatures your post count must be 10 or greater. You currently have 0 posts.
.
Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor
Bookmark Post in Technorati
Reply With Quote
  #4 (permalink)  
Old 07-28-2008, 10:34 PM
Norm's Avatar
Senior Member
 
Join Date: Jun 2008
Location: SW MO, USA
Posts: 1,616
Norm is on a distinguished road
I reworked tim's code to use some of the built in methods. Probably not as efficient but is some shorter. Also for testing I prefer to have all the data in the program vs external files, so I used ByteArrays in place of files.

Code:
/* * Main.java * * Created on January 15, 2008, 9:35 AM * Modified July 28, 2008 by Norm */ package stringbits; import java.io.*; import java.util.*; /** * * @author tim */ public class Main { //-------------------------------------------------------------------------------- public static String[] readBinaryStrings(InputStream is, int size) throws Throwable{ boolean EOF = false; Vector<String> list = new Vector<String>(); // Save chunks of size bytes String current = ""; do{ int next = is.read(); if (next != -1){ // test EOF String add = "00000000"+Integer.toBinaryString(next); add = add.substring(add.length()-8); // get rightmost 8 chars current += add; if (current.length() >= size * 8){ list.add(new String(current)); current = ""; } } else { if (!current.equals("")) list.add(new String(current)); // add partial string EOF = true; } } while (!EOF); is.close(); // Convert the Vector to an String array return list.toArray(new String[list.size()]); // return result; } //---------------------------------------------------------------------------------- // Convert array of String representation of binary to a single String public static void writeBinaryStrings(OutputStream os, String[] bitStrings) throws Throwable{ final int ChunkSize = 8; for (String string : bitStrings){ int nbrChunks = string.length() / ChunkSize; // Get chars in 8 char chunks for (int i = 0; i < nbrChunks; i++){ int startIndex = i * ChunkSize; int endIndex = startIndex + ChunkSize; String next = string.substring(startIndex, endIndex); // next 8 bytes os.write(Byte.parseByte(next, 2)); // to a byte } // end for(i) }// end for(string) os.close(); } //----------------------------------------------------------------------------------- // Testing code here public static void main(String[] args) { // Define some test data byte[] byteData = new byte[] {0x35, 0x73, (byte)0x9A}; //0011 0101 0111 0011 1001 1010 String inputData = "This is a string that should be long enough to show that the code works"; byteData = inputData.getBytes(); ByteArrayInputStream bais = new ByteArrayInputStream(byteData); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try{ String[] bit64Strings = readBinaryStrings(bais, 8); for (String string : bit64Strings){ System.out.println(string); // show results } // Now convert back writeBinaryStrings(baos, bit64Strings); System.out.println(baos); // should be same as original // Test it equal System.out.println("output " + (baos.toString().equals(inputData) ? "matches" : "does NOT match" ) + " input"); } catch (Throwable e) { showError(e); } } public static void showError(Throwable e){ System.out.println("Problem: " + e.getMessage()); } }
Bookmark Post in Technorati
Reply With Quote
  #5 (permalink)  
Old 07-29-2008, 12:25 AM
fishtoprecords's Avatar
Senior Member
 
Join Date: Jun 2008
Posts: 359
fishtoprecords is on a distinguished road
Quote:
Originally Posted by JoaoPe View Post
DES algorithm reads 64 bits from file each time and encode them (the process is repeat till the end of file) to the new encrypted file. The decoding process is the opposite but that doesn't matter for this problem.

My problem is the algorithm is all implemented treating bits (0's and 1's) as strings
Norm's code should help you a lot. Its not clear to me how you are storing the keys or cleartext, or how you are are reading them.

In general, with crypto code, you need to think of the data as eight bit octets, not strings, not bits. Octets are unsigned, and Java doesn't have an 'unsigned byte' data type, but you can usually get it working being careful about signs and not doing addition on bytes
Bookmark Post in Technorati
Reply With Quote
  #6 (permalink)  
Old 07-29-2008, 02:25 AM
Norm's Avatar
Senior Member
 
Join Date: Jun 2008
Location: SW MO, USA
Posts: 1,616
Norm is on a distinguished road
Quote:
algorithm is all implemented treating bits (0's and 1's) as strings
I have a hard time understanding how that works. As a programmer, It seems like a very hard way to do it. Perhaps the OP has misunderstood how the algorithm works.
Bookmark Post in Technorati
Reply With Quote
  #7 (permalink)  
Old 07-29-2008, 04:46 PM
Nicholas Jordan's Avatar
Senior Member
 
Join Date: Jun 2008
Location: Southwest
Posts: 581
Nicholas Jordan is on a distinguished road
DES is not 64 bit keylength
Quote:
Originally Posted by Norm View Post
I have a hard time understanding how that works. As a programmer, It seems like a very hard way to do it. Perhaps the OP has misunderstood how the algorithm works.
Yes, what OP should do is take a hash of the string and store that:
Quote:
My problem is the algorithm is all implemented treating bits (0's and 1's) as strings (it's easier I guess). I want to known how can I read, inside a loop, 8bytes (64bits) from file each time and convert them to a string of bits. At the end I want to convert that 64 bits string back to bytes to be able to write them to the encrypted file.
I tried that a few days ago, got null pointer. I went back and used KeyGenerator in java.security specifiying the keysize given in the DES documentaton in Java. I do not have the cryptographic skills to test whether I was doing data protection but the null pointer went away.

Hint to original poster: Study you decsion 8bytes (64bits) in the available documentation for DES. While you are at it, consider using a hash of the String as the stored information.
__________________
Please provide your feedback on our
To view links or images in signatures your post count must be 10 or greater. You currently have 0 posts.
.
Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor
Bookmark Post in Technorati
Reply With Quote
Sponsored Links
Reply


Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
how to write onto a file mirage_87 New To Java 3 09-18-2008 09:30 AM
How to read a text file from a Java Archive File Java Tip Java Tips 0 02-08-2008 10:13 AM
File Write Error vikain Advanced Java 5 01-02-2008 05:38 AM
.jnlp cant read & write on browser despite signed .jar bongia New To Java 0 11-14-2007 07:04 PM
Write unicode into file vata2999 New To Java 1 08-08-2007 04:04 PM


All times are GMT +3. The time now is 02:36 AM.


VBulletin, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Content Relevant URLs by vBSEO ©2007, Crawlability, Inc.
Copyright ©2006 - 2007, www.java-forums.org