AES CTR实施

时间:2014-01-29 19:18:33

标签: python cryptography pycrypto

我正在尝试自己实现CTR模式(目前仅解密),仅使用pycrypto的AES内置函数。这意味着我不应该使用mode = AES.MODE_CTR。但是,我知道使用AES.MODE_CTR会更简单,但我这样做是为了学习体验。

我不确定如何将AES用作PRF,以便在CTR加密算法中使用它。

我做错了什么? (非parallalel版)

from Crypto.Cipher import AES

ciphers = ["69dda8455c7dd4254bf353b773304eec0ec7702330098ce7f7520d1cbbb20fc3" + \
    "88d1b0adb5054dbd7370849dbf0b88d393f252e764f1f5f7ad97ef79d59ce29f5f51eeca32eabedd9afa9329", \
    "770b80259ec33beb2561358a9f2dc617e46218c0a53cbeca695ae45faa8952aa" + \
    "0e311bde9d4e01726d3184c34451"]

key     = "36f18357be4dbd77f050515c73fcf9f2"  

class IVCounter(object):
    def __init__(self, value):
        self.value = value

    def increment(self):
        # Add the counter value to IV
        newIV = hex(int(self.value.encode('hex'), 16) + 1)

        # Cut the negligible part of the string
        self.value = newIV[2:len(newIV) - 1].decode('hex') # for not L strings remove $ - 1 $ 
        return self.value

    def __repr__(self):
        self.increment()
        return self.value

    def string(self):
        return self.value

class CTR():
    def __init__(self, k):
        self.key = k

    def __strxor(self, a, b):     # xor two strings of different lengths
        if len(a) > len(b):
            return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a[:len(b)], b)])
        else:
            return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b[:len(a)])])

    def __split_len(self, seq, lenght):
        return [seq[i:i+lenght] for i in range(0, len(seq), lenght)]

    def __AESdecryptor(self, k, cipher):
        decryptor = AES.new(k, AES.MODE_ECB)

        return decryptor.decrypt(cipher)

    def decrypt(self, cipher):
        # Split the CT in blocks of 16 bytes
        blocks = self.__split_len(cipher.decode('hex'), 16)

        # Takes the initiator vector
        self.IV = IVCounter(blocks[0])
        blocks.remove(blocks[0])    

        # Message block 
        msg = []

        # Decrypt
        for b in blocks:
            aes = self.__AESdecryptor(self.key.decode('hex'), self.IV.string())
            msg.append(self.__strxor(b, aes))

            self.IV.increment()

        return ''.join(msg)

def main():
    decryptor = CTR(key)
    for c in ciphers:
        print 'msg = ' + decryptor.decrypt(c)

if __name__ == '__main__':
    main()

这段代码应该和下面的代码一样,但它不是应该解码的。

import Crypto.Util.Counter
ctr_e = Crypto.Util.Counter.new(128, initial_value=long(IV.encode('hex'), 16))
decryptor = AES.new(key.decode('hex'), AES.MODE_CTR, counter=ctr_e)
print decryptor.decrypt(''.join(blocks))

2 个答案:

答案 0 :(得分:2)

# Decrypt
for b in blocks:
    aes = self.__AESdecryptor(self.IV.string(), self.key.decode('hex'))
    msg.append(self.__strxor(b, aes))
    self.IV.increment()

return ''.join(msg)

AES CTR模式使用AES的正向转换进行加密和解密。也就是说,在两种情况下,加密计数器然后执行XOR。当我说'向前转型'时,我的意思是你总是执行AES_Encrypt(counter)(并且从不执​​行AES_Decrypt(counter))。

无论是加密还是解密,都可以对纯文本和密文执行XOR。 text XOR encrypt(counter)是加密或解密操作。这是一个流密码。

self.IV.string()不是AES密钥。它是在密钥下加密的值。加密后,使用{plain | cipher}文本进行异或。

答案 1 :(得分:2)

我终于让这段代码运行良好,错误非常简单。我不应该使用解密AES功能,我应该使用加密AES功能(正如noloader所说,我第一次不太了解他)。感谢所有帮助过的人,这里是固定代码:

from Crypto.Cipher import AES

ciphers = ["69dda8455c7dd4254bf353b773304eec0ec7702330098ce7f7520d1cbbb20fc3" + \
    "88d1b0adb5054dbd7370849dbf0b88d393f252e764f1f5f7ad97ef79d59ce29f5f51eeca32eabedd9afa9329",      \
    "770b80259ec33beb2561358a9f2dc617e46218c0a53cbeca695ae45faa8952aa" + \
    "0e311bde9d4e01726d3184c34451"]

key     = "36f18357be4dbd77f050515c73fcf9f2"  

class IVCounter(object):
    def __init__(self, value):
    self.value = value

    def increment(self):
        # Add the counter value to IV
        newIV = hex(int(self.value.encode('hex'), 16) + 1)

        # Cut the negligible part of the string
        self.value = newIV[2:len(newIV) - 1].decode('hex') # for not L strings remove $ - 1 $ 
        return self.value

    def __repr__(self):
        self.increment()
        return self.value

    def string(self):
        return self.value

class CTR():
    def __init__(self, k):
        self.key = k.decode('hex')

    def __strxor(self, a, b):     # xor two strings of different lengths
        if len(a) > len(b):
        return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a[:len(b)], b)])
        else:
        return "".join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b[:len(a)])])

    def __split_len(self, seq, lenght):
        return [seq[i:i+lenght] for i in range(0, len(seq), lenght)]

    def __AESencryptor(self, cipher):
        encryptor = AES.new(self.key, AES.MODE_ECB)
        return encryptor.encrypt(cipher)

    def decrypt(self, cipher):
        # Split the CT into blocks of 16 bytes
        blocks = self.__split_len(cipher.decode('hex'), 16)

        # Takes the initiator vector
        self.IV = IVCounter(blocks[0])
        blocks.remove(blocks[0])    

        # Message block 
        msg = []

        # Decrypt
        for b in blocks:
        aes = self.__AESencryptor(self.IV.string())
        msg.append(self.__strxor(b, aes))

        self.IV.increment()

        return ''.join(msg)

def main():
    decryptor = CTR(key)
    for c in ciphers:
    print 'msg = ' + decryptor.decrypt(c)

if __name__ == '__main__':
    main()