Results 1 to 7 of 7
  1. #1
    JoaoPe is offline Member
    Join Date
    Jan 2008
    Location
    Portugal
    Posts
    1
    Rep Power
    0

    Default 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:

    Java 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

  2. #2
    tim's Avatar
    tim
    tim is offline Senior Member
    Join Date
    Dec 2007
    Posts
    435
    Rep Power
    7

    Default 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? :D

    Java Code:
    /*
     * Main.java
     *
     * Created on January 15, 2008, 9:35 AM
     */
    
    package stringbits;
    
    import java.io.*;
    import java.util.*;
    
    /**
     *
     * @author tim
     */
    public class Main {
        [COLOR="DarkRed"]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;
        }[/COLOR]
        [COLOR="DarkGreen"]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;
        }[/COLOR]
        [COLOR="Navy"]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();
        }[/COLOR]
        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!
    Last edited by tim; 01-15-2008 at 10:20 AM.
    Eyes dwelling into the past are blind to what lies in the future. Step carefully.

  3. #3
    Nicholas Jordan's Avatar
    Nicholas Jordan is offline Senior Member
    Join Date
    Jun 2008
    Location
    Southwest
    Posts
    1,018
    Rep Power
    8

    Exclamation 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:
    Java 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.
    Introduction to Programming Using Java.
    Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor

  4. #4
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,390
    Rep Power
    25

    Default

    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.

    Java 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());
        }
    }

  5. #5
    fishtoprecords's Avatar
    fishtoprecords is offline Senior Member
    Join Date
    Jun 2008
    Posts
    571
    Rep Power
    7

    Default

    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

  6. #6
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,390
    Rep Power
    25

    Default

    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.

  7. #7
    Nicholas Jordan's Avatar
    Nicholas Jordan is offline Senior Member
    Join Date
    Jun 2008
    Location
    Southwest
    Posts
    1,018
    Rep Power
    8

    Post 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:
    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.
    Introduction to Programming Using Java.
    Cybercartography: A new theoretical construct proposed by D.R. Fraser Taylor

Similar Threads

  1. how to write onto a file
    By mirage_87 in forum New To Java
    Replies: 6
    Last Post: 09-08-2009, 03:54 PM
  2. How to read a text file from a Java Archive File
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 02-08-2008, 09:13 AM
  3. File Write Error
    By vikain in forum Advanced Java
    Replies: 5
    Last Post: 01-02-2008, 04:38 AM
  4. Replies: 0
    Last Post: 11-14-2007, 06:04 PM
  5. Write unicode into file
    By vata2999 in forum New To Java
    Replies: 1
    Last Post: 08-08-2007, 03:04 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •