不同的python口译员的不同输出

时间:2015-10-25 20:56:05

标签: python-2.7 python-3.x

我试图在python中实现单字节XOR解密。当我在 python2.7 中运行时,我得到了所需的值
(88, "Cooking MC's like a pound of bacon")
但是当在 python3.2 中运行时,我得到了 (0, b'\x1b77316?x\x15\x1b\x7f+x413=x9x(7-6<x7>x:9;76')

这是我的代码。

'''
Created on Oct 24, 2015

Matasano Crypto Challenge 3
'''

import binascii
from Crypto.Util.strxor import strxor_c  
from collections import Counter
import math

FREQUENCY_TABLE = {
    b'a':  0.08167,
    b'b':  0.01492,
    b'c':  0.02782,
    b'd':  0.04253,
    b'e':  0.1270,
    b'f':  0.02228,
    b'g':  0.02015,
    b'h':  0.06094,
    b'i':  0.06966,
    b'j':  0.00153,
    b'k':  0.00772,
    b'l':  0.04025,
    b'm':  0.02406,
    b'n':  0.06749,
    b'o':  0.07507,
    b'p':  0.01929,
    b'q':  0.00095,
    b'r':  0.05987,
    b's':  0.06327,
    b't':  0.09056,
    b'u':  0.02758,
    b'v':  0.00978,
    b'w':  0.02360,
    b'x':  0.00150,
    b'y':  0.01974,
    b'z':  0.00074,
}

def englishness(a):
    c = Counter(a.lower())
    total_characters = len(a)
    coefficient = sum(math.sqrt(FREQUENCY_TABLE.get(char, 0) * y/total_characters) for char,y in c.items())
    print (coefficient)
    return coefficient

def answer(s):
    print (s)
    def compfunc(items):
        return englishness(items[1])
    return max([(i, strxor_c(s,i)) for i in range(0,256)], key = compfunc)

if __name__ == '__main__':
    encodedS = b'1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736'
    S = binascii.unhexlify(encodedS)
    print (answer(S))

我稍微弄乱了代码,发现englishness()函数没有在python3.2中给出正确的系数(它总是给0)。我无法弄清楚我做错了什么。

1 个答案:

答案 0 :(得分:0)

此行存在问题

coefficient = sum(math.sqrt(FREQUENCY_TABLE.get(char, 0) * y/total_characters) for char,y in c.items())

在Python3中,char是角色的ord - 而不是Python2中的实际角色。比较:

$ python2
Python 2.7.6 (default, Jun 22 2015, 17:58:13) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> [char for char in b'foobar']
['f', 'o', 'o', 'b', 'a', 'r']
>>> 

$ python3
Python 3.4.3 (default, Jul 28 2015, 18:20:59) 
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> [char for char in b'foobar']
[102, 111, 111, 98, 97, 114]

一个快速(丑陋)修复

coefficient = sum(math.sqrt(FREQUENCY_TABLE.get(bytes([char]), 0) * y/total_characters) for char,y in c.items())