Python Crypto.Cipher.AES 模块,MODE_CTR 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用Crypto.Cipher.AES.MODE_CTR

项目:llk    作者:Tycx2ry    | 项目源码 | 文件源码
def _decrypt_stealth_auth(content, authentication_cookie):
    from Crypto.Cipher import AES
    from Crypto.Util import Counter
    from Crypto.Util.number import bytes_to_long

    # byte 1 = authentication type, 2-17 = input vector, 18 on = encrypted content

    iv, encrypted = content[1:17], content[17:]
    counter = Counter.new(128, initial_value = bytes_to_long(iv))
    cipher = AES.new(authentication_cookie, AES.MODE_CTR, counter = counter)

    return cipher.decrypt(encrypted)
项目:weightlog    作者:pajowu    | 项目源码 | 文件源码
def encrypt(password, data):
    '''
    Encrypt some data.  Input can be bytes or a string (which will be encoded
    using UTF-8).

    @param password: The secret value used as the basis for a key.
    This should be as long as varied as possible.  Try to avoid common words.

    @param data: The data to be encrypted.

    @return: The encrypted data, as bytes.
    '''
    data = _str_to_bytes(data)
    _assert_encrypt_length(data)
    salt = bytes(_random_bytes(SALT_LEN[LATEST]//8))
    hmac_key, cipher_key = _expand_keys(password, salt, EXPANSION_COUNT[LATEST])
    counter = Counter.new(HALF_BLOCK, prefix=salt[:HALF_BLOCK//8])
    cipher = AES.new(cipher_key, AES.MODE_CTR, counter=counter)
    encrypted = cipher.encrypt(data)
    hmac = _hmac(hmac_key, HEADER[LATEST] + salt + encrypted)
    return HEADER[LATEST] + salt + encrypted + hmac
项目:weightlog    作者:pajowu    | 项目源码 | 文件源码
def decrypt(password, data):
    '''
    Decrypt some data.  Input must be bytes.

    @param password: The secret value used as the basis for a key.
    This should be as long as varied as possible.  Try to avoid common words.

    @param data: The data to be decrypted, typically as bytes.

    @return: The decrypted data, as bytes.  If the original message was a
    string you can re-create that using `result.decode('utf8')`.
    '''
    _assert_not_unicode(data)
    _assert_header_prefix(data)
    version = _assert_header_version(data)
    _assert_decrypt_length(data, version)
    raw = data[HEADER_LEN:]
    salt = raw[:SALT_LEN[version]//8]
    hmac_key, cipher_key = _expand_keys(password, salt, EXPANSION_COUNT[version])
    hmac = raw[-HASH.digest_size:]
    hmac2 = _hmac(hmac_key, data[:-HASH.digest_size])
    _assert_hmac(hmac_key, hmac, hmac2)
    counter = Counter.new(HALF_BLOCK, prefix=salt[:HALF_BLOCK//8])
    cipher = AES.new(cipher_key, AES.MODE_CTR, counter=counter)
    return cipher.decrypt(raw[SALT_LEN[version]//8:-HASH.digest_size])
项目:ansible-provider-docs    作者:alibaba    | 项目源码 | 文件源码
def _decrypt_pycrypto(cls, b_ciphertext, b_crypted_hmac, b_key1, b_key2, b_iv):
        # EXIT EARLY IF DIGEST DOESN'T MATCH
        hmac_decrypt = HMAC_pycrypto.new(b_key2, b_ciphertext, SHA256_pycrypto)
        if not cls._is_equal(b_crypted_hmac, to_bytes(hmac_decrypt.hexdigest())):
            return None

        # SET THE COUNTER AND THE CIPHER
        ctr = Counter_pycrypto.new(128, initial_value=int(b_iv, 16))
        cipher = AES_pycrypto.new(b_key1, AES_pycrypto.MODE_CTR, counter=ctr)

        # DECRYPT PADDED DATA
        b_plaintext = cipher.decrypt(b_ciphertext)

        # UNPAD DATA
        if PY3:
            padding_length = b_plaintext[-1]
        else:
            padding_length = ord(b_plaintext[-1])

        b_plaintext = b_plaintext[:-padding_length]
        return b_plaintext
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def _set_key(self, key):
        self.key = key
        self._cipher = AES.new(key, AES.MODE_CTR, counter=self.counter)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def new_cipher(self, key, iv):
        """
        @param key:    the secret key, a byte string
        @param iv:     the initialization vector, a byte string
        @return:    an initialized cipher object for this algo
        """
        if (hasattr(self.cipher, 'MODE_CTR') and self.mode == self.cipher.MODE_CTR
            or hasattr(self.cipher, 'MODE_GCM') and self.mode == self.cipher.MODE_GCM):
            # in counter mode, the "iv" must be incremented for each block
            # it is calculated like this:
            # +---------+------------------+---------+
            # |  nonce  |        IV        | counter |
            # +---------+------------------+---------+
            #   m bytes       n bytes        4 bytes
            # <-------------------------------------->
            #               block_size
            nonce_size = self.cipher.block_size - self.iv_size - 4

            # instead of asking for an extra parameter, we extract the last
            # nonce_size bytes of the key and use them as the nonce.
            # +----------------------------+---------+
            # |        cipher key          |  nonce  |
            # +----------------------------+---------+
            #                              <--------->
            #                               nonce_size
            cipher_key, nonce = key[:-nonce_size], key[-nonce_size:]

            return self.cipher.new(cipher_key, self.mode,
                                   counter=Counter.new(4 * 8, prefix=nonce + iv))
        else:
            return self.cipher.new(key, self.mode, iv)
项目:matasano    作者:shainer    | 项目源码 | 文件源码
def EncryptWithStream(plaintext):
    """Encrypts using AES in CTR mode with random key and nonce."""
    key = Random.new().read(AES.block_size)
    cipher = AES.new(key=key, mode=AES.MODE_CTR, counter=Counter.new(AES.block_size * 8))
    return cipher.encrypt(plaintext)
项目:watchmen    作者:lycclsltt    | 项目源码 | 文件源码
def _set_key(self, key):
        self.key = key
        self._cipher = AES.new(key, AES.MODE_CTR, counter=self.counter)
项目:spiderfoot    作者:wi-fi-analyzer    | 项目源码 | 文件源码
def _decrypt_stealth_auth(content, authentication_cookie):
    from Crypto.Cipher import AES
    from Crypto.Util import Counter
    from Crypto.Util.number import bytes_to_long

    # byte 1 = authentication type, 2-17 = input vector, 18 on = encrypted content

    iv, encrypted = content[1:17], content[17:]
    counter = Counter.new(128, initial_value = bytes_to_long(iv))
    cipher = AES.new(authentication_cookie, AES.MODE_CTR, counter = counter)

    return cipher.decrypt(encrypted)
项目:aws-cfn-plex    作者:lordmuffin    | 项目源码 | 文件源码
def _set_key(self, key):
        self.key = key
        self._cipher = AES.new(key, AES.MODE_CTR, counter=self.counter)
项目:militarygrade    作者:tiran    | 项目源码 | 文件源码
def encrypt_image(name, key, iv):
    img = Image.open(name)
    img = img.convert(mode='RGB')
    counter = Counter.new(128, initial_value=iv)
    cipher = AES.new(key, AES.MODE_CTR, counter=counter)
    return cipher.encrypt(img.tobytes()), img


# random key for AES-256
项目:git_intgrtn_aws_s3    作者:droidlabour    | 项目源码 | 文件源码
def _set_key(self, key):
        self.key = key
        self._cipher = AES.new(key, AES.MODE_CTR, counter=self.counter)
项目:MCSManager-fsmodule    作者:Suwings    | 项目源码 | 文件源码
def _set_key(self, key):
        self.key = key
        self._cipher = AES.new(key, AES.MODE_CTR, counter=self.counter)
项目:MCSManager-fsmodule    作者:Suwings    | 项目源码 | 文件源码
def aesEncrypt(data, key):
        cipher = AES.new(key, AES.MODE_CTR,
                         counter=Counter.new(128, initial_value=0))

        return cipher.encrypt(data)
项目:MCSManager-fsmodule    作者:Suwings    | 项目源码 | 文件源码
def aesDecrypt(data, key):
        cipher = AES.new(key, AES.MODE_CTR,
                         counter=Counter.new(128, initial_value=0))
        return cipher.decrypt(data)
项目:pupy    作者:ru-faraon    | 项目源码 | 文件源码
def __init__(self, key, iv, counter_wraparound=False):
        """Initialize AES with the given key and IV.

        If counter_wraparound is set to True, the AES-CTR counter will
        wraparound to 0 when it overflows.
        """

        assert(len(key) == 16)
        assert(len(iv) == 16)

        self.ctr = Counter.new(128, initial_value=long(iv.encode('hex'), 16),
                               allow_wraparound=counter_wraparound)
        self.cipher = AES.new(key, AES.MODE_CTR, counter=self.ctr)
项目:DevOps    作者:YoLoveLife    | 项目源码 | 文件源码
def encrypt(self, b_plaintext, b_password):
        b_salt = os.urandom(32)
        b_key1, b_key2, b_iv = self._gen_key_initctr(b_password, b_salt)

        # PKCS#7 PAD DATA http://tools.ietf.org/html/rfc5652#section-6.3
        bs = AES.block_size
        padding_length = (bs - len(b_plaintext) % bs) or bs
        b_plaintext += to_bytes(padding_length * chr(padding_length), encoding='ascii', errors='strict')

        # COUNTER.new PARAMETERS
        # 1) nbits (integer) - Length of the counter, in bits.
        # 2) initial_value (integer) - initial value of the counter. "iv" from _gen_key_initctr

        ctr = Counter.new(128, initial_value=int(b_iv, 16))

        # AES.new PARAMETERS
        # 1) AES key, must be either 16, 24, or 32 bytes long -- "key" from _gen_key_initctr
        # 2) MODE_CTR, is the recommended mode
        # 3) counter=<CounterObject>

        cipher = AES.new(b_key1, AES.MODE_CTR, counter=ctr)

        # ENCRYPT PADDED DATA
        b_ciphertext = cipher.encrypt(b_plaintext)

        # COMBINE SALT, DIGEST AND DATA
        hmac = HMAC.new(b_key2, b_ciphertext, SHA256)
        b_vaulttext = b'\n'.join([hexlify(b_salt), to_bytes(hmac.hexdigest()), hexlify(b_ciphertext)])
        b_vaulttext = hexlify(b_vaulttext)
        return b_vaulttext
项目:DevOps    作者:YoLoveLife    | 项目源码 | 文件源码
def decrypt(self, b_vaulttext, b_password):
        # SPLIT SALT, DIGEST, AND DATA
        b_vaulttext = unhexlify(b_vaulttext)
        b_salt, b_cryptedHmac, b_ciphertext = b_vaulttext.split(b"\n", 2)
        b_salt = unhexlify(b_salt)
        b_ciphertext = unhexlify(b_ciphertext)
        b_key1, b_key2, b_iv = self._gen_key_initctr(b_password, b_salt)

        # EXIT EARLY IF DIGEST DOESN'T MATCH
        hmacDecrypt = HMAC.new(b_key2, b_ciphertext, SHA256)
        if not self._is_equal(b_cryptedHmac, to_bytes(hmacDecrypt.hexdigest())):
            return None
        # SET THE COUNTER AND THE CIPHER
        ctr = Counter.new(128, initial_value=int(b_iv, 16))
        cipher = AES.new(b_key1, AES.MODE_CTR, counter=ctr)

        # DECRYPT PADDED DATA
        b_plaintext = cipher.decrypt(b_ciphertext)

        # UNPAD DATA
        if PY3:
            padding_length = b_plaintext[-1]
        else:
            padding_length = ord(b_plaintext[-1])

        b_plaintext = b_plaintext[:-padding_length]
        return b_plaintext
项目:ActualBotNet    作者:invasi0nZ    | 项目源码 | 文件源码
def encrypt(self, data):
        print str(data)
        cipher = AES.new(self._key(), AES.MODE_CTR, counter=lambda: self._key()[:16])
        data = self._pad(data)
        data = cipher.encrypt(data)
        cipher = XOR.new(self._key())
        data = cipher.encrypt(data)
        data =  base64.b64encode(data)
        return data
项目:ActualBotNet    作者:invasi0nZ    | 项目源码 | 文件源码
def decrypt(self, data):
        cipher = XOR.new(self._key())
        data = base64.b64decode(data)
        data = cipher.decrypt(data)
        cipher = AES.new(self._key(), AES.MODE_CTR, counter=lambda: self._key()[:16])
        data = cipher.decrypt(data)
        data = self._unpad(data)
        return data
项目:ActualBotNet    作者:invasi0nZ    | 项目源码 | 文件源码
def encrypt(self, data):
        cipher = AES.new(self._key(), AES.MODE_CTR, counter=lambda: self._key()[:16])
        data = self._pad(data)
        data = cipher.encrypt(data)
        cipher = XOR.new(self._key())
        data = cipher.encrypt(data)
        data = base64.b64encode(data)
        return data
项目:ActualBotNet    作者:invasi0nZ    | 项目源码 | 文件源码
def decrypt(self, data):
        cipher = XOR.new(self._key())
        data = base64.b64decode(data)
        data = cipher.decrypt(data)
        cipher = AES.new(self._key(), AES.MODE_CTR, counter=lambda: self._key()[:16])
        data = cipher.decrypt(data)
        data = self._unpad(data)
        return data
项目:airpyrt-tools    作者:x56    | 项目源码 | 文件源码
def __init__(self, key, iv):
        self.key = key
        self.iv = iv

        self.ctr = Counter.new(128, initial_value=int(iv.encode("hex"), 16))
        self.cipher = AES.new(key, AES.MODE_CTR, counter=self.ctr)
项目:trex-http-proxy    作者:alwye    | 项目源码 | 文件源码
def new_cipher(self, key, iv):
        """
        @param key:    the secret key, a byte string
        @param iv:     the initialization vector, a byte string
        @return:    an initialized cipher object for this algo
        """
        if (hasattr(self.cipher, 'MODE_CTR') and self.mode == self.cipher.MODE_CTR
            or hasattr(self.cipher, 'MODE_GCM') and self.mode == self.cipher.MODE_GCM):
            # in counter mode, the "iv" must be incremented for each block
            # it is calculated like this:
            # +---------+------------------+---------+
            # |  nonce  |        IV        | counter |
            # +---------+------------------+---------+
            #   m bytes       n bytes        4 bytes
            # <-------------------------------------->
            #               block_size
            nonce_size = self.cipher.block_size - self.iv_size - 4

            # instead of asking for an extra parameter, we extract the last
            # nonce_size bytes of the key and use them as the nonce.
            # +----------------------------+---------+
            # |        cipher key          |  nonce  |
            # +----------------------------+---------+
            #                              <--------->
            #                               nonce_size
            cipher_key, nonce = key[:-nonce_size], key[-nonce_size:]

            return self.cipher.new(cipher_key, self.mode,
                                   counter=Counter.new(4 * 8, prefix=nonce + iv))
        else:
            return self.cipher.new(key, self.mode, iv)
项目:trex-http-proxy    作者:alwye    | 项目源码 | 文件源码
def new_cipher(self, key, iv):
        """
        @param key:    the secret key, a byte string
        @param iv:     the initialization vector, a byte string
        @return:    an initialized cipher object for this algo
        """
        if type(key) is str:
            key = key.encode('ascii')
        if (hasattr(self.cipher, 'MODE_CTR') and self.mode == self.cipher.MODE_CTR
            or hasattr(self.cipher, 'MODE_GCM') and self.mode == self.cipher.MODE_GCM):
            # in counter mode, the "iv" must be incremented for each block
            # it is calculated like this:
            # +---------+------------------+---------+
            # |  nonce  |        IV        | counter |
            # +---------+------------------+---------+
            #   m bytes       n bytes        4 bytes
            # <-------------------------------------->
            #               block_size
            nonce_size = self.cipher.block_size - self.iv_size - 4

            # instead of asking for an extra parameter, we extract the last
            # nonce_size bytes of the key and use them as the nonce.
            # +----------------------------+---------+
            # |        cipher key          |  nonce  |
            # +----------------------------+---------+
            #                              <--------->
            #                               nonce_size
            cipher_key, nonce = key[:-nonce_size], key[-nonce_size:]

            return self.cipher.new(cipher_key, self.mode,
                                   counter=Counter.new(4 * 8, prefix=nonce + iv))
        else:
            return self.cipher.new(key, self.mode, iv)
项目:PyMal    作者:cysinfo    | 项目源码 | 文件源码
def _set_key(self, key):
        self.key = key
        self._cipher = AES.new(key, AES.MODE_CTR, counter=self.counter)
项目:SublimeRemoteGDB    作者:summerwinter    | 项目源码 | 文件源码
def _set_key(self, key):
        self.key = key
        self._cipher = AES.new(key, AES.MODE_CTR, counter=self.counter)
项目:scapy-bpf    作者:guedou    | 项目源码 | 文件源码
def new_cipher(self, key, iv):
        """
        @param key:    the secret key, a byte string
        @param iv:     the initialization vector, a byte string
        @return:    an initialized cipher object for this algo
        """
        if (hasattr(self.cipher, 'MODE_CTR') and self.mode == self.cipher.MODE_CTR
            or self.is_aead):
            # in counter mode, the "iv" must be incremented for each block
            # it is calculated like this:
            # +---------+------------------+---------+
            # |  nonce  |        IV        | counter |
            # +---------+------------------+---------+
            #   m bytes       n bytes        4 bytes
            # <-------------------------------------->
            #               block_size
            nonce_size = self.cipher.block_size - self.iv_size - 4

            # instead of asking for an extra parameter, we extract the last
            # nonce_size bytes of the key and use them as the nonce.
            # +----------------------------+---------+
            # |        cipher key          |  nonce  |
            # +----------------------------+---------+
            #                              <--------->
            #                               nonce_size
            cipher_key, nonce = key[:-nonce_size], key[-nonce_size:]
            if self.is_aead:
                return self.cipher.new(cipher_key, self.mode, nonce + iv,
                                       counter=Counter.new(4 * 8, prefix=nonce + iv))

            return self.cipher.new(cipher_key, self.mode,
                                   counter=Counter.new(4 * 8, prefix=nonce + iv))
        else:
            return self.cipher.new(key, self.mode, iv)
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def _set_key(self, key):
        self.key = key
        self._cipher = AES.new(key, AES.MODE_CTR, counter=self.counter)
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def new_cipher(self, key, iv):
        """
        @param key:    the secret key, a byte string
        @param iv:     the initialization vector, a byte string
        @return:    an initialized cipher object for this algo
        """
        if (hasattr(self.cipher, 'MODE_CTR') and self.mode == self.cipher.MODE_CTR
            or hasattr(self.cipher, 'MODE_GCM') and self.mode == self.cipher.MODE_GCM):
            # in counter mode, the "iv" must be incremented for each block
            # it is calculated like this:
            # +---------+------------------+---------+
            # |  nonce  |        IV        | counter |
            # +---------+------------------+---------+
            #   m bytes       n bytes        4 bytes
            # <-------------------------------------->
            #               block_size
            nonce_size = self.cipher.block_size - self.iv_size - 4

            # instead of asking for an extra parameter, we extract the last
            # nonce_size bytes of the key and use them as the nonce.
            # +----------------------------+---------+
            # |        cipher key          |  nonce  |
            # +----------------------------+---------+
            #                              <--------->
            #                               nonce_size
            cipher_key, nonce = key[:-nonce_size], key[-nonce_size:]

            return self.cipher.new(cipher_key, self.mode,
                                   counter=Counter.new(4 * 8, prefix=nonce + iv))
        else:
            return self.cipher.new(key, self.mode, iv)
项目:Encryped-file-system    作者:kittenish    | 项目源码 | 文件源码
def _set_key(self, key):
        self.key = key
        self._cipher = AES.new(key, AES.MODE_CTR, counter=self.counter)
项目:python-group-proj    作者:Sharcee    | 项目源码 | 文件源码
def aesEncrypt(data, key):
        cipher = AES.new(key, AES.MODE_CTR,
                         counter=Counter.new(128, initial_value=0))

        return cipher.encrypt(data)
项目:python-group-proj    作者:Sharcee    | 项目源码 | 文件源码
def aesDecrypt(data, key):
        cipher = AES.new(key, AES.MODE_CTR,
                         counter=Counter.new(128, initial_value=0))
        return cipher.decrypt(data)
项目:scapy-radio    作者:BastilleResearch    | 项目源码 | 文件源码
def new_cipher(self, key, iv):
        """
        @param key:    the secret key, a byte string
        @param iv:     the initialization vector, a byte string
        @return:    an initialized cipher object for this algo
        """
        if (hasattr(self.cipher, 'MODE_CTR') and self.mode == self.cipher.MODE_CTR
            or hasattr(self.cipher, 'MODE_GCM') and self.mode == self.cipher.MODE_GCM):
            # in counter mode, the "iv" must be incremented for each block
            # it is calculated like this:
            # +---------+------------------+---------+
            # |  nonce  |        IV        | counter |
            # +---------+------------------+---------+
            #   m bytes       n bytes        4 bytes
            # <-------------------------------------->
            #               block_size
            nonce_size = self.cipher.block_size - self.iv_size - 4

            # instead of asking for an extra parameter, we extract the last
            # nonce_size bytes of the key and use them as the nonce.
            # +----------------------------+---------+
            # |        cipher key          |  nonce  |
            # +----------------------------+---------+
            #                              <--------->
            #                               nonce_size
            cipher_key, nonce = key[:-nonce_size], key[-nonce_size:]

            return self.cipher.new(cipher_key, self.mode,
                                   counter=Counter.new(4 * 8, prefix=nonce + iv))
        else:
            return self.cipher.new(key, self.mode, iv)
项目:isf    作者:w3h    | 项目源码 | 文件源码
def _set_key(self, key):
        self.key = key
        self._cipher = AES.new(key, AES.MODE_CTR, counter=self.counter)
项目:isf    作者:w3h    | 项目源码 | 文件源码
def new_cipher(self, key, iv):
        """
        @param key:    the secret key, a byte string
        @param iv:     the initialization vector, a byte string
        @return:    an initialized cipher object for this algo
        """
        if (hasattr(self.cipher, 'MODE_CTR') and self.mode == self.cipher.MODE_CTR
            or self.is_aead):
            # in counter mode, the "iv" must be incremented for each block
            # it is calculated like this:
            # +---------+------------------+---------+
            # |  nonce  |        IV        | counter |
            # +---------+------------------+---------+
            #   m bytes       n bytes        4 bytes
            # <-------------------------------------->
            #               block_size
            nonce_size = self.cipher.block_size - self.iv_size - 4

            # instead of asking for an extra parameter, we extract the last
            # nonce_size bytes of the key and use them as the nonce.
            # +----------------------------+---------+
            # |        cipher key          |  nonce  |
            # +----------------------------+---------+
            #                              <--------->
            #                               nonce_size
            cipher_key, nonce = key[:-nonce_size], key[-nonce_size:]
            if self.is_aead:
                return self.cipher.new(cipher_key, self.mode, nonce + iv,
                                       counter=Counter.new(4 * 8, prefix=nonce + iv))

            return self.cipher.new(cipher_key, self.mode,
                                   counter=Counter.new(4 * 8, prefix=nonce + iv))
        else:
            return self.cipher.new(key, self.mode, iv)
项目:pelisalacarta-ce    作者:pelisalacarta-ce    | 项目源码 | 文件源码
def prepare_decoder(self,offset):
        initial_value = self.initial_value + int(offset/16)
        self.decryptor = AES.new(self._file._client.a32_to_str(self.k), AES.MODE_CTR, counter = Counter.new(128, initial_value = initial_value))
        #self.decryptor = aes.AESModeOfOperationCTR(f=self,key=self._client.a32_to_str(self.k),counter=aes.Counter(initial_value=initial_value))
        rest = offset - int(offset/16)*16
        if rest:
            self.decode(str(0)*rest)
项目:MrRAT    作者:user696    | 项目源码 | 文件源码
def encrypt(self, init_value, plaintext, auth_data=b''):
        if init_value >= (1 << 96):
            raise InvalidInputException('IV should be 96-bit')
        # a naive checking for IV reuse
        if init_value == self.prev_init_value:
            raise InvalidInputException('IV must not be reused!')
        self.prev_init_value = init_value

        len_plaintext = len(plaintext)
        # len_auth_data = len(auth_data)

        if len_plaintext > 0:
            counter = Counter.new(
                nbits=32,
                prefix=long_to_bytes(init_value, 12),
                initial_value=2,  # notice this
                allow_wraparound=False)
            aes_ctr = AES.new(self.__master_key, AES.MODE_CTR, counter=counter)

            if 0 != len_plaintext % 16:
                padded_plaintext = plaintext + \
                    b'\x00' * (16 - len_plaintext % 16)
            else:
                padded_plaintext = plaintext
            ciphertext = aes_ctr.encrypt(padded_plaintext)[:len_plaintext]

        else:
            ciphertext = b''

        auth_tag = self.__ghash(auth_data, ciphertext)
        # print 'GHASH\t', hex(auth_tag)
        auth_tag ^= bytes_to_long(self.__aes_ecb.encrypt(
                                  long_to_bytes((init_value << 32) | 1, 16)))

        # assert len(ciphertext) == len(plaintext)
        assert auth_tag < (1 << 128)
        return ciphertext, auth_tag
项目:MrRAT    作者:user696    | 项目源码 | 文件源码
def decrypt(self, init_value, ciphertext, auth_tag, auth_data=b''):
        if init_value >= (1 << 96):
            raise InvalidInputException('IV should be 96-bit')
        if auth_tag >= (1 << 128):
            raise InvalidInputException('Tag should be 128-bit')

        if auth_tag != self.__ghash(auth_data, ciphertext) ^ \
                bytes_to_long(self.__aes_ecb.encrypt(
                long_to_bytes((init_value << 32) | 1, 16))):
            raise InvalidTagException

        len_ciphertext = len(ciphertext)
        if len_ciphertext > 0:
            counter = Counter.new(
                nbits=32,
                prefix=long_to_bytes(init_value, 12),
                initial_value=2,
                allow_wraparound=True)
            aes_ctr = AES.new(self.__master_key, AES.MODE_CTR, counter=counter)

            if 0 != len_ciphertext % 16:
                padded_ciphertext = ciphertext + \
                    b'\x00' * (16 - len_ciphertext % 16)
            else:
                padded_ciphertext = ciphertext
            plaintext = aes_ctr.decrypt(padded_ciphertext)[:len_ciphertext]

        else:
            plaintext = b''

        return plaintext
项目:yw_save    作者:togenyan    | 项目源码 | 文件源码
def resetCTR(self, nonce):
        self.L = 15 - len(nonce)
        self.L_prime = self.L - 1
        self.N = len(nonce)
        self.nonce = nonce

        data = bytes([self.L_prime]) + nonce
        ctr = Counter.new((0x10 - len(data)) * 8, prefix=data, initial_value=0)
        self.aes_ctr = AES.new(self.key, mode=AES.MODE_CTR, counter=ctr)
项目:pyethereum    作者:ethereumproject    | 项目源码 | 文件源码
def aes_ctr_encrypt(text, key, params):
    iv = big_endian_to_int(decode_hex(params["iv"]))
    ctr = Counter.new(128, initial_value=iv,  allow_wraparound=True)
    mode = AES.MODE_CTR
    encryptor = AES.new(key, mode, counter=ctr)
    return encryptor.encrypt(text)
项目:pyethereum    作者:ethereumproject    | 项目源码 | 文件源码
def aes_ctr_decrypt(text, key, params):
    iv = big_endian_to_int(decode_hex(params["iv"]))
    ctr = Counter.new(128, initial_value=iv,  allow_wraparound=True)
    mode = AES.MODE_CTR
    encryptor = AES.new(key, mode, counter=ctr)
    return encryptor.decrypt(text)
项目:plugin.video.streamondemand-pureita    作者:orione7    | 项目源码 | 文件源码
def prepare_decoder(self,offset):
        initial_value = self.initial_value + int(offset/16)
        self.decryptor = AES.new(self._file._client.a32_to_str(self.k), AES.MODE_CTR, counter = Counter.new(128, initial_value = initial_value))
        #self.decryptor = aes.AESModeOfOperationCTR(f=self,key=self._client.a32_to_str(self.k),counter=aes.Counter(initial_value=initial_value))
        rest = offset - int(offset/16)*16
        if rest:
            self.decode(str(0)*rest)
项目:rocksmith    作者:0x0L    | 项目源码 | 文件源码
def aes_sng(key, ivector):
    ctr = counter._newBE(b'', b'', ivector, allow_wraparound=False)
    return AES.new(key, mode=AES.MODE_CTR, counter=ctr)
项目:Mac-Python-3.X    作者:L1nwatch    | 项目源码 | 文件源码
def _decrypt_file(self, encrypted_file=None):
        def __decrypt_aes_key(decrypter, encrypted_key):
            plain_text = decrypter.decrypt(encrypted_key)
            return plain_text

        def __decrypt_encrypted_file(file_path):
            aes_key = __decrypt_aes_key(self.rsa, self.encrypted_aes_key)

            with open(file_path, "rb") as f:
                data = f.read()

            counter = slice(0, 16)
            aes = AES.new(aes_key, AES.MODE_CTR, counter=lambda: data[counter])
            file_contents = aes.decrypt(data[16:])

            return file_contents

        if encrypted_file is None:
            # http://www.xuebuyuan.com/1918954.html
            encrypted_file = tkinter.filedialog.askopenfilename(title="????????")
            if encrypted_file == "":
                return

        file_path = tkinter.filedialog.asksaveasfilename(title="??????????")
        file_contents = __decrypt_encrypted_file(encrypted_file)
        self._update_state_board("????!", new=True)
        with open(file_path, "wb") as f:
            f.write(file_contents)

        return file_contents
项目:kekescan    作者:xiaoxiaoleo    | 项目源码 | 文件源码
def _set_key(self, key):
        self.key = key
        self._cipher = AES.new(key, AES.MODE_CTR, counter=self.counter)
项目:Repobot    作者:Desgard    | 项目源码 | 文件源码
def _set_key(self, key):
        self.key = key
        self._cipher = AES.new(key, AES.MODE_CTR, counter=self.counter)
项目:PACE-python    作者:mit-ll    | 项目源码 | 文件源码
def _encrypt(plaintext, key, init_ctr=None):
        """Optional initial counter argument, to be used only for testing 
           purposes, must be the AES block length (16 bytes).
        """

        #Deal with the case when field is empty
        if plaintext is None:
            plaintext = ''

        if init_ctr is not None:
            if len(init_ctr) != AES.block_size:
                raise EncryptionException('Initial counter must be ' + 
                                          str(AES.block_size) + ' bytes')
            else:
                #Convert counter bytes to an integer (an unsigned long long), 
                #in two steps because unpack takes 8-byte (not 16-byte) input
                int1 = struct.unpack('>Q', init_ctr[:AES.block_size//2])[0]
                int2 = struct.unpack('>Q', init_ctr[AES.block_size//2:])[0]
                init_ctr_int = int1 * 2**(AES.block_size*4) + int2

        if init_ctr is None:
            #Generate 64-bit nonce randomly
            nonce = Random.new().read(AES.block_size//2)
            #Set remaining 64 bits to be a block counter starting at 1
            init_ctr = struct.pack('15s', nonce) + '\x01'
            #Compute integer version of initial counter by scaling nonce by 
            #64 bits and adding 1
            init_ctr_int = struct.unpack('>Q', nonce)[0]*2**(AES.block_size*4)+1

        ctr = Counter.new(AES.block_size*8, initial_value = init_ctr_int)
        cipher = AES.new(key, AES.MODE_CTR, counter = ctr) 
        return init_ctr + cipher.encrypt(plaintext)
项目:PACE-python    作者:mit-ll    | 项目源码 | 文件源码
def _decrypt(ciphertext, key):
        #error handling
        Pycrypto_AES_Base._has_iv_material(ciphertext)
        try: 
            nonce = struct.unpack('>Q', ciphertext[:AES.block_size//2])[0]
            block_ctr = struct.unpack(
                '>Q', 
                ciphertext[AES.block_size//2 : AES.block_size])[0]
            init_ctr = nonce * 2**(AES.block_size*4) + block_ctr
        except ValueError:
            raise DecryptionException("Value for the start counter value is not an integer.")

        ctr = Counter.new(AES.block_size*8, initial_value = init_ctr)
        cipher = AES.new(key, AES.MODE_CTR, counter = ctr)
        return cipher.decrypt(str(ciphertext[AES.block_size:]))
项目:blockhooks    作者:EthereumWebhooks    | 项目源码 | 文件源码
def aes_ctr_encrypt(text, key, params):
    iv = big_endian_to_int(decode_hex(params["iv"]))
    ctr = Counter.new(128, initial_value=iv,  allow_wraparound=True)
    mode = AES.MODE_CTR
    encryptor = AES.new(key, mode, counter=ctr)
    return encryptor.encrypt(text)