算法暴露接口(xhs、dy、ks、wx、hnw)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

36 lines
673 B

7 months ago
  1. """
  2. rc4
  3. """
  4. def KSA(key):
  5. """ Key-Scheduling Algorithm (KSA) """
  6. S = list(range(256))
  7. j = 0
  8. for i in range(256):
  9. j = (j + S[i] + key[i % len(key)]) % 256
  10. S[i], S[j] = S[j], S[i]
  11. return S
  12. def PRGA(S):
  13. """ Pseudo-Random Generation Algorithm (PRGA) """
  14. i, j = 0, 0
  15. while True:
  16. i = (i + 1) % 256
  17. j = (j + S[i]) % 256
  18. S[i], S[j] = S[j], S[i]
  19. K = S[(S[i] + S[j]) % 256]
  20. yield K
  21. def RC4(key, text):
  22. """ RC4 encryption/decryption """
  23. S = KSA(key)
  24. keystream = PRGA(S)
  25. res = []
  26. for char in text:
  27. res.append(char ^ next(keystream))
  28. return bytes(res)