1

我一直在玩 python 的加密库,并构建了一个简单的线程服务器来加密和解密。我遇到的问题是大约三分之一的解密返回不正确。这是代码:

class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):

    def handle(self):
        global KEY
        request_text = ''
        while request_text.rfind("\n") == -1:
            sock_data='';
            recv_size=8192
            sock_data=self.request.recv(recv_size)
            if sock_data == '':
                print "hangup"
                break
            request_text = request_text + sock_data

        args = json.loads(request_text)
        print request_text
        print "\n"
        if args['command'] == 'encrypt':
            iv = Random.new().read(AES.block_size)
            cipher = AES.new(KEY, AES.MODE_CFB, iv)
            crypted_message = iv + b'|' + cipher.encrypt(unquote_plus(args['message']))
            response = {'encrypted_message': binascii.hexlify(crypted_message)}

        if args['command'] == 'decrypt':
            unhexed = binascii.unhexlify(args['message'])
            components = unhexed.split('|')
            iv = components[0]
            cipher = AES.new(KEY, AES.MODE_CFB, iv)
            decrypted_message = cipher.decrypt(components[1])
            response = {'decrypted_message': decrypted_message}

        self.request.sendall(json.dumps(response) + "\n")

通常,我从 python 得到这个错误:

    Traceback (most recent call last):
  File "/usr/local/lib/python2.7/SocketServer.py", line 582, in process_request_thread
    self.finish_request(request, client_address)
  File "/usr/local/lib/python2.7/SocketServer.py", line 323, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "/usr/local/lib/python2.7/SocketServer.py", line 639, in __init__
    self.handle()
  File "cryptoserver.py", line 40, in handle
    cipher = AES.new(KEY, AES.MODE_CFB, iv)
  File "build/bdist.macosx-10.4-x86_64/egg/Crypto/Cipher/AES.py", line 95, in new
    return AESCipher(key, *args, **kwargs)
  File "build/bdist.macosx-10.4-x86_64/egg/Crypto/Cipher/AES.py", line 59, in __init__
    blockalgo.BlockAlgo.__init__(self, _AES, key, *args, **kwargs)
  File "build/bdist.macosx-10.4-x86_64/egg/Crypto/Cipher/blockalgo.py", line 141, in __init__
    self._cipher = factory.new(key, *args, **kwargs)
ValueError: IV must be 16 bytes long
----------------------------------------

但同样经常,我没有收到错误,但解密无法正常工作。我正在使用这个 php 来测试它:

<?php
include_once("config.php");

function encrypt($text) {
    $package = array("command" => "encrypt",
                    "message" => base64_encode($text));
    $package_json = json_encode($package);
    $serverSays = transmit($package_json);
    $serverSaysArray = json_decode($serverSays);
    return $serverSaysArray->encrypted_message;
}

function decrypt($text) {
    $package = array("command" => "decrypt",
                    "message" => $text);

    $package_json = json_encode($package);
    $serverSays = transmit($package_json);
    $serverSaysArray = json_decode($serverSays);
    return base64_decode($serverSaysArray->decrypted_message);
}

function transmit($package) {
    global $CRYPTO_PORT;
    global $CRYPTO_HOST;

    $serverLink = fsockopen($CRYPTO_HOST, $CRYPTO_PORT);
    if ($serverLink === FALSE) {
        error_log("Could not connect to encryption server");
        return FALSE;
    }
    fwrite($serverLink, $package . "\n");

    $response = '';
    while (!feof($serverLink)) {
        $response .= fgets($serverLink, 128);
    }
    fclose($serverLink);
    return $response;
}

while (TRUE) {
    $enc = encrypt('totsadaddywoopxxx');
    print "$enc\n";
    $dec = decrypt($enc);
    print "$dec\n";
    $enc = encrypt('totsadaddywoopxxx');
    print "$enc\n";
    $dec = decrypt($enc);
    print "$dec\n";
    $enc = encrypt('totsadaddywoopxxx');
    print "$enc\n";
    $dec = decrypt($enc);
    print "$dec\n";
    #print decrypt('1c6dee677126551fa4b3f0732986dc3b7c985c64c07075e3651213d7a69435bcd87083e729e8de860c');
    #print "\n";
    #print decrypt('550cbec7498371dc01bcd6b88fc623b47cb2efd1881da6e07ee992229308305992bbc7ccc374f00c91d56d10a68d6110e2');
    print "===========================\n";

    sleep(1);
}
4

1 回答 1

1

在您的解密例程中,您使用:

 unhexed.split('|')

找到IV和密文之间的边界。但是,IV 是由发送者随机生成的。有时,它的 16 个字节之一是 124,即边界字符“|”。

当这种情况发生时(大约 6% 的情况),解密程序将初始化密码

  • 长度在 1 到 15 个字节之间的 IV,这会导致异常,或者
  • 长度为 0 的 IV,这会导致不正确的解密,因为在 PyCrypto 版本<2.6 中,默认情况下将使用全零的 16 字节 IV

在解密例程中,您应该改为:

components = [ unhexed[:AES.block_size], unhexed[AES.block_size+1:] ]

或者你可以去掉'|' 完全分隔符。

于 2012-08-31T19:43:39.520 回答