Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...