2015-02-18 396 views
1

所以我是一個Python n00b,我試圖破解這個腳本來創建一個終點加密工具。基本上,腳本使用raw_input並使用16位數字符串使用AES對其進行編碼。爲了解密該消息,您需要手動粘貼已編碼的文本,然後粘貼密鑰。有沒有辦法從文件中拉出文本,然後將編碼文本輸出到不同的文件?如何從一個txt文件導入raw_input /將raw_input寫入一個txt文件

這裏是我迄今:

from Crypto.Cipher import AES 
import string 
import base64 
import time 
#import modules 
PADDING = '{' 
BLOCK_SIZE = 32 
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING 
#prepare crypto method 
EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s))) 
DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING) 
#set encryption/decryption variables 
loop=5 
while loop==5: 
    #set up loop, so the program can be rerun again if desired without restarting 
    option=raw_input("Would You Like to Encrypt Or Decrypt Text?\nEncrypt: a\nDecrypt: b\n") 
    if option=='a': 
     letter=3 
     while letter==3: 
      secret = raw_input("Please Enter An Encryption Key {must be 16 characters long}: ") 
      countTotal= (len(secret)) 
      if countTotal==16: 
       cipher = AES.new(secret) 
       letter=0 
      else: 
       print "Please Ensure The Key You Entered Is 16 Characters In Length\n" 
       letter=3 
       #this checks the encryption key to ensure it matches the correct length 
     # encode a string 
     data=raw_input("Please Enter Text You'd Like Encrypted: ") 
     encoded = EncodeAES(cipher, data) 
     print 'Encrypted string:', encoded 
     options=raw_input("Would You Like To Encrypt/Decrypt Again? Y/N\n") 
     if options=='y': 
      loop=5 
     if options=='n': 
      loop=0 

    if option=='b': 

     encoded=raw_input("Please Enter The Encoded String:\n") 
     letter=3 
     while letter==3: 
      secret=raw_input("Please Enter The Decryption Key:\n") 
      countTotal= (len(secret)) 
      #this checks the encryption key to ensure it matches the correct length 
      if countTotal==16: 
       cipher = AES.new(secret) 
       letter=0 
       decoded = DecodeAES(cipher, encoded) 
       print 'Decrypted string:', decoded 
       options=raw_input("Would You Like To Encrypt/Decrypt Again? Y/N\n") 
       if options=='y': 
        loop=5 
       if options=='n': 
        loop=0 
      else: 
       print "Please Ensure The Key You Entered Is 16 Characters In Length\n" 
       letter=3 

if loop==0: 
    print "Goodbye!!" 
    time.sleep(2) 
    exit 
    #exits the program if desired by user 

回答

2

你可以打開一個特定的文件,打開( 'filename.extension', 'R/W/...')。然後,您可以通過read(),readline()或readlines()來瀏覽文件的內容。要寫入文件,只需打開一個文件是這樣的:

f = open('filename.txt', 'w')  #make new file (open for write) 
f.write('This is a test\n')  #write to that file 

更多信息閱讀和寫作看到:https://docs.python.org/2/tutorial/inputoutput.html

+0

謝謝你的鏈接!很有幫助。它完全按照我的需要分解它。我會給你一個upvote,但我不能直到我的代表達到15! – greenMamBa 2015-02-18 00:51:37

+0

@Jonathan沒問題,很高興我能幫上忙 – rodalfus 2015-02-18 01:03:33