anonymous group photoblog software
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.
 
 
 
 
 
 

108 lines
2.7 KiB

  1. '''Module with misleading name for cryptographic code'''
  2. import struct
  3. def rc4(message, key, skip=256):
  4. s = range(256) #0..255
  5. k = [ord(x) for x in key] #unpack 'C*'
  6. message = [ord(x) for x in message]
  7. def swap(x, y):
  8. s[x], s[y] = s[y], s[x]
  9. x = y = 0
  10. for x in xrange(256):
  11. y = (y + s[x] + k[x % len(k)]) % 256
  12. swap(x, y)
  13. x = y = 0
  14. for x in xrange(skip):
  15. x = (x + 1) % 256
  16. y = (y + s[x]) % 256
  17. swap(x, y)
  18. for i in xrange(len(message)):
  19. x = (x + 1) % 256
  20. y = (y + s[x]) % 256
  21. swap(x, y)
  22. message[i] = message[i] ^ s[(s[x] + s[y]) % 256]
  23. return ''.join([chr(x) for x in message])
  24. class RC6(object):
  25. def __init__(self, key):
  26. self.state = S = []
  27. key += "\0" * (4 - len(key) & 3) # pad key
  28. L = list(struct.unpack("<%sL" % (len(key) / 4), key))
  29. S.append(0xb7e15163)
  30. for i in range(43):
  31. S.append(_add(S[i], 0x9e3779b9))
  32. v = max(132, len(L) * 3)
  33. A = B = i = j = 0
  34. for n in range(v):
  35. A = S[i] = _rol(_add(S[i], A, B), 3)
  36. B = L[j] = _rol(_add(L[j] + A + B), _add(A + B))
  37. i = (i + 1) % len(S)
  38. j = (j + 1) % len(L)
  39. def encrypt(self, block):
  40. S = self.state
  41. A, B, C, D = struct.unpack("<4L", block.ljust(16, '\0'))
  42. B = _add(B, S[0])
  43. D = _add(D, S[1])
  44. for i in range(1, 21): # 1..20
  45. t = _rol(_mul(B, _rol(B, 1) | 1), 5)
  46. u = _rol(_mul(D, _rol(D, 1) | 1), 5)
  47. A = _add(_rol(A ^ t, u), S[2 * i])
  48. C = _add(_rol(C ^ u, t), S[2 * i + 1])
  49. A, B, C, D = B, C, D, A
  50. A = _add(A, S[42])
  51. C = _add(C, S[43])
  52. return struct.pack("<4L", A, B, C, D)
  53. def decrypt(self, block):
  54. S = self.state
  55. A, B, C, D = struct.unpack("<4L", block + "\0" * 16)
  56. C = _add(C, -S[43])
  57. A = _add(A, -S[42])
  58. for i in range(20,0,-1): # 20..1
  59. A, B, C, D = D, A, B, C
  60. u = _rol(_mul(D, _add(_rol(D, 1) | 1)), 5)
  61. t = _rol(_mul(B, _add(_rol(B, 1) | 1)), 5)
  62. C = _ror(_add(C, -S[2 * i + 1]), t) ^ u
  63. A = _ror(_add(A, -S[2 * i]), u) ^ t
  64. D = _add(D, -S[1])
  65. B = _add(B, -S[0])
  66. return struct.pack("<4L", A, B, C, D)
  67. # helper functions for rc6
  68. def _add(*args):
  69. return sum(args) % 4294967296
  70. def _rol(x, n):
  71. n = 31 & n
  72. return x << n | 2 ** n - 1 & x >> 32 - n
  73. def _ror(x, y): # rorororor
  74. return _rol(x, 32 - (31 & y))
  75. def _mul(a, b):
  76. return (((a >> 16) * (b & 65535) + (b >> 16) * (a & 65535)) * 65536 +
  77. (a & 65535) * (b & 65535)) % 4294967296