Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

python - 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=input("Enter file name:")
fr=open(filename)
keep_going=0
data = fr.readline()
fw=open('encrypted_file.txt', 'w')
for x in range(len(data)):
    fw.write(data[x])       
fw.close()
fr.close()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...