2016-04-25 61 views
1

我已經有過使用...我有完成計劃的問題,使其輸出正確的RC4加密塊幾個Python腳本來看看......RC4加密

計劃目前詢問一個「密鑰」和「明文」(用密鑰加密的文本)。 並輸出編碼的字符串......我想。所以如果我輸入單詞「純文本」來加密我得到以下。不過,我認爲這是不完整的......

[187, 243, 22, 232, 217, 64, 175, 10, 211] 

我希望有我的加密輸出十六進制

BB F3 16 E8 D9 40 AF 0A D3 

我的計劃是目前不完整的,而只是想在某個方向如何

  1. 玩完加密部分,因此它輸出爲十六進制(我想我已經轉換成字節爲十六進制?)

編輯:以上已被Ebrahim解決。只需要解密幫助

  1. 我迷失在從何處開始解密......我希望能夠獲得一個輸入,它將採用一個密鑰和一個密文無論是在十六進制;並將密文解密爲明文。

我理解加密過程中的邏輯,但即使它非常相似,我仍然無法抓住解密過程。


# Global variables 
state = [None] * 256 
p = q = None 

def setKey(key): 
    ##RC4 Key Scheduling Algorithm 
    global p, q, state 
    state = [n for n in range(256)] 
    p = q = j = 0 
    for i in range(256): 
     if len(key) > 0: 
      j = (j + state[i] + key[i % len(key)]) % 256 
     else: 
     j = (j + state[i]) % 256 
    state[i], state[j] = state[j], state[i] 

def byteGenerator(): 
    ##RC4 Pseudo-Random Generation Algorithm 
    global p, q, state 
    p = (p + 1) % 256 
    q = (q + state[p]) % 256 
    state[p], state[q] = state[q], state[p] 
    return state[(state[p] + state[q]) % 256] 

def encrypt(key,inputString): 
    ##Encrypt input string returning a byte list 
    setKey(string_to_list(key)) 
    return [ord(p)^byteGenerator() for p in inputString] 

def decrypt(inputByteList): 
    ##Decrypt input byte list returning a string 
    return "".join([chr(c^byteGenerator()) for c in inputByteList]) 



def intToList(inputNumber): 
    ##Convert a number into a byte list 
    inputString = "{:02x}".format(inputNumber) 
    return [int(inputString[i:i + 2], 16) for i in range(0, len(inputString), 2)] 

def string_to_list(inputString): 
    ##Convert a string into a byte list 
    return [ord(c) for c in inputString] 




loop = 1 
while loop == 1: #simple loop to always bring the user back to the menu 

    print("RC4 Encryptor/Decryptor") 
    print 
    print("Please choose an option from the below menu") 
    print 
    print("1) Encrypt") 
    print("2) Decrypt") 
    print 

    choice = input("Choose your option: ") 
    choice = int(choice) 

    if choice == 1: 
     key = raw_input("Enter Key: ") 
     inputstring = raw_input("enter plaintext: ") 
     encrypt(key, inputstring) 


    elif choice == 2: 
     key = raw_input("Enter Key: ") 
     ciphertext = raw_input("enter plaintext: ") 
     print decrypt(intToList(ciphertext)) 

    elif choice == 3: 
    #returns the user to the previous menu by ending the loop and clearing the screen. 
     loop = 0 

    else: 
     print ("please enter a valid option") #if any NUMBER other than 1, 2 or 3 is entered. 
+0

_however我認爲這是不完整的..._:你爲什麼這麼認爲? – EbraHim

+0

@EbraHim我試圖讓我的加密文本「明文」輸出在十六進制而不是一個字節列表。抱歉應該更好地措辭。 – LewisFletch

+0

@EbraHim你能幫助解答我的問題的一部分嗎? – LewisFletch

回答

1

要將小數輸出轉換爲十六進制輸出:

>>> arr = [187, 243, 22, 232, 217, 64, 175, 10, 211] 
>>> ' '.join('%02x'%i for i in arr) 
'bb f3 16 e8 d9 40 af 0a d3' 
>>> 
+0

好的,真棒。非常感謝。我怎麼去解密相同的十六進制字符串?用純文本輸出它?使用我的代碼 – LewisFletch