IcyFlame
IcyFlame

Reputation: 5199

encryption and writing to file

So heres the deal.

I have some data. It is so arranged that each line consists of one record. And each record consists of 4 items:

  1. username
  2. account name
  3. password
  4. remarks

These records are separated by :

So a sample record would look like:

un0:ac0:password0:linkedtoemail1

Now, when the application is closed, I encrypt all the data using ARC4 and then write it to a file. And delete the plaintext file.

filin = open('file','r')
separator = '\n'
filout = open('temp','w')

for i in filin:

    b = ARC4.new('0123456789123456').encrypt(i)

    filout.write(b + separator)

While writing I add a \n between two records. But when decrypting it again, I use : for i in filin where filin is the filestream object. Now when some text gets encrypted then a \n character is a part of the enrypted string. So when I decrypt I get results that I don't want.

Please tell me if there is a better way to do this. What separator should I use between two records after I have encrypted the records? And how should I detect this separator when I am decrypting the data? Kindly post the code for whatever solution you are suggesting.

I am using Python 2.7 on a Linux Mint machine.

Upvotes: 0

Views: 1506

Answers (3)

Elazar
Elazar

Reputation: 21585

You should encrypt the record seperator too, into a binary file.

There should not be any seperator in the raw encrypted file, even if you could have escaped them (which you can't do easily)

Assuming data will fit easily in memory, it might be something like that:

with open('file') as filin:
    data = filin.read()

from Crypto.Cipher import ARC4 # a better cipher may fit here too
with open('temp','wb') as filout:
    b = ARC4.new('0123456789123456').encrypt(data)
    filout.write(b)

I am not a security expert, so I don't know how safe it is. I believe it is safer than what you tried in your question, anyway.

with open('temp','rb') as filin:
    data = ARC4.new('0123456789123456').decrypt(filin.read())

Upvotes: 1

Gung Foo
Gung Foo

Reputation: 13558

My 2 cents are to put your userdata into a dictionary and encode it using json, which you then encrypt.

It will save you the "looking for a terminator" hassle and the json encoding function will take care of any neccessary escaping also.

Upvotes: 1

Noctua
Noctua

Reputation: 5208

You could first write the length of the next encrypted record.

filin = open('file','r')
separator = '\n'
filout = open('temp','w')

for i in filin:

    b = ARC4.new('0123456789123456').encrypt(i)

    filout.write(b.len() + separator)
    filout.write(b)

Then on reading, first read the number, then read as many characters as the number indicates.

Upvotes: -1

Related Questions