d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Need Python Help Please > Bit Level File Manipulation
Add Reply New Topic New Poll
Member
Posts: 3,373
Joined: Dec 2 2006
Gold: 0.56
Apr 10 2013 11:07am
For a final program project for one of my classes I'm working on making a cryptography program. I've already made a very basic shift cipher program that reads from a text file and saved the encrypted version.

However, I would like to go deeper and actual make a somewhat useful cryptography program. I'm not concerned about the algorithms at this point, I only need to know how to take a file in Python, read each individual bit or perhaps groups of bits, and edit them.

Right now, I have this. I'm using BitString module to read the files hex/bits and I can save the file as well. However, where my problem comes in is actually editing the hex/bit values and saving the file after that. Tkinter is used to prompt the user to select a file. I am working in Python 2.7.

Code
#Encryption and decryption program

import tkFileDialog
from Tkinter import Tk
from bitstring import Bits, BitStream


Tk().withdraw() #closes root window when file dialog appears
file = tkFileDialog.askopenfilename() #prompts users to chose a file

num = file.count("/") #counts backslash to find ending slice

encrypted = "encrypted_" + str(file.split("/")[num]) #removes dir, adds encrypted to file name

data = Bits(filename = str(file))
infile = open(file, "rb")
outfile = open(encrypted, "wb")#opens file
print infile.read()


for nibble in data.cut(8): #cuts the stream up into single byte chunks


   nibble.tobytes
   
 
   print nibble

   outfile.write(nibble.bytes)



infile.close()
outfile.close()


If anyone is familiar with BitString and can tell me how to do it with that module that'd be awesome. If there is a way to do it in Python without that module or with another module I would be more they grateful for any help.

If you need anymore information or clarification don't be afraid to ask.

This post was edited by KratosGOW on Apr 10 2013 11:08am
Member
Posts: 3,373
Joined: Dec 2 2006
Gold: 0.56
Apr 10 2013 01:22pm
Well. I seem to have figured out that problem. However, now I have another one.

Code
key = [int(i) for i in str(key)]


This provides me with single digit entries in a list. However, I want to have each entry to be two digits. How would I go about making that happen?

Key is a 10 digit int.

This post was edited by KratosGOW on Apr 10 2013 01:23pm
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll