Advertisement
Guest User

RC4

a guest
Feb 11th, 2020
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. # Global variables
  2. state = [None] * 256
  3. p = q = None
  4.  
  5. def setKey(key):
  6. ##RC4 Key Scheduling Algorithm
  7. global p, q, state
  8. state = [n for n in range(256)]
  9. p = q = j = 0
  10. for i in range(256):
  11. if len(key) > 0:
  12. j = (j + state[i] + key[i % len(key)]) % 256
  13. else:
  14. j = (j + state[i]) % 256
  15. state[i], state[j] = state[j], state[i]
  16.  
  17. def byteGenerator():
  18. ##RC4 Pseudo-Random Generation Algorithm
  19. global p, q, state
  20. p = (p + 1) % 256
  21. q = (q + state[p]) % 256
  22. state[p], state[q] = state[q], state[p]
  23. return state[(state[p] + state[q]) % 256]
  24.  
  25. def encrypt(key,inputString):
  26. ##Encrypt input string returning a byte list
  27. setKey(string_to_list(key))
  28. return [ord(p) ^ byteGenerator() for p in inputString]
  29.  
  30. def decrypt(inputByteList):
  31. ##Decrypt input byte list returning a string
  32. return "".join([chr(c ^ byteGenerator()) for c in inputByteList])
  33.  
  34.  
  35.  
  36. def intToList(inputNumber):
  37. ##Convert a number into a byte list
  38. inputString = "{:02x}".format(inputNumber)
  39. return [(inputString[i:i + 2], 16) for i in range(0, len(inputString), 2)]
  40.  
  41. def string_to_list(inputString):
  42. ##Convert a string into a byte list
  43. return [ord(c) for c in inputString]
  44.  
  45.  
  46. loop = 1
  47. while loop == 1: #simple loop to always bring the user back to the menu
  48.  
  49. print("RC4 Encryptor/Decryptor")
  50. print
  51. print("Please choose an option from the below menu")
  52. print
  53. print("1) Encrypt")
  54. print("2) Decrypt")
  55. print
  56.  
  57. choice = input("Choose your option: ")
  58. choice = int(choice)
  59.  
  60. if choice == 1:
  61. key = input("Enter Key: ")
  62. inputstring = input("enter plaintext: ")
  63. print(encrypt(key, inputstring))
  64.  
  65.  
  66. elif choice == 2:
  67. key = input("Enter Key: ")
  68. ciphertext = input("enter plaintext: ")
  69. print(decrypt(intToList(ciphertext)))
  70.  
  71. elif choice == 3:
  72. #returns the user to the previous menu by ending the loop and clearing the screen.
  73. loop = 0
  74.  
  75. else:
  76. print ("please enter a valid option") #if any NUMBER other than 1, 2 or 3 is entered.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement