RC4 Python implementation

I'm cooking 2021-11-25 09:45:59
rc4 rc python implementation

RC4 The algorithm is a stream cipher ( Byte oriented operations ), Key length is variable ( Generate the key stream according to the plaintext length )
RC4 Encryption process :
1, Initialize the status array S: length 256 byte , Every S[i] by 1 Bytes ,S[i] The value of is 0-255
2, Initialize temporary array T:T The length of is 256 byte , Every T[i] by 1 Bytes ,
First, generate a key array Key, Key The length of is 1~256 byte ( Random ), Every Key[i] by 1 Bytes , And each Key[i] The value of is randomly generated ;
And then the array Key Each of the Key[i] Take turns and loop into the array T, such as Key[]=1,2,3,4,5 , Then put it into the array T:T[] =1,2,3,4,5,1,2,3,4,5…1,2,3,4,5,1,2 Will array T fill , This array T Finished initializing , And random ;
3, Initial permutation array S : After initialization T, And a variable j=0, Scramble the array S, send S It's random :
Through for each S[i], adopt j = (j + S[i] + T[I]) mod 256 , In exchange for S[i] and S[j] Value ;
My understanding of this step : Because the initialized array T It's random , So it will T Element is added to get S[j] And replace S[i] and S[j] , Make the array S Pseudorandom ;
4, Generate key stream KeyStream: First, get the plaintext length , Decide to generate a key stream of the same length as plaintext ,
Through to each S[i],j=0,j=(j+S[i]) mod 256 take S[i] And S[j] substitution , When i>255, go back to S[0], Repeat the replacement operation again :
j,t = 0,0
for i in range(txtlen): // txtlen Is the length of the plaintext , Through the loop , Generate equal length key stream
i = i mod 256 // adopt mod 256 , Ensure that subsequent pairs of arrays S Repetitive operation
j = (j+S[i]) mod 256
tmp = S[i]
S[i] = S[j] // substitution S[i] And S[j]
S[j] = tmp
t = (S[i] + S[j]) mod 256
KeyStream.append(S[t]) //S[t] by A bit in the key stream
My understanding of this step : Suppose a box is called S, There is a row of 256 One says from 0-255 A number ball , And this 256 The ball was disrupted earlier , Now you need to start from S The first one in the box (i), And through the formula j = (j+S[i]) mod 256 What you get is j individual , Write down the number on the ball and pass the formula t = (S[i] + S[j]) mod 256 Get number t, Then you go and find out the second t A little ball , The number on it S[t] Is a bit in the key stream , And you put the first (i) The ball and the second j Exchange a small ball and put it back S box , Then repeat the steps just now to touch the second (i) And the j And so on , Until you repeat this step txtlen Time ; notes : When you touch the first 256 individual ( The last one ), But you haven't finished yet txtlen Time , So the next time you touch the ball is to go back to the first start , This is the corresponding pair array S Repetitive operation ;

Attach reference code , If there is any wrong , I would appreciate your comments. ^-^:

#encoding = utf-8
import random
# Initialization vector S
def init_S():
global S
for i in range(256):
S.append(i)
# Initialization vector T
def init_T():
global Key,T
keylen = random.randint(1,256)
for i in range(keylen):
index = random.randint(0,61) # Get a random temporary key Key
Key.append(WordList[index])
for i in range(256):
tmp = Key[i % keylen] # Initialization vector T
T.append(tmp)
# The initial displacement S[i]
def swap_S():
global S,T
j = 0
for i in range(256):
j = (j+S[i]+ord(T[i])) % 256
tmp = S[i]
S[i] = S[j]
S[j] = tmp
# Key stream generation 
def Get_KeyStream():
global S,text,KeyStream
txtlen = len(text)
j,t = 0,0
for i in range(txtlen):
i = i % 256
j = (j+S[i]) % 256
tmp = S[i]
S[i] = S[j]
S[j] = tmp
t = (S[i] + S[j]) % 256
KeyStream.append(S[t])
# encryption & Decrypt 
def Get_code():
global PlainText,CryptoText,KeyStream,text
for i in range(len(text)):
CryptoText += chr(ord(text[i]) ^ KeyStream[i]) # encryption 
for i in range(len(text)):
PlainText += chr(ord(CryptoText[i]) ^ KeyStream[i]) # Decrypt 
print('''[+]================= Began to encrypt ==================''')
print("[+] Your ciphertext ---------->",CryptoText)
print('''[+]================= Start decrypting ==================''')
print("[+] Your plaintext ---------->",PlainText)
if __name__ == '__main__' :
T,S,Key = [],[],[]
PlainText,CryptoText,KeyStream = '','',[]
WordList = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" # Used to generate temporary keys Key
print(''' ——————— ———————— —————— | —— \ / _____| / | | | |__) | | / / —— | | | __ / | | / |_| | | ^__^ is easy ~, that right ? | | \ \ | |_____ |______| | |__| \__\ \________| |_| ██████╗ ██████╗██╗ ██╗ ███╗ ███╗ ██╗███████╗ ███████╗ █████╗ ███████╗██╗ ██╗ ██╔══██╗██╔════╝██║ ██║ ██╔██╗ ██╔██╗ ██║██╔════╝ ██╔════╝██╔══██╗██╔════╝╚██╗ ██╔╝ ██████╔╝██║ ███████║ ╚═╝╚═╝ ╚═╝╚═╝ ██║███████╗ █████╗ ███████║███████╗ ╚████╔╝ ██╔══██╗██║ ╚════██║ ██║╚════██║ ██╔══╝ ██╔══██║╚════██║ ╚██╔╝ ██║ ██║╚██████╗ ██║ ███████╗ ██║███████║ ███████╗██║ ██║███████║ ██║ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚══════╝ ╚═╝╚══════╝ ╚══════╝╚═╝ ╚═╝╚══════╝ ╚═╝ ''')
text = input("[+]please input you Plaintext here : ")
init_S()
init_T()
swap_S()
Get_KeyStream()
Get_code()

Screenshot of the code running correctly :
 Insert picture description here

版权声明
本文为[I'm cooking]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/11/20211109005248956u.html

  1. Python regular expression select Characters
  2. Object oriented composition of Python
  3. Python Software Development Directory
  4. Python package
  5. Python module
  6. Python is process oriented and functional
  7. Python generator
  8. Python iterator
  9. Python decorator
  10. Python function closure
  11. Python namespace and scope
  12. Python function
  13. Python file processing
  14. Python data type
  15. Process control of Python
  16. Garbage collection mechanism of Python
  17. Python: the field notes of dtype = 'object' can also be arranged in ascending and descending order
  18. . value in pandas_ Usage of counts()
  19. 202111 | some hands-on practice of Python time function
  20. 202111 | in Python, timestamp, time string and real date time are converted to each other
  21. Pandas draws line chart, bar chart and bar chart
  22. Exploration and practice of easy transformation between various data structures in Python
  23. A simple practice of Python list generation
  24. Use Python to guess the number of machines and judge the number of guesses
  25. Question about Python: did you learn Python
  26. 20210928 | Python case: building tax calculation function
  27. Python basic syntax collation
  28. Some small accumulation of writing programs in python (4)
  29. Some small accumulation of writing programs in python (3)
  30. Python leak detection tips (3)
  31. Python leak detection tips (2)
  32. Python leak detection tips (1)
  33. Python foundation and MySQL Foundation
  34. Some small accumulation of writing programs in python (2)
  35. Some small accumulation of writing programs in Python
  36. Python 3.7.3 + cuda9.2 installing Python
  37. Python knowledge used to write programs
  38. Python installation + vscode configuration Python environment
  39. Some small problems during Python installation
  40. Answer and Q & A of Python practice introduction course
  41. Sorting out the learning route for Python beginners
  42. The 6-line Python code uses the pdf2docx module converter object to convert PDF into docx file
  43. Batch compression of picture files using Python
  44. Using Python to write djikstra algorithm for robot path planning
  45. python实现手机号获取短信验证码 | 对接打码平台
  46. Detailed explanation of Euler Rodriguez code in Python
  47. Prove that angular displacement is not a vector with Python
  48. Using Python program to deeply understand homogeneous transfer matrix t
  49. Triple product formula of vector and its proof (with Python code)
  50. Derivation of differential formula of DH matrix using Python
  51. Python openpyxl operation on Excel (get the total number of columns, get the value of a row, get the value of a column, and set the cell value)
  52. Realizing Excel data filtering and data matching with Python
  53. Python reads and writes files
  54. Four scenarios of processing Excel files with Python
  55. Python converts dictionary to excel
  56. Python implements file reading and writing
  57. Basic Python syntax -- functions
  58. Python learning thinking
  59. Basic Python syntax -- lists, dictionaries
  60. Python basic syntax -- conditional judgment, input ()