Skip to content Skip to sidebar Skip to footer

How To 'encrypt' A File

Just trimmed this down big time I have an overall assignment that must read a file, encrypt it and then write the encrypted data to a new file. what i've tried is this: filename=in

Solution 1:

If your goal is just to exchange the letters in a string with others that you specify, then the solution is the following:

decrypted = 'abcdefghijklmnopqrstuvwxyz'#normal alphabet
encrypted = 'MNBVCXZLKJHGFDSAPOIUYTREWQ'#your "crypted" alphabet#Encription
text = 'cryptme'#the string to be crypted
encrypted_text = ''for letter in text:
    encrypted_text += encrypted[decrypted.find(letter)]
print encrypted_text
#will print BOWAUFC#Decription
text = encrypted_text #"BOWAUFC" in this example
decrypted_text = ''for letter in text:
    decrypted_text += decrypted[encrypted.find(letter)]
print decrypted_text
#will print cryptme

Note that your "crypted alphabet" do not convert any white space or any symbols but the lowercase letters, if you have other symbols in your text you have to include them as well.

However, this is not the proper way to encrypt anything! As suggested by others already, look up for a proper encryption algorithm.

Solution 2:

I would suggest you look into Simple Crypt, this all depends on the level of security you want.

If I understand your question enough, Simple Crypt should do the job that you need.

https://pypi.python.org/pypi/simple-crypt

Solution 3:

Here's a very simple implementation of the Vigenère Cipher I made:

from string import ascii_uppercase as alphabet

val = {}
for x in xrange(len(alphabet)):
    val[alphabet[x]] = x
    val[x] = alphabet[x]

encrypt = lambda a, b: ''.join(val[(val[a[i]]+val[b[i%len(b)]])%26] for i in xrange(len(a)))
decrypt = lambda a, b: ''.join(val[(val[a[i]]-val[b[i%len(b)]])%26] for i in xrange(len(a)))

Where a is the message and b is the key (I know it's written a bit tersely, but it was for a code golf competition). There are plenty of ciphers out there; you don't have to use this one, and probably shouldn't. It is just meant to get you thinking about possible ways to go about doing this. A very simple cipher that I think is good for your purposes is the Caesar Cipher.

One other thing that I'd like to point out is that your code doesn't look to modular -- one of your teacher's requirements -- right now. I'd recommend breaking it down to a function to open a file, a function to perform the actual **cryption, and a "main" function to take the user's input and call the other functions.

Best of luck to you!

Post a Comment for "How To 'encrypt' A File"