RC4 Encryption in Python -
i've had through several python scripts using rc4 block cipher... i'm having issues completing program outputs properly...
program asks "key" , "plaintext" (text encrypt key). , outputs encoded string... think. if enter word "plaintext" encrypt following. think incomplete...
[187, 243, 22, 232, 217, 64, 175, 10, 211]
i want have encrypted output in hex
bb f3 16 e8 d9 40 af 0a d3
my program incomplete @ moment, direction on how to
- finish off encryption part outputs hexadecimal (i think have convert bytes hex?)
edit: above has been resolved ebrahim. need decryption
- i'm lost on begin decryption... want able have input take key , ciphertext both in hexadecimal; , decrypt ciphertext plaintext.
i understand logic in encryption process, i'm having trouble grasping decryption process though quite similar.
# global variables state = [none] * 256 p = q = none def setkey(key): ##rc4 key scheduling algorithm global p, q, state state = [n n in range(256)] p = q = j = 0 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 byte list setkey(string_to_list(key)) return [ord(p) ^ bytegenerator() p in inputstring] def decrypt(inputbytelist): ##decrypt input byte list returning string return "".join([chr(c ^ bytegenerator()) c in inputbytelist]) def inttolist(inputnumber): ##convert number byte list inputstring = "{:02x}".format(inputnumber) return [int(inputstring[i:i + 2], 16) in range(0, len(inputstring), 2)] def string_to_list(inputstring): ##convert string byte list return [ord(c) c in inputstring] loop = 1 while loop == 1: #simple loop bring user menu print("rc4 encryptor/decryptor") print print("please choose option below menu") print print("1) encrypt") print("2) decrypt") print choice = input("choose 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 user previous menu ending loop , clearing screen. loop = 0 else: print ("please enter valid option") #if number other 1, 2 or 3 entered.
to convert decimal output hex output:
>>> arr = [187, 243, 22, 232, 217, 64, 175, 10, 211] >>> ' '.join('%02x'%i in arr) 'bb f3 16 e8 d9 40 af 0a d3' >>>
Comments
Post a Comment