免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 7423 | 回复: 0
打印 上一主题 下一主题

hoxede的QQ填充算法和TEA 加解密的python实现 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2005-07-26 13:34 |只看该作者 |倒序浏览
  1. """
  2. The MIT License

  3. Copyright (c) 2005 hoxide

  4. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

  5. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

  6. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


  7. QQ Crypt module.

  8. """

  9. from struct import pack as _pack
  10. from struct import unpack as _unpack
  11. from binascii import b2a_hex, a2b_hex

  12. from random import seed
  13. from random import randint as _randint

  14. __all__ = ['encrypt', 'decrypt']

  15. seed()

  16. op = 0xffffffffL


  17. def xor(a, b):
  18.     a1,a2 = _unpack('>;LL', a[0:8])
  19.     b1,b2 = _unpack('>;LL', b[0:8])
  20.     r = _pack('>;LL', ( a1 ^ b1) & op, ( a2 ^ b2) & op)
  21.     return r


  22. def code(v, k):
  23.     """
  24.     TEA coder encrypt 64 bits value, by 128 bits key,
  25.     QQ do 16 round TEA.
  26.     To see:
  27.     http://www.ftp.cl.cam.ac.uk/ftp/papers/djw-rmn/djw-rmn-tea.html .
  28.    
  29.     TEA 加密,  64比特明码, 128比特密钥, qq的TEA算法使用16轮迭代
  30.     具体参看
  31.     http://www.ftp.cl.cam.ac.uk/ftp/papers/djw-rmn/djw-rmn-tea.html

  32.     >;>;>; c = code('abcdefgh', 'aaaabbbbccccdddd')
  33.     >;>;>; b2a_hex(c)
  34.     'a557272c538d3e96'
  35.     """
  36.     n=16  #qq use 16
  37.     delta = 0x9e3779b9L
  38.     k = _unpack('>;LLLL', k[0:16])
  39.     y, z = _unpack('>;LL', v[0:8])
  40.     s = 0
  41.     for i in xrange(n):
  42.         s += delta
  43.         y += (op &(z<<4))+ k[0] ^ z+ s ^ (op&(z>;>;5)) + k[1] ;
  44.         y &= op
  45.         z += (op &(y<<4))+ k[2] ^ y+ s ^ (op&(y>;>;5)) + k[3] ;
  46.         z &= op
  47.     r = _pack('>;LL',y,z)
  48.     return r

  49. def encrypt(v, k):
  50.     """
  51.     Encrypt Message follow QQ's rule.
  52.     用QQ的规则加密消息

  53.     v is the message to encrypt, k is the key
  54.     参数 v 是被加密的明文, k是密钥
  55.     fill char is some random numbers (in old QQ is 0xAD)
  56.     填充字符数是随机数, (老的QQ使用0xAD)
  57.     fill n char's n = (8 - (len(v)+2)) %8 + 2
  58.     填充字符的个数 n = (8 - (len(v)+2)) %8 + 2
  59.     ( obviously, n is 2 at least, n is 2-9)
  60.     ( 显然, n至少为2, 取2到9之间)

  61.     then insert (n - 2)|0xF8 in the front of the fill chars
  62.     然后在填充字符前部插入1字节, 值为 ((n - 2)|0xF8)
  63.     to record the number of fill chars.
  64.     以便标记填充字符的个数.
  65.     append 7 '\0' in the end of the message.
  66.     在消息尾部添加7字节'\0'
  67.    
  68.     thus the lenght of the message become filln + 8 + len(v),
  69.     因此消息总长变为 filln + 8 + len(v),
  70.     and it == 0 (mod 8)
  71.     他模8余0(被8整除)

  72.     Encrypt the message .
  73.     加密这段消息
  74.     Per 8 bytes,
  75.     每8字节,
  76.     the result is:
  77.     规则是
  78.    
  79.     r = code( v ^ tr, key) ^ to   (*)

  80.     code is the QQ's TEA function.
  81.     code函数就是QQ 的TEA加密函数.
  82.     v is 8 bytes data to encrypt.
  83.     v是被加密的8字节数据
  84.     tr is the result in preceding round.
  85.     tr是前次加密的结果
  86.     to is the data coded in perceding round, is v_pre ^ r_pre_pre
  87.     to是前次被加密的数据, 等于 v_pre ^ r_pre_pre

  88.     For the first 8 bytes 'tr' and 'to' is zero.
  89.     对头8字节, 'tr' 和 'to' 设为零
  90.    
  91.     loop and loop,
  92.     不断循环,
  93.     that's end.
  94.     结束.
  95.    
  96.     >;>;>; en = encrypt('', b2a_hex('b537a06cf3bcb33206237d7149c27bc3'))
  97.     >;>;>; decrypt(en,  b2a_hex('b537a06cf3bcb33206237d7149c27bc3'))
  98.     ''
  99.     """
  100.     ##FILL_CHAR = chr(0xAD)
  101.     END_CHAR = '\0'
  102.     FILL_N_OR = 0xF8
  103.     vl = len(v)
  104.     filln = (8-(vl+2))%8 + 2;
  105.     fills = ''
  106.     for i in xrange(filln):
  107.         fills = fills + chr(_randint(0, 0xff))
  108.     v = ( chr((filln -2)|FILL_N_OR)
  109.           + fills
  110.           + v
  111.           + END_CHAR * 7)
  112.     tr = '\0'*8
  113.     to = '\0'*8
  114.     r = ''
  115.     o = '\0' * 8
  116.     #print 'len(v)=', len(v)
  117.     for i in xrange(0, len(v), 8):
  118.         o = xor(v[i:i+8], tr)
  119.         tr = xor( code(o, k), to)
  120.         to = o
  121.         r += tr
  122.     return r

  123. def decrypt(v, k):
  124.     """
  125.     DeCrypt Message
  126.     消息解密
  127.    
  128.     by (*) we can find out follow easyly:
  129.     通过(*)式,我们可以容易得发现(明文等于):
  130.    
  131.     x  = decipher(v[i:i+8] ^ prePlain, key) ^ preCyrpt
  132.    
  133.     prePlain is pre 8 byte to be code.
  134.     perPlain 是被加密的前8字节
  135.    
  136.     Attention! It's v per 8 byte value xor pre 8 byte prePlain,
  137.     注意! 他等于前8字节数据异或上前8字节prePlain,
  138.     not just per 8 byte.
  139.     而不只是前8字节.
  140.     preCrypt is pre 8 byte Cryped.
  141.     perCrypt 是前8字节加密结果.

  142.     In the end of deCrypte the raw message,
  143.     在解密完原始数据后,
  144.     we have to cut the filled bytes which was append in encrypt.
  145.     我们必须去除在加密是添加的填充字节.

  146.     the number of the filling bytes in the front of message is
  147.     填充在消息头部的字节数是
  148.     pos + 1.
  149.    
  150.     pos is the first byte of deCrypted --- r[0] & 0x07 + 2
  151.     pos等于解密后的第一字节 --- r[0] & 0x07 + 2

  152.     the end of filling aways is 7 zeros.
  153.     尾部填充始终是7字节零.
  154.     we can test the of 7 bytes is zeros, to make sure it is right.
  155.     我们可以通测试最后7字节是零, 来确定它是正确的.
  156.    
  157.     so return r[pos+1:-7]
  158.     所以返回 r[pos+1:-7]

  159.     >;>;>; r = encrypt('', b2a_hex('b537a06cf3bcb33206237d7149c27bc3'))
  160.     >;>;>; decrypt(r, b2a_hex('b537a06cf3bcb33206237d7149c27bc3'))
  161.     ''
  162.     >;>;>; r = encrypt('abcdefghijklimabcdefghijklmn', b2a_hex('b537a06cf3bcb33206237d7149c27bc3'))
  163.     >;>;>; decrypt(r, b2a_hex('b537a06cf3bcb33206237d7149c27bc3'))
  164.     'abcdefghijklimabcdefghijklmn'
  165.     >;>;>; import md5
  166.     >;>;>; key = md5.new(md5.new('python').digest()).digest()
  167.     >;>;>; data='8CE160B9F312AEC9AC8D8AEAB41A319EDF51FB4BB5E33820C77C48DFC53E2A48CD1C24B29490329D2285897A32E7B32E9830DC2D0695802EB1D9890A0223D0E36C35B24732CE12D06403975B0BC1280EA32B3EE98EAB858C40670C9E1A376AE6C7DCFADD4D45C1081571D2AF3D0F41B73BDC915C3AE542AF2C8B1364614861FC7272E33D90FA012620C18ABF76BE0B9EC0D24017C0C073C469B4376C7C08AA30'
  168.     >;>;>; data = a2b_hex(data)
  169.     >;>;>; b2a_hex(decrypt(data, key))
  170.     '00553361637347436654695a354d7a51531c69f1f5dde81c4332097f0000011f4042c89732030aa4d290f9f941891ae3670bb9c21053397d05f35425c7bf80000000001f40da558a481f40000100004dc573dd2af3b28b6a13e8fa72ea138cd13aa145b0e62554fe8df4b11662a794000000000000000000000000dde81c4342c8966642c4df9142c3a4a9000a000a'
  171.    
  172.     """
  173.     l = len(v)
  174.     #if l%8 !=0 or l<16:
  175.     #    return ''
  176.     prePlain = decipher(v, k)
  177.     pos = (ord(prePlain[0]) & 0x07L) +2
  178.     r = prePlain
  179.     preCrypt = v[0:8]
  180.     for i in xrange(8, l, 8):
  181.         x = xor(decipher(xor(v[i:i+8], prePlain),k ), preCrypt)
  182.         prePlain = xor(x, preCrypt)
  183.         preCrypt = v[i:i+8]
  184.         r += x
  185.     if r[-7:] != '\0'*7: return None
  186.    

  187.     return r[pos+1:-7]

  188. def decipher(v, k):
  189.     """
  190.     TEA decipher, decrypt  64bits value with 128 bits key.
  191.     TEA 解密程序, 用128比特密钥, 解密64比特值

  192.     it's the inverse function of TEA encrypt.
  193.     他是TEA加密函数的反函数.

  194.     >;>;>; c = code('abcdefgh', 'aaaabbbbccccdddd')
  195.     >;>;>; decipher( c, 'aaaabbbbccccdddd')
  196.     'abcdefgh'
  197.     """

  198.     n = 16
  199.     y, z = _unpack('>;LL', v[0:8])
  200.     a, b, c, d = _unpack('>;LLLL', k[0:16])
  201.     delta = 0x9E3779B9L;
  202.     s = (delta << 4)&op
  203.     for i in xrange(n):
  204.         z -= ((y<<4)+c) ^ (y+s) ^ ((y>;>;5) + d)
  205.         z &= op
  206.         y -= ((z<<4)+a) ^ (z+s) ^ ((z>;>;5) + b)
  207.         y &= op
  208.         s -= delta
  209.         s &= op
  210.     return _pack('>;LL', y, z)

  211. def _test():
  212.     import doctest, tea
  213.     return doctest.testmod(tea)


  214. if __name__ == "__main__":
  215.     _test()

复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP