Beispiel #1
0
 def _start_gcm(self, factory, key, *args, **kwargs):
     if self.block_size != 16:
         raise TypeError('GCM mode is only available for ciphers that operate on 128 bits blocks')
     self.nonce = _getParameter('nonce', 1, args, kwargs)
     if not self.nonce:
         raise TypeError('MODE_GCM requires a nonce')
     self._mac_len = kwargs.get('mac_len', 16)
     if not (self._mac_len and 4 <= self._mac_len <= 16):
         raise ValueError("Parameter 'mac_len' must not be larger than 16 bytes")
     self._next = [self.update,
      self.encrypt,
      self.decrypt,
      self.digest,
      self.verify]
     self._done_assoc_data = False
     self._msg_len = 0
     hash_subkey = factory.new(key).encrypt(bchr(0) * 16)
     if len(self.nonce) == 12:
         self._j0 = bytes_to_long(self.nonce + b('\x00\x00\x00\x01'))
     else:
         fill = (16 - len(self.nonce) % 16) % 16 + 8
         ghash_in = self.nonce + bchr(0) * fill + long_to_bytes(8 * len(self.nonce), 8)
         mac = _GHASH(hash_subkey, factory.block_size)
         mac.update(ghash_in)
         self._j0 = bytes_to_long(mac.digest())
     ctr = Counter.new(128, initial_value=self._j0 + 1, allow_wraparound=True)
     self._cipher = self._factory.new(key, MODE_CTR, counter=ctr)
     self._cipherMAC = _GHASH(hash_subkey, factory.block_size)
     ctr = Counter.new(128, initial_value=self._j0, allow_wraparound=True)
     self._tag_cipher = self._factory.new(key, MODE_CTR, counter=ctr)
Beispiel #2
0
    def runTest(self):
        from Crypto.Util import Counter

        def pythonCounter():
            state = [0]
            def ctr():
                # First block succeeds; Second and subsequent blocks raise OverflowError
                if state[0] == 0:
                    state[0] = 1
                    return b("\xff") * self.module.block_size
                else:
                    raise OverflowError
            return ctr

        for little_endian in (0, 1): # (False, True) Test both endiannesses
            block = b("\x00") * self.module.block_size

            # Test PyObject_CallObject code path: if the counter raises OverflowError
            cipher = self.module.new(a2b_hex(self.key), self.module.MODE_CTR, counter=pythonCounter())
            cipher.encrypt(block)
            self.assertRaises(OverflowError, cipher.encrypt, block)
            self.assertRaises(OverflowError, cipher.encrypt, block)

            # Test PyObject_CallObject code path: counter object should raise OverflowError
            ctr = Counter.new(8*self.module.block_size, initial_value=2L**(8*self.module.block_size)-1, little_endian=little_endian)
            ctr()
            self.assertRaises(OverflowError, ctr)
            self.assertRaises(OverflowError, ctr)

            # Test the CTR-mode shortcut
            ctr = Counter.new(8*self.module.block_size, initial_value=2L**(8*self.module.block_size)-1, little_endian=little_endian)
            cipher = self.module.new(a2b_hex(self.key), self.module.MODE_CTR, counter=ctr)
            cipher.encrypt(block)
            self.assertRaises(OverflowError, cipher.encrypt, block)
            self.assertRaises(OverflowError, cipher.encrypt, block)
Beispiel #3
0
def decrpy_msg(p_a, a_name, p_b, b_name):
    a = initialize(p_a)
    pg = get_pg()
    b = initialize(p_b)
    #print a, b
    #print pg
    s1 = send_key(p_a, a['token'], u'1', b_name)
    s2 = send_key(p_b, b['token'], u'1', a_name)
    print s1, s2
    k = recieve_msg(p_a, a['token'])
    #print k
    secret = 1
    k_hash = sha1(chr(1)).digest()
    k_a = k_hash[:16]
    k_a_nonce = k_hash[16:]
    while True:
        iv = hex_to_string(k['iv'])
        ctr = Counter.new(32, k_a_nonce+iv)
        key = AES.new(k_a, AES.MODE_CTR, 'x'*16, counter=ctr)
        print key.decrypt(hex_to_string(k['msg']))
        try:
            k = send_msg(p_b, b['token'], k['msg'], k['iv'])['reply']
        except:
            return
        #print k
        iv = hex_to_string(k['iv'])
        ctr = Counter.new(32, k_a_nonce+iv)
        key = AES.new(k_a, AES.MODE_CTR, 'x'*16, counter=ctr)
        print key.decrypt(hex_to_string(k['msg']))
        try:
            k = send_msg(p_a, a['token'], k['msg'], k['iv'])['reply']
        except:
            return
Beispiel #4
0
    def test_encryption(self, cipher_name, module, key_bytes, mode):
        self.announce_start("%s encryption" % (cipher_name,))

        # Generate random keys for use with the tests
        rand = self.random_data(key_bytes + module.block_size)
        key, iv = rand[:key_bytes], rand[key_bytes:]
        blocks = self.random_blocks(16384, 1000)
        if mode is None:
            cipher = module.new(key)
        elif mode == "CTR-BE":
            from Crypto.Util import Counter
            cipher = module.new(key, module.MODE_CTR, counter=Counter.new(module.block_size*8, little_endian=False))
        elif mode == "CTR-LE":
            from Crypto.Util import Counter
            cipher = module.new(key, module.MODE_CTR, counter=Counter.new(module.block_size*8, little_endian=True))
        elif hasattr(module, 'MODE_CCM') and mode==module.MODE_CCM:
            cipher = module.new(key, mode, iv[:8], msg_len=len(rand)*len(blocks))
        elif mode==module.MODE_CTR:
            ctr = Crypto.Util.Counter.new(module.block_size*8,
                    initial_value=bytes_to_long(iv),
                    allow_wraparound=True)
            cipher = module.new(key, module.MODE_CTR, counter=ctr)
        elif mode==module.MODE_ECB:
            cipher = module.new(key, module.MODE_ECB)
        else:
            cipher = module.new(key, mode, iv)

        # Perform encryption
        t0 = time.time()
        for b in blocks:
            cipher.encrypt(b)
        t = time.time()

        encryption_speed = (len(blocks) * len(blocks[0])) / (t - t0)
        self.announce_result(encryption_speed / 10**6, "MBps")
Beispiel #5
0
def final_decrpy_msg(p_a = Alice, a_name = 'alice'):
    a = initialize(p_a)
    pg = get_pg()
    #print a, b
    #print pg
    s1 = send_key(p_a, a['token'], u'1', 'eve')
    print s1
    secret = 1
    k = recieve_msg(p_a, a['token'])
    k_hash = sha1(chr(1)).digest()
    k_a = k_hash[:16]
    k_a_nonce = k_hash[16:]
    while True:
        iv = hex_to_string(k['iv'])
        ctr = Counter.new(32, k_a_nonce+iv)
        key = AES.new(k_a, AES.MODE_CTR, 'x'*16, counter=ctr)
        print key.decrypt(hex_to_string(k['msg']))

        ctr = Counter.new(32, k_a_nonce+iv)
        key = AES.new(k_a, AES.MODE_CTR, 'x'*16, counter=ctr)
        w =  string_to_hex(key.encrypt(the_hint))
##        return key, ctr, w
##        print key.decrypt(hex_to_string(w))
##        print key.decrypt(key.encrypt(the_hint))
        print w
        k = send_msg(p_a, a['token'], w, k['iv'])['reply']
        print k
Beispiel #6
0
    def test_encryption(self, cipher_name, module, key_bytes, mode):
        self.announce_start("%s encryption" % (cipher_name,))

        # Generate random keys for use with the tests
        rand = self.random_data(key_bytes + module.block_size)
        key, iv = rand[:key_bytes], rand[key_bytes:]
        blocks = self.random_blocks(16384, 1000)
        if mode is None:
            cipher = module.new(key)
        elif mode == "CTR-BE":
            from Crypto.Util import Counter

            cipher = module.new(key, module.MODE_CTR, counter=Counter.new(module.block_size * 8, little_endian=False))
        elif mode == "CTR-LE":
            from Crypto.Util import Counter

            cipher = module.new(key, module.MODE_CTR, counter=Counter.new(module.block_size * 8, little_endian=True))
        else:
            cipher = module.new(key, mode, iv)

        # Perform encryption
        t0 = time.time()
        for b in blocks:
            cipher.encrypt(b)
        t = time.time()

        encryption_speed = (len(blocks) * len(blocks[0])) / (t - t0)
        self.announce_result(encryption_speed / 10 ** 6, "MBps")
Beispiel #7
0
def test():
    # NIST Example Vector #1
    # Make sure my counter / encryption / decryption matches 
    # pycryptos (mostly)
    
    pt = unhexlify(b'6bc1bee22e409f96e93d7e117393172a')
    k = unhexlify(b'2b7e151628aed2a6abf7158809cf4f3c')
    exp = b'874d6191b620e3261bef6864990db6ce'
    exp2 = b'6bc1bee22e409f96e93d7e117393172a'
    
    ctrn = Counter.new(128, initial_value = int(b'f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff', 16))
    ctr = CTRCounter(bits = 128, init = int(b'f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff', 16), little_endian = False)

    cipher = AES.new(k, AES.MODE_CTR, counter=ctrn)
    
    a = hexlify(cipher.encrypt(pt))
    b = hexlify(ctr_encrypt(pt, k, ctr))
    
    assert a == b == exp
    
    ctrn = Counter.new(128, initial_value = int(b'f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff', 16))
    ctr2 = CTRCounter(bits = 128, init = int(b'f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff', 16), little_endian = False)
    
    cipher = AES.new(k, AES.MODE_CTR, counter=ctrn)
     
    c = hexlify(cipher.decrypt(unhexlify(a)))
    d = hexlify(ctr_decrypt(unhexlify(b), k, ctr2))
    
    assert c == d == exp2
Beispiel #8
0
    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)
Beispiel #9
0
	def __init__(self, fp, key):
		self.fp = fp
		self.key = key
		self.read_cipher = AES.new(self.key, AES.MODE_CTR, counter=Counter.new(128))
		self.write_cipher = AES.new(self.key, AES.MODE_CTR, counter=Counter.new(128))
		if hasattr(fp, "getvalue"):
			self.getvalue = self._getvalue
		if hasattr(fp, "seek"):
			self.seek = self._seek
Beispiel #10
0
 def test_BE_shortcut(self):
     """Big endian, shortcut enabled"""
     c = Counter.new(128)
     self.assertEqual(c.__PCT_CTR_SHORTCUT__,True) # assert_
     c = Counter.new(128, little_endian=False)
     self.assertEqual(c.__PCT_CTR_SHORTCUT__,True) # assert_
     c = Counter.new(128, disable_shortcut=False)
     self.assertEqual(c.__PCT_CTR_SHORTCUT__,True) # assert_
     c = Counter.new(128, little_endian=False, disable_shortcut=False)
     self.assertEqual(c.__PCT_CTR_SHORTCUT__,True) # assert_
Beispiel #11
0
    def __init__(self, key):
        """ Initialize AES with the given key and two counters, one for encryption and one for decryption. """

        counterIn = Counter.new(128)
        self.cipherIn = AES.new(key, mode=AES.MODE_CTR,
                                counter=counterIn)

        counterOut = Counter.new(128)
        self.cipherOut = AES.new(key, mode=AES.MODE_CTR,
                                 counter=counterOut)
Beispiel #12
0
	def _seek(self, offset, from_what=0):
		res = self.fp.seek(offset, from_what)
		loc = self.fp.tell()
		read_ctr = Counter.new(128, initial_value=loc/16+1)
		write_ctr = Counter.new(128, initial_value=loc/16+1)
		self.read_cipher = AES.new(self.key, AES.MODE_CTR, counter=read_ctr)
		self.write_cipher = AES.new(self.key, AES.MODE_CTR, counter=write_ctr)
		self.read_cipher.encrypt("0"*(loc%16))
		self.write_cipher.encrypt("0"*(loc*16))
		return res
Beispiel #13
0
	def before_uupdate(self, uuid, f):
		if uuid[-4:] == ".dir":
			return uuid, f
		if hasattr(f, "read"):
			return uuid, AESWrapper(f, self.key)
		elif not isinstance(f, basestring):
			cipher = AES.new(self.key, AES.MODE_CTR, counter=Counter.new(128))
			return uuid, cipher.encrypt(json.dumps(f))
		else:
			cipher = AES.new(self.key, AES.MODE_CTR, counter=Counter.new(128))
			return uuid, cipher.encrypt(f)
Beispiel #14
0
def example_ctr():
    key = 'This is a key123'.encode()
    iv = 'This is an IV456'.encode()
    ctr = Counter.new(128)
    obj = AES.new(key, AES.MODE_CTR, iv, ctr)
    message = "The answer is no".encode()
    ciphertext = obj.encrypt(message)
    print(ciphertext)

    ctr = Counter.new(128)
    obj = AES.new(key, AES.MODE_CTR, iv, ctr)
    print(obj.decrypt(ciphertext))
Beispiel #15
0
 def startEncryption(self, enckey, deckey):
     self.logger.debug('Instantiating symmetric ciphers...')
     self.enckey = enckey
     self.deckey = deckey
     # encryption
     encctro = Counter.new(64, suffix=self.counter_suffix)
     self.enccipher = AES.new(enckey, AES.MODE_CTR, counter=encctro)
     # decryption
     decctro = Counter.new(64, suffix=self.counter_suffix)
     self.deccipher = AES.new(deckey, AES.MODE_CTR, counter=decctro)
     # counters
     self.encctr = 1
     self.decctr = 1
Beispiel #16
0
    def _start_gcm(self, factory, key, *args, **kwargs):

        if self.block_size != 16:
            raise TypeError("GCM mode is only available for ciphers that operate on 128 bits blocks")

        self.nonce = _getParameter('nonce', 1, args, kwargs)
        if not self.nonce:
            raise TypeError("MODE_GCM requires a nonce")

        self._mac_len = kwargs.get('mac_len', 16)
        if not (self._mac_len and 4 <= self._mac_len <= 16):
            raise ValueError("Parameter 'mac_len' must not be larger than 16 bytes")

        # Allowed transitions after initialization
        self._next = [self.update, self.encrypt, self.decrypt,
                      self.digest, self.verify]

        self._done_assoc_data = False

        # Length of the ciphertext or plaintext
        self._msg_len = 0

        # Step 1 in SP800-38D, Algorithm 4 (encryption) - Compute H
        # See also Algorithm 5 (decryption)
        hash_subkey = factory.new(key).encrypt(bchr(0) * 16)

        # Step 2 - Compute J0 (integer, not byte string!)
        if len(self.nonce) == 12:
            self._j0 = bytes_to_long(self.nonce + b("\x00\x00\x00\x01"))
        else:
            fill = (16 - (len(self.nonce) % 16)) % 16 + 8
            ghash_in = (self.nonce +
                        bchr(0) * fill +
                        long_to_bytes(8 * len(self.nonce), 8))

            mac = _GHASH(hash_subkey, factory.block_size, '0K')
            mac.update(ghash_in)
            self._j0 = bytes_to_long(mac.digest())

        # Step 3 - Prepare GCTR cipher for encryption/decryption
        ctr = Counter.new(128, initial_value=self._j0 + 1,
                          allow_wraparound=True)
        self._cipher = self._factory.new(key, MODE_CTR, counter=ctr)

        # Step 5 - Bootstrat GHASH
        self._cipherMAC = _GHASH(hash_subkey, factory.block_size, '64K')

        # Step 6 - Prepare GCTR cipher for GMAC
        ctr = Counter.new(128, initial_value=self._j0, allow_wraparound=True)
        self._tag_cipher = self._factory.new(key, MODE_CTR, counter=ctr)
Beispiel #17
0
    def test_decrypt_ctr(self):
        ctr_key = '36f18357be4dbd77f050515c73fcf9f2'.decode("hex")
        blob = "69dda8455c7dd4254bf353b773304eec0ec7702330098ce7f7520d1cbbb20fc388d1b0adb5054dbd7370849dbf0b88d393f252e764f1f5f7ad97ef79d59ce29f5f51eeca32eabedd9afa9329".decode("hex")

        iv = blob[0:16]
        ciphertext = blob[16:]

        ctr = Counter.new(128, initial_value=long(iv.encode('hex'), 16))
        obj = AES.new(ctr_key, AES.MODE_CTR, counter=ctr)

        text_aes_ctr = obj.decrypt(ciphertext)

        ctr = Counter.new(128, initial_value=long(iv.encode('hex'), 16))
        my_decrypt = ctr_d(ciphertext, ctr_key, ctr)
        self.assertEquals(text_aes_ctr, my_decrypt)
Beispiel #18
0
def decrypt(secret, message):
    message = message.encode('utf-8')
    curve = SECP256k1.curve()
    order = SECP256k1.order()
    R_size = 1 + 32
    mac_size = hashlib.sha256().digest_size

    message_binary = base64.b64decode(message)
    if len(message_binary) < (R_size + mac_size):
        return None

    R = decode_point(message_binary)
    d = message_binary[R_size:R_size + mac_size]
    prefix_bytes = message_binary[R_size + mac_size:R_size + mac_size + 8]
    c = message_binary[R_size + mac_size + 8:]
    S = (secret * R).x()
    S_bytes = S.to_bytes(32, 'big')
    k_E = hashlib.sha256(S_bytes + b'\0\0\0\1').digest()
    k_M = hashlib.sha256(S_bytes + b'\0\0\0\2').digest()
    d_verify = hmac.new(k_M, prefix_bytes + c, hashlib.sha256).digest()
    if d_verify != d:
        return None
    ctr = Counter.new(64, prefix=prefix_bytes)
    cipher = AES.new(key=k_E, mode=AES.MODE_CTR, counter=ctr)
    padded = cipher.decrypt(c)
    try:
        return unpad(padded, AES.block_size).decode('utf-8')
    except:
        return None
def write_logfile(log_filename, auth_token, logfile_pt):
    
    # Compress the plaintext log file
    logfile_pt = zlib.compress(logfile_pt, 5)
    
    # Generate the encryption and hmac keys from the token
    encrypt_key, hmac_key = generate_keys(auth_token)
    
    # Set-up the counter for AES CTR-mode cipher
    ctr_iv = urandom(16)
    ctr = Counter.new(128, initial_value=long(ctr_iv.encode('hex'),16)) # AES is 128 bits (16 bytes)
    logfile_ct = ctr_iv.encode('hex')
    
    # Create the cipher object
    cipher = AES.new(encrypt_key.decode('hex'), AES.MODE_CTR, counter=ctr)
    
    # Encrypt the plain text log and add it to the logfile cipher text
    # which currently contains the IV for AES CTR mode
    logfile_ct = logfile_ct + cipher.encrypt(logfile_pt)
    
    # Use the 2nd half of the hashed token to sign the cipher text
    # version of the logfile using a MAC (message authentication code)
    hmac_obj = HMAC.new(hmac_key.decode('hex'), logfile_ct)
    mac = hmac_obj.hexdigest()
    
    # Add the mac to the encrypted log file
    logfile_ct = logfile_ct + mac
    
    # Write the signed and encrypted log file to disk.
    # The caller should handle an IO exception
    with open(log_filename, 'wb') as f:
        f.write(logfile_ct)
    
    return None
Beispiel #20
0
    def decrypt(self, data, password):

        # SPLIT SALT, DIGEST, AND DATA
        data = ''.join(data.split("\n"))
        data = unhexlify(data)
        salt, cryptedHmac, cryptedData = data.split("\n", 2)
        salt = unhexlify(salt)
        cryptedData = unhexlify(cryptedData)

        key1, key2, iv = self.gen_key_initctr(password, salt)

        # EXIT EARLY IF DIGEST DOESN'T MATCH 
        hmacDecrypt = HMAC.new(key2, cryptedData, SHA256)
        if not self.is_equal(cryptedHmac, hmacDecrypt.hexdigest()):
            return None

        # SET THE COUNTER AND THE CIPHER
        ctr = Counter.new(128, initial_value=long(iv, 16))
        cipher = AES.new(key1, AES.MODE_CTR, counter=ctr)

        # DECRYPT PADDED DATA
        decryptedData = cipher.decrypt(cryptedData)

        # UNPAD DATA
        padding_length = ord(decryptedData[-1])
        decryptedData = decryptedData[:-padding_length]

        return decryptedData
Beispiel #21
0
 def __initSecureChannel(self):
     
     """
     keys are generated for the four possible encryption/decryption situations
     if the user is a server (conn_type != client), then they are ordered slightly differently
     """
     enc_send_key, enc_recv_key, self.__auth_send_hmac, self.__auth_recv_hmac = [
         SHA256.new(str(self.__shared_key) + uniq_text).digest()
         for uniq_text in (["a send b", "b send a", "a auth b", "b auth a"] if self._role == self.CLIENT else ["b send a", "a send b", "b auth a", "a auth b"])
     ]
     
     #in the case of send/recv encryption, we only need one cipher, rather than making a new one each time.
     self.__encrypt_cipher = AES.new(enc_send_key, AES.MODE_CTR, counter=Counter.new(128))
     self.__decrypt_cipher = AES.new(enc_recv_key, AES.MODE_CTR, counter=Counter.new(128))
     
     return 0
Beispiel #22
0
    def __init__(self, stash_key, manager_provider, aws_profile=None, aws_region=None, aws_bucket=None):
        check_latest_version()

        self._aws_manager = manager_provider.aws_manager(aws_profile, aws_region or 'us-east-1')

        if aws_bucket is None:
            deployment_bucket_name = 'novastash_%s' % self._aws_manager.account_alias
        else:
            deployment_bucket_name = aws_bucket

        key = "%s.txt.enc" % stash_key
        existing_stash = self._aws_manager.s3_get(deployment_bucket_name, key)

        if existing_stash is None:
            raise NovaError("No stash '%s' found!" % stash_key)
        else:
            contents = existing_stash['Body'].read()
            metadata = existing_stash['Metadata']
            encryption_key = metadata['encryption-key']
            kms_response = self._aws_manager.kms_decrypt(b64decode(encryption_key), {})

            key = kms_response['Plaintext'][:32]
            hmac_key = kms_response['Plaintext'][32:]
            hmac = HMAC(hmac_key, msg=b64decode(contents), digestmod=SHA256)

            if hmac.hexdigest() != metadata['hmac']:
                raise NovaError("Computed HMAC on '%s' does not match stored HMAC" % stash_key)

            dec_ctr = Counter.new(128)
            decryptor = AES.new(key, AES.MODE_CTR, counter=dec_ctr)
            print(decryptor.decrypt(b64decode(contents)).decode("utf-8"))
Beispiel #23
0
    def encrypt(self, data, password):

        salt = os.urandom(32)
        key1, key2, iv = self.gen_key_initctr(password, salt)

        # PKCS#7 PAD DATA http://tools.ietf.org/html/rfc5652#section-6.3
        bs = AES.block_size
        padding_length = (bs - len(data) % bs) or bs
        data += padding_length * chr(padding_length)

        # 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=long(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(key1, AES.MODE_CTR, counter=ctr)

        # ENCRYPT PADDED DATA
        cryptedData = cipher.encrypt(data)                

        # COMBINE SALT, DIGEST AND DATA
        hmac = HMAC.new(key2, cryptedData, SHA256)
        message = "%s\n%s\n%s" % ( hexlify(salt), hmac.hexdigest(), hexlify(cryptedData) )
        message = hexlify(message)
        return message
def decrypt(password, data, expansion_count=EXPANSION_COUNT):
    '''
    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)
    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])
Beispiel #25
0
    def initiate_session(self):
        # Perform the initial connection handshake for agreeing on a shared secret

        ### TODO: Your code here!
        # This can be broken into code run just on the server or just on the client
        if self.server or self.client:
            my_public_key, my_private_key = create_dh_key()
            # Send them our public key
            self.send(bytes(str(my_public_key), "ascii"))
            # Receive their public key
            their_public_key = int(self.recv())
            # Obtain our shared secret
            self.key = calculate_dh_secret(their_public_key, my_private_key)
            print("Shared hash: {}".format(self.key))

        # Create a counter from PyCrypto library. Has 128 bits and uses a randomly generated initial value
        counter = Counter.new(128)

        # Creating AES cipher with 16 bit key, counter mode and counter initialised in previous line
        self.cipher = AES.new(self.key[:16], AES.MODE_CTR, counter=counter) # Changes from XOR to AES

        self.send_seed = read_hex(self.key[:4])
        self.recv_seed = self.send_seed
        print("Send seed: {}".format(self.send_seed))
        print("Recv seed: {}".format(self.recv_seed))
Beispiel #26
0
 def _encode_impersonate_v1(self, ptxt, pubkey, privkey, progress_callback=None, 
            ttl=_default_ttl):
     if ptxt is None or len(ptxt) == 0:
         return False
     tval = int(time.time())
     texp = tval + ttl
     q = privkey.current_privkey_val(tval)
     if q is None:
         return False
     Q = privkey.current_pubkey_point(tval)
     P = pubkey.current_pubkey_point(tval)
     if P is None:
         return False
     status = {}
     status['besthash'] = 0
     status['bestbits'] = _masksize
     status['nhash'] = 0
     status['nhash2'] = 0
     while True:
         s = random.randint(2, _C['n']-1)
         I = _G * s
         maskval = ((I.affine()[0] >> (_C['bits'] - _masksize)) &
                    privkey.addr['mask'])
         maskmiss = bin(maskval ^ privkey.addr['mtgt']).count('1')
         if maskmiss < status['bestbits']:
             status['bestbits'] = maskmiss
             status['besthash'] = maskval
         if maskval == privkey.addr['mtgt']:
             break
         if progress_callback:
             if (status['nhash'] % 10) == 0:
                 progress_callback(status)
         status['nhash'] += 1
     J = Q * s
     stext = (_pfmt % s).encode()
     h = int(sha256(stext + ptxt.encode()).hexdigest(), 16)
     k = (q * h) % _C['n']
     K = P * h
     DH = P * k
     iv = int(I.compress()[-32:],16)
     keybin = unhexlify(DH.compress()[-64:])
     counter = Counter.new(128,initial_value=iv)
     cryptor = AES.new(keybin, AES.MODE_CTR, counter=counter)
     msg = (_pfmt % s).encode() + b':' + b64encode(ptxt.encode())
     ctxt = cryptor.encrypt(msg)
     altK = Q * h
     self.time = tval
     self.expire = texp
     self.s = s
     self.I = I
     self.J = J
     self.K = K
     self.ptxt = ptxt
     self.ctxt = ctxt
     self.altK = altK
     self.version = "0100"
     header = self._short_header()
     sigkey = int(sha256(DH.compress()).hexdigest(), 16) % _C['n']
     self.sig = _ecdsa.sign(sigkey, ctxt, header)
     return self
Beispiel #27
0
 def _decode_v1(self,DH):
     sp = int(sha256(DH.compress()).hexdigest(), 16) % _C['n']
     SP = _G * sp
     if not _ecdsa.verify(SP, self.sig, self.ctxt, self._short_header()):
         return False
     iv = int(self.I.compress()[-32:],16)
     keybin = unhexlify(DH.compress()[-64:])
     counter = Counter.new(128,initial_value=iv)
     cryptor = AES.new(keybin, AES.MODE_CTR, counter=counter)
     etxt = cryptor.decrypt(self.ctxt)
     msg = etxt.split(b':')
     if len(msg) != 2:
         return False
     if len(msg[0]) != 64:
         return False
     s = 0
     try:
         s = int(msg[0],16)
     except ValueError:
         return False
     if self.I != (_G * s):
         return False
     try:
         self.ptxt = b64decode(msg[1])
     except:
         return False
     self.ptxt = self.ptxt.decode()
     self.s = s
     stext = (_pfmt % s).encode()
     self.h = int(sha256(stext + self.ptxt.encode()).hexdigest(), 16)
     return True
Beispiel #28
0
def decryptCTR(in_file="/tmp/indice6.html", out_file=None, 
               password="******"+time.strftime("%Y-%m-%d"), key_length=32,
               base64=True,padding=False):
    if (base64):
        tmpFile=tempfile.mktemp()
        deBase64(in_file,tmpFile)
        in_file=tmpFile
    in_file=open(in_file,"rb")
    if (out_file==None):
        out_file=sys.stdout
    else:
        out_file=open(out_file,"w")
    bs = AES.block_size
    salt = in_file.read(bs)[len('Salted__'):]
    key, iv = derive_key_and_iv(password, salt, key_length, bs)
    #print "key: "+key.encode("hex")
    #print "iv: "+iv.encode("hex")
    #sys.exit(0)
    ctr=Counter.new(bs*8,initial_value=long(iv.encode("hex"),16))
    cipher = AES.new(key, AES.MODE_CTR, counter = ctr)
    next_chunk = ''
    finished = False
    while not finished:
        chunk, next_chunk = next_chunk, cipher.decrypt(in_file.read(1 * bs))
        if len(next_chunk) == 0:
            if (padding):
                padding_length = ord(chunk[-1])
                chunk = chunk[:-padding_length]
            finished = True
        out_file.write(chunk)
    in_file.close()
    if (out_file!=sys.stdout):
       out_file.close()
Beispiel #29
0
    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
Beispiel #30
0
    def __init__(self, factory, **kwargs):
        """Create a new block cipher, configured in
        Galois Counter Mode (GCM).

        :Parameters:
          factory : module
            A block cipher module, taken from `Crypto.Cipher`.
            The cipher must have block length of 16 bytes.
            GCM has been only defined for `Crypto.Cipher.AES`.

        :Keywords:
          key : byte string
            The secret key to use in the symmetric cipher.
            It must be 16 (e.g. *AES-128*), 24 (e.g. *AES-192*)
            or 32 (e.g. *AES-256*) bytes long.

          nonce : byte string
            A mandatory value that must never be reused for any other encryption.

            There are no restrictions on its length,
            but it is recommended to use at least 16 bytes.

            The nonce shall never repeat for two
            different messages encrypted with the same key,
            but it does not need to be random.

          mac_len : integer
            Length of the MAC, in bytes.
            It must be no larger than 16 bytes (which is the default).
        """

        self.block_size = factory.block_size
        if self.block_size != 16:
            raise ValueError("GCM mode is only available for ciphers"
                             " that operate on 128 bits blocks")

        self._factory = factory
        try:
            self._key = key = kwargs.pop("key")
            nonce = kwargs.pop("nonce")
        except KeyError as e:
            raise TypeError("Missing parameter:" + str(e))
        self._mac_len = kwargs.pop("mac_len", 16)

        self._tag = None  ## Cache for MAC tag

        # MAC tag length
        if not (4 <= self._mac_len <= 16):
            raise ValueError("Parameter 'mac_len' must not be larger"
                             " than 16 bytes")

        # Allowed transitions after initialization
        self._next = [self.update, self.encrypt, self.decrypt,
                      self.digest, self.verify]

        self._no_more_assoc_data = False

        # Length of the ciphertext or plaintext
        self._msg_len = 0

        # Step 1 in SP800-38D, Algorithm 4 (encryption) - Compute H
        # See also Algorithm 5 (decryption)
        hash_subkey = factory.new(key,
                                  self._factory.MODE_ECB,
                                  **kwargs
                                  ).encrypt(bchr(0) * 16)

        # Step 2 - Compute J0 (integer, not byte string!)
        if len(nonce) == 12:
            self._j0 = bytes_to_long(nonce + b("\x00\x00\x00\x01"))
        else:
            fill = (16 - (len(nonce) % 16)) % 16 + 8
            ghash_in = (nonce +
                        bchr(0) * fill +
                        long_to_bytes(8 * len(nonce), 8))
            mac = _GHASH(hash_subkey, factory.block_size)
            mac.update(ghash_in)
            self._j0 = bytes_to_long(mac.digest())
            del mac

        # Step 3 - Prepare GCTR cipher for encryption/decryption
        ctr = Counter.new(128, initial_value=self._j0 + 1)
        self._cipher = factory.new(key,
                                   self._factory.MODE_CTR,
                                   counter=ctr,
                                   **kwargs)

        # Step 5 - Bootstrat GHASH
        self._signer = _GHASH(hash_subkey, factory.block_size)

        # Step 6 - Prepare GCTR cipher for GMAC
        ctr = Counter.new(128, initial_value=self._j0)
        self._tag_cipher = factory.new(key,
                                       self._factory.MODE_CTR,
                                       counter=ctr,
                                       **kwargs)
Beispiel #31
0
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)
Beispiel #32
0
 def initialize_cipher(self):
     self.ctr_e = Counter.new(self.AES_block_size, initial_value=self.iv)
     self.ctr_d = Counter.new(self.AES_block_size, initial_value=self.iv)
     self.encryptor = AES.new(self.key, AES.MODE_CTR, counter=self.ctr_e)
     self.decryptor = AES.new(self.key, AES.MODE_CTR, counter=self.ctr_d)
Beispiel #33
0
class CtrTests(unittest.TestCase):

    key_128 = get_tag_random("key_128", 16)
    key_192 = get_tag_random("key_192", 24)
    nonce_32 = get_tag_random("nonce_32", 4)
    nonce_64 = get_tag_random("nonce_64", 8)
    ctr_64 = Counter.new(32, prefix=nonce_32)
    ctr_128 = Counter.new(64, prefix=nonce_64)

    def test_loopback_128(self):
        cipher = AES.new(self.key_128, AES.MODE_CTR, counter=self.ctr_128)
        pt = get_tag_random("plaintext", 16 * 100)
        ct = cipher.encrypt(pt)

        cipher = AES.new(self.key_128, AES.MODE_CTR, counter=self.ctr_128)
        pt2 = cipher.decrypt(ct)
        self.assertEqual(pt, pt2)

    def test_loopback_64(self):
        cipher = DES3.new(self.key_192, DES3.MODE_CTR, counter=self.ctr_64)
        pt = get_tag_random("plaintext", 8 * 100)
        ct = cipher.encrypt(pt)

        cipher = DES3.new(self.key_192, DES3.MODE_CTR, counter=self.ctr_64)
        pt2 = cipher.decrypt(ct)
        self.assertEqual(pt, pt2)

    def test_invalid_counter_parameter(self):
        # Counter object is required for ciphers with short block size
        self.assertRaises(TypeError, DES3.new, self.key_192, AES.MODE_CTR)
        # Positional arguments are not allowed (Counter must be passed as
        # keyword)
        self.assertRaises(TypeError, AES.new, self.key_128, AES.MODE_CTR,
                          self.ctr_128)

    def test_nonce_attribute(self):
        # Nonce attribute is the prefix passed to Counter (DES3)
        cipher = DES3.new(self.key_192, DES3.MODE_CTR, counter=self.ctr_64)
        self.assertEqual(cipher.nonce, self.nonce_32)

        # Nonce attribute is the prefix passed to Counter (AES)
        cipher = AES.new(self.key_128, AES.MODE_CTR, counter=self.ctr_128)
        self.assertEqual(cipher.nonce, self.nonce_64)

        # Nonce attribute is not defined if suffix is used in Counter
        counter = Counter.new(64, prefix=self.nonce_32, suffix=self.nonce_32)
        cipher = AES.new(self.key_128, AES.MODE_CTR, counter=counter)
        self.assertFalse(hasattr(cipher, "nonce"))

    def test_nonce_parameter(self):
        # Nonce parameter becomes nonce attribute
        cipher1 = AES.new(self.key_128, AES.MODE_CTR, nonce=self.nonce_64)
        self.assertEqual(cipher1.nonce, self.nonce_64)

        counter = Counter.new(64, prefix=self.nonce_64, initial_value=0)
        cipher2 = AES.new(self.key_128, AES.MODE_CTR, counter=counter)
        self.assertEqual(cipher1.nonce, cipher2.nonce)

        pt = get_tag_random("plaintext", 65536)
        self.assertEqual(cipher1.encrypt(pt), cipher2.encrypt(pt))

        # Nonce is implicitly created (for AES) when no parameters are passed
        nonce1 = AES.new(self.key_128, AES.MODE_CTR).nonce
        nonce2 = AES.new(self.key_128, AES.MODE_CTR).nonce
        self.assertNotEqual(nonce1, nonce2)
        self.assertEqual(len(nonce1), 8)

        # Nonce can be zero-length
        cipher = AES.new(self.key_128, AES.MODE_CTR, nonce=b(""))
        self.assertEqual(b(""), cipher.nonce)

        # Nonce and Counter are mutually exclusive
        self.assertRaises(TypeError,
                          AES.new,
                          self.key_128,
                          AES.MODE_CTR,
                          counter=self.ctr_128,
                          nonce=self.nonce_64)

    def test_initial_value_parameter(self):
        # Test with nonce parameter
        cipher1 = AES.new(self.key_128,
                          AES.MODE_CTR,
                          nonce=self.nonce_64,
                          initial_value=0xFFFF)
        counter = Counter.new(64, prefix=self.nonce_64, initial_value=0xFFFF)
        cipher2 = AES.new(self.key_128, AES.MODE_CTR, counter=counter)
        pt = get_tag_random("plaintext", 65536)
        self.assertEqual(cipher1.encrypt(pt), cipher2.encrypt(pt))

        # Test without nonce parameter
        cipher1 = AES.new(self.key_128, AES.MODE_CTR, initial_value=0xFFFF)
        counter = Counter.new(64, prefix=cipher1.nonce, initial_value=0xFFFF)
        cipher2 = AES.new(self.key_128, AES.MODE_CTR, counter=counter)
        pt = get_tag_random("plaintext", 65536)
        self.assertEqual(cipher1.encrypt(pt), cipher2.encrypt(pt))

        # Initial_value and Counter are mutually exclusive
        self.assertRaises(TypeError,
                          AES.new,
                          self.key_128,
                          AES.MODE_CTR,
                          counter=self.ctr_128,
                          initial_value=0)

    def test_iv_with_matching_length(self):
        self.assertRaises(ValueError,
                          AES.new,
                          self.key_128,
                          AES.MODE_CTR,
                          counter=Counter.new(120))
        self.assertRaises(ValueError,
                          AES.new,
                          self.key_128,
                          AES.MODE_CTR,
                          counter=Counter.new(136))

    def test_block_size_128(self):
        cipher = AES.new(self.key_128, AES.MODE_CTR, counter=self.ctr_128)
        self.assertEqual(cipher.block_size, AES.block_size)

    def test_block_size_64(self):
        cipher = DES3.new(self.key_192, DES3.MODE_CTR, counter=self.ctr_64)
        self.assertEqual(cipher.block_size, DES3.block_size)

    def test_unaligned_data_128(self):
        plaintexts = [b("7777777")] * 100

        cipher = AES.new(self.key_128, AES.MODE_CTR, counter=self.ctr_128)
        ciphertexts = [cipher.encrypt(x) for x in plaintexts]
        cipher = AES.new(self.key_128, AES.MODE_CTR, counter=self.ctr_128)
        self.assertEqual(
            b("").join(ciphertexts), cipher.encrypt(b("").join(plaintexts)))

        cipher = AES.new(self.key_128, AES.MODE_CTR, counter=self.ctr_128)
        ciphertexts = [cipher.encrypt(x) for x in plaintexts]
        cipher = AES.new(self.key_128, AES.MODE_CTR, counter=self.ctr_128)
        self.assertEqual(
            b("").join(ciphertexts), cipher.encrypt(b("").join(plaintexts)))

    def test_unaligned_data_64(self):
        plaintexts = [b("7777777")] * 100
        cipher = DES3.new(self.key_192, AES.MODE_CTR, counter=self.ctr_64)
        ciphertexts = [cipher.encrypt(x) for x in plaintexts]
        cipher = DES3.new(self.key_192, AES.MODE_CTR, counter=self.ctr_64)
        self.assertEqual(
            b("").join(ciphertexts), cipher.encrypt(b("").join(plaintexts)))

        cipher = DES3.new(self.key_192, AES.MODE_CTR, counter=self.ctr_64)
        ciphertexts = [cipher.encrypt(x) for x in plaintexts]
        cipher = DES3.new(self.key_192, AES.MODE_CTR, counter=self.ctr_64)
        self.assertEqual(
            b("").join(ciphertexts), cipher.encrypt(b("").join(plaintexts)))

    def test_unknown_parameters(self):
        self.assertRaises(TypeError,
                          AES.new,
                          self.key_128,
                          AES.MODE_CTR,
                          7,
                          counter=self.ctr_128)
        self.assertRaises(TypeError,
                          AES.new,
                          self.key_128,
                          AES.MODE_CTR,
                          counter=self.ctr_128,
                          unknown=7)
        # But some are only known by the base cipher (e.g. use_aesni consumed by the AES module)
        AES.new(self.key_128,
                AES.MODE_CTR,
                counter=self.ctr_128,
                use_aesni=False)

    def test_null_encryption_decryption(self):
        for func in "encrypt", "decrypt":
            cipher = AES.new(self.key_128, AES.MODE_CTR, counter=self.ctr_128)
            result = getattr(cipher, func)(b(""))
            self.assertEqual(result, b(""))

    def test_either_encrypt_or_decrypt(self):
        cipher = AES.new(self.key_128, AES.MODE_CTR, counter=self.ctr_128)
        cipher.encrypt(b(""))
        self.assertRaises(TypeError, cipher.decrypt, b(""))

        cipher = AES.new(self.key_128, AES.MODE_CTR, counter=self.ctr_128)
        cipher.decrypt(b(""))
        self.assertRaises(TypeError, cipher.encrypt, b(""))

    def test_wrap_around(self):
        counter = Counter.new(8, prefix=bchr(9) * 15)

        cipher = AES.new(self.key_128, AES.MODE_CTR, counter=counter)
        cipher.encrypt(bchr(9) * 16 * 255)
        self.assertRaises(OverflowError, cipher.encrypt, bchr(9) * 16)

        cipher = AES.new(self.key_128, AES.MODE_CTR, counter=counter)
        cipher.decrypt(bchr(9) * 16 * 255)
        self.assertRaises(OverflowError, cipher.decrypt, bchr(9) * 16)
Beispiel #34
0
import zlib
import os
import sys

from Crypto.Cipher import AES
from Crypto.Util import Counter

ENCRYPT_KEY = bytes.fromhex(
    '0000000000000000000000000000000000000000000000000000000000000000')
# Determine this key.
# Character set: lowercase letters and underscore
PROBLEM_KEY = 'not_the_flag'


def encrypt(data, ctr):
    return AES.new(ENCRYPT_KEY, AES.MODE_CTR,
                   counter=ctr).encrypt(zlib.compress(data))


while True:
    f = input("Encrypting service\n")
    if len(f) < 20:
        continue
    enc = encrypt(bytes((PROBLEM_KEY + f).encode('utf-8')),
                  Counter.new(64, prefix=os.urandom(8)))
    print("%s%d" % (enc, len(enc)))
Beispiel #35
0
def de_AES_CTR(key, encrypted):
    ctr = Counter.new(128)
    cipher = AES.new(key, AES.MODE_CTR, counter=ctr)
    decrypted = cipher.decrypt(encrypted)
    decrypted = decrypted[:len(decrypted) -
                          int(decrypted[-1].encode('hex'), 16)]
Beispiel #36
0
try:
    opts, args = getopt.getopt(sys.argv[1:],'hi:')
except getopt.GetoptError:
    print("Usage: eke_bob_2.py -i <input_msg_file>")
    sys.exit(2)

input_msg_file = 'eke_msg_3.txt'

for opt, arg in opts:
    if opt == '-h':
        print("Usage: eke_bob_2.py -i <input_msg_file>")
        sys.exit()
    elif opt == '-i':
        if len(arg) != 0: input_msg_file = arg

f = open("sessionkey.txt", "rb")
session_key = b64decode(f.readline())
f.close()

f = open(input_msg_file, 'rb')
nonce = b64decode(f.readline())
enc_msg = b64decode(f.readline())
f.close()

ctr = Counter.new(64, prefix=nonce, initial_value=0)
aes_cipher = AES.new(session_key, AES.MODE_CTR, counter=ctr)

msg = aes_cipher.decrypt(enc_msg)
print(msg.decode('utf-8'))

Beispiel #37
0
		for j in range(i, len(cipher), sz):
			part.append(cipher[j])
		res, _, k = solveSingleXor(bytes(part))
		key.append(k)
		idx = i
		for j in res:
			ans[idx] = j
			idx += sz
	return (bytes(ans), bytes(key))

def sxor(a, b):
	return bytes([a[i] ^ b[i] for i in range(len(b))])

def solve(ls):
	l = min([len(s) for s in ls])
	ciphertext = b"".join([s[:l] for s in ls])

	_, key = solveVignere(ciphertext, l)
	for s in ls:
		print(sxor(s, key))


inputString = open("text.txt", "r").read().split('\n')
key = os.urandom(16)
nonce = os.urandom(8)
ls = []
for s in inputString:
	cipher = AES.new(key, AES.MODE_CTR, counter=Counter.new(64, prefix=nonce))
	ls.append(cipher.encrypt(base64.b64decode(s)))

solve(ls)
Beispiel #38
0
def decrypt_file_key(ct, book_key):
    ctr = Counter.new(128, initial_value=int(bytes(book_key[16:]).hex(),16))
    cipher = AES.new(bytes(book_key[:16]), AES.MODE_CTR, counter=ctr)
    return list(cipher.decrypt(ct))
Beispiel #39
0
def send(senderID, payload, groupkey, password):

    nonce = Random.get_random_bytes(8)
    # create a counter object and set the nonce as its prefix and set the initial counter value to 0
    ctr = Counter.new(64, prefix=nonce, initial_value=0)

    # create an AES-CTR cipher object and encrypt the header + payload
    ENC = AES.new(groupkey, AES.MODE_CTR, counter=ctr)
    payload = payload.encode('utf-8')
    encrypted = ENC.encrypt(payload)

    # create a SHA256 hash object and hash the encrypted content
    h = SHA256.new()
    h.update(encrypted)

    # RSA PKCS1 PSS SIGNATURE
    sigkfile = open("setup/%s-key.pem" % senderID, 'r')
    sigkeystr = sigkfile.read()
    sigkfile.close()
    sigkey = RSA.import_key(sigkeystr, passphrase=password)
    signer = PKCS1_PSS.new(sigkey)

    # sign the hash
    signature = signer.sign(h)

    #update sndsqn in the sndstate file
    fileName = 'setup/sndstate' + senderID + '.txt'
    ofile = open(fileName, 'r')
    temp = ofile.readline()
    sndsqn = int(temp.split('sndsqn: ')[1])
    #print(sndsqn)
    ofile.close()
    ofile = open(fileName, 'w')
    ofile.write('sndsqn: ' + str(sndsqn + 1))
    ofile.close()

    # compute payload_length + sig_length
    payload_length = len(encrypted)
    sig_length = 128

    # compute message length...
    # header:
    #    sender: 1 byte
    #    length: 3 btyes
    #    sqn:    4 bytes
    # nonce: 8 bytes
    # payload: payload_length
    # signature: sig_length
    msg_length = 8 + len(nonce) + payload_length + sig_length

    # create header
    header_sender = senderID.encode('utf-8')  # message sender
    header_length = str(msg_length).encode(
        'utf-8')  # message length (encoded on 3 bytes)
    header_sqn = (sndsqn + 1).to_bytes(
        4,
        byteorder='big')  # next message sequence number (encoded on 4 bytes)
    header = header_sender + header_length + header_sqn

    return (header + nonce + encrypted + signature)
    '''
Beispiel #40
0
    start = timer()
    decrypt(enc_files[i], verification_files[i])
    end = timer()
    capture_time.append(end - start)

plt.plot(capture_time[:2], label='1 MB file AES 128 CBC')
plt.plot(capture_time[2:4], label='1 KB file AES 128 CBC')

from Crypto.Cipher import AES
from Crypto.Util import Counter
from Crypto import Random
import matplotlib.pyplot as plt
from timeit import default_timer as timer

nonce = Random.get_random_bytes(8)
count = Counter.new(64, nonce)
key = Random.get_random_bytes(16)


def encrypt(input_file, enc_file):
    encrypt = AES.new(key, AES.MODE_CTR, counter=count)
    with open(enc_file, 'wb') as fout:
        with open(input_file, 'rb') as fin:
            data = fin.read()
            encrypted = encrypt.encrypt(data)
            fout.write(encrypted)


def decrypt(enc_file, verification_file):
    count = Counter.new(64, nonce)
    decrypt = AES.new(key, AES.MODE_CTR, counter=count)
Beispiel #41
0
 def create_aes_ctr(key, iv):
     ctr = Counter.new(128, initial_value=iv)
     return AES.new(key, AES.MODE_CTR, counter=ctr)
Beispiel #42
0
    def uploadfile(self, filename, dst=None):
        if not dst:
            root_id = getattr(self, 'root_id', None)
            if root_id == None:
                self.get_files()
            dst = self.root_id
        infile = open(filename, 'rb')
        size = os.path.getsize(filename)
        ul_url = self.api_req({'a': 'u', 's': size})['p']

        ul_key = [random.randint(0, 0xFFFFFFFF) for _ in range(6)]
        counter = Counter.new(
            128, initial_value=((ul_key[4] << 32) + ul_key[5]) << 64)
        encryptor = AES.new(a32_to_str(ul_key[:4]),
                            AES.MODE_CTR,
                            counter=counter)

        file_mac = [0, 0, 0, 0]
        for chunk_start, chunk_size in sorted(get_chunks(size).items()):
            chunk = infile.read(chunk_size)

            chunk_mac = [ul_key[4], ul_key[5], ul_key[4], ul_key[5]]
            for i in range(0, len(chunk), 16):
                block = chunk[i:i + 16]
                if len(block) % 16:
                    block += b'\0' * (16 - len(block) % 16)
                block = str_to_a32(block)
                chunk_mac = [
                    chunk_mac[0] ^ block[0], chunk_mac[1] ^ block[1],
                    chunk_mac[2] ^ block[2], chunk_mac[3] ^ block[3]
                ]
                chunk_mac = aes_cbc_encrypt_a32(chunk_mac, ul_key[:4])

            file_mac = [
                file_mac[0] ^ chunk_mac[0], file_mac[1] ^ chunk_mac[1],
                file_mac[2] ^ chunk_mac[2], file_mac[3] ^ chunk_mac[3]
            ]
            file_mac = aes_cbc_encrypt_a32(file_mac, ul_key[:4])

            chunk = encryptor.encrypt(chunk)
            url = '%s/%s' % (ul_url, str(chunk_start))
            outfile = requests.post(url, data=chunk, stream=True).raw

            # assume utf-8 encoding. Maybe this entire section can be simplified
            # by not looking at the raw output
            # (http://docs.python-requests.org/en/master/user/advanced/#body-content-workflow)

            completion_handle = outfile.read().decode('utf-8')
        infile.close()

        meta_mac = (file_mac[0] ^ file_mac[1], file_mac[2] ^ file_mac[3])

        attributes = {'n': os.path.basename(filename)}
        enc_attributes = base64urlencode(enc_attr(attributes, ul_key[:4]))
        key = [
            ul_key[0] ^ ul_key[4], ul_key[1] ^ ul_key[5],
            ul_key[2] ^ meta_mac[0], ul_key[3] ^ meta_mac[1], ul_key[4],
            ul_key[5], meta_mac[0], meta_mac[1]
        ]
        encrypted_key = a32_to_base64(encrypt_key(key, self.master_key))
        data = self.api_req({
            'a':
            'p',
            't':
            dst,
            'n': [{
                'h': completion_handle,
                't': 0,
                'a': enc_attributes,
                'k': encrypted_key
            }]
        })
        return data
Beispiel #43
0
    def get_bytes(self):
        return self._bmp_header.pack(
            self.header,
            len(self.data) + self._bmp_header.size, self.res1, self.res2,
            self.image_offset + self._bmp_header.size) + self.data


from Crypto.Cipher import AES
from Crypto.Util import Counter

for mode, name in [(AES.MODE_ECB, 'ecb'), (AES.MODE_CBC, 'cbc'),
                   (AES.MODE_CTR, 'ctr')]:
    with open('gompei.bmp', 'rb') as gompei:
        bmp = Bmp(gompei.read())

        key = b'0' * AES.block_size
        iv = key

        ctr = Counter.new(128)

        aes = AES.new(key, mode, iv,
                      counter=ctr) if mode == AES.MODE_CTR else AES.new(
                          key, mode, iv)

        bmp.data = bmp.data[:bmp.image_offset] + aes.encrypt(
            bmp.data[bmp.image_offset:])

        with open('gompei_' + name + '.bmp', 'wb') as out:
            out.write(bmp.get_bytes())
def encrypt_file_3(filename, masterpassword, encmethod):
    output_filename = filename + ".crypt"
    file_to_encrypt = open(filename, "rb")
    file_to_output = open(output_filename, "wb")
    file_to_output_hex = ""
    startlen = 0
    file_to_encrypt_bin = file_to_encrypt.read()
    file_to_encrypt_hex = binascii.hexlify(file_to_encrypt_bin)
    file_length = len(file_to_encrypt_hex)
    masterkey, iv = generate_header_file(masterpassword, file_length, filename,
                                         encmethod)
    file_padding = 32 - (file_length % 32)
    while file_padding > 0:
        if file_padding >= 2:
            file_to_encrypt_hex += format(rng.randint(0, 255), '02x')
            file_padding -= 2
        else:
            file_to_encrypt_hex += "0"
            file_padding -= 1
    file_checksum = hashlib.sha512(
        file_to_encrypt_hex[0:file_length]).hexdigest()
    file_to_encrypt_hex += file_checksum
    file_length = len(file_to_encrypt_hex)
    file_to_encrypt.close()
    print "Times to iterate (W/chk): " + str(file_length / 32)
    print "Encrypted file checksum: ", file_checksum
    times_to_iterate = file_length / 32
    times_to_iterate_total = times_to_iterate
    current_key = hashlib.sha256(masterkey).digest()
    iv_hash = hashlib.sha512(iv + masterkey).hexdigest()
    real_iv_to_use = binascii.hexlify(
        hashlib.pbkdf2_hmac('sha512', masterkey, iv_hash, 10))
    real_iv_to_use = binascii.unhexlify(real_iv_to_use[:32])
    chunk_list = []
    if encmethod == 3:
        cipher = AES.new(current_key, AES.MODE_CBC, real_iv_to_use)
    elif encmethod == 4:
        icv = int(binascii.hexlify(real_iv_to_use), 16)
        ctr = Counter.new(128, initial_value=icv)
        cipher = AES.new(current_key, AES.MODE_CTR, counter=ctr)
    elif encmethod == 5:
        cipher = AES.new(current_key, AES.MODE_CFB, real_iv_to_use)
    elif encmethod == 6:
        cipher = AES.new(current_key, AES.MODE_OFB, real_iv_to_use)
    while times_to_iterate > 0:
        current_plaintext_chunk = binascii.unhexlify(
            file_to_encrypt_hex[startlen:startlen + 32])
        chunk_list.append(
            binascii.hexlify(cipher.encrypt(current_plaintext_chunk)))
        startlen += 32
        times_to_iterate -= 1
        if times_to_iterate % 15000 == 0:
            print "Encryption Progress: ", (
                times_to_iterate_total -
                times_to_iterate) / float(times_to_iterate_total) * 100.0, "%"
    #print file_to_output_hex
    file_to_output_hex = "".join(chunk_list)
    file_to_output.write(binascii.unhexlify(file_to_output_hex))
    file_to_output.close()
    dtk, dtl, dtv, div = read_header_file(masterpassword, filename)
    if dtv == 3 or dtv == 4 or dtv == 5 or dtv == 6:
        is_correct = decrypt_file_3(filename, True, dtk, dtl, div, dtv)
        if is_correct == "File decrypted, checksum OK":
            return "Encryption Done and Verified"
        else:
            return "ERROR!"
    else:
        return "BAD HEADER ERROR!"
Beispiel #45
0
    def _download_file(self,
                       file_handle,
                       file_key,
                       dest_path=None,
                       dest_filename=None,
                       is_public=False,
                       file=None):
        if file is None:
            if is_public:
                file_key = base64_to_a32(file_key)
                file_data = self._api_request({
                    'a': 'g',
                    'g': 1,
                    'p': file_handle
                })
            else:
                file_data = self._api_request({
                    'a': 'g',
                    'g': 1,
                    'n': file_handle
                })

            k = (file_key[0] ^ file_key[4], file_key[1] ^ file_key[5],
                 file_key[2] ^ file_key[6], file_key[3] ^ file_key[7])
            iv = file_key[4:6] + (0, 0)
            meta_mac = file_key[6:8]
        else:
            file_data = self._api_request({'a': 'g', 'g': 1, 'n': file['h']})
            k = file['k']
            iv = file['iv']
            meta_mac = file['meta_mac']

        # Seems to happens sometime... When this occurs, files are
        # inaccessible also in the official also in the official web app.
        # Strangely, files can come back later.
        if 'g' not in file_data:
            raise RequestError('File not accessible anymore')
        file_url = file_data['g']
        file_size = file_data['s']
        attribs = base64_url_decode(file_data['at'])
        attribs = decrypt_attr(attribs, k)

        if dest_filename is not None:
            file_name = dest_filename
        else:
            file_name = attribs['n']

        input_file = requests.get(file_url, stream=True).raw

        if dest_path is None:
            dest_path = ''
        else:
            dest_path += '/'

        with tempfile.NamedTemporaryFile(mode='w+b',
                                         prefix='megapy_',
                                         delete=False) as temp_output_file:
            k_str = a32_to_str(k)
            counter = Counter.new(128,
                                  initial_value=((iv[0] << 32) + iv[1]) << 64)
            aes = AES.new(k_str, AES.MODE_CTR, counter=counter)

            mac_str = '\0' * 16
            mac_encryptor = AES.new(k_str, AES.MODE_CBC,
                                    mac_str.encode("utf8"))
            iv_str = a32_to_str([iv[0], iv[1], iv[0], iv[1]])

            for chunk_start, chunk_size in get_chunks(file_size):
                chunk = input_file.read(chunk_size)
                chunk = aes.decrypt(chunk)
                temp_output_file.write(chunk)

                encryptor = AES.new(k_str, AES.MODE_CBC, iv_str)
                for i in range(0, len(chunk) - 16, 16):
                    block = chunk[i:i + 16]
                    encryptor.encrypt(block)

                # fix for files under 16 bytes failing
                if file_size > 16:
                    i += 16
                else:
                    i = 0

                block = chunk[i:i + 16]
                if len(block) % 16:
                    block += b'\0' * (16 - (len(block) % 16))
                mac_str = mac_encryptor.encrypt(encryptor.encrypt(block))

                file_info = os.stat(temp_output_file.name)
                logger.info('%s of %s downloaded', file_info.st_size,
                            file_size)
            file_mac = str_to_a32(mac_str)
            # check mac integrity
            if (file_mac[0] ^ file_mac[1],
                    file_mac[2] ^ file_mac[3]) != meta_mac:
                raise ValueError('Mismatched mac')
            output_path = Path(dest_path + file_name)
            shutil.move(temp_output_file.name, output_path)
            return output_path
        self.key = key

    def cifrar(self, cadena, contador):
        cadena = cadena.encode("UTF-8")
        cipher = AES.new(self.key, AES.MODE_CTR, counter=contador)
        ciphertext = cipher.encrypt(cadena)
        return ciphertext

    def descifrar(self, cifrado, contador):
        decipher_aes = AES.new(self.key, AES.MODE_CTR, counter=contador)
        new_data = decipher_aes.decrypt(cifrado).decode("utf-8", "ignore")
        return new_data


IV = get_random_bytes(8)
#Clave aleatoria 128 bits
key = get_random_bytes(16)
#Creo un nuevo counter
counter = Counter.new(64, prefix=IV)

print("AES Modo de Operacion CTR:")
datos = "Hola Amigos De Seguridad"
print(datos)
d = AES_CIPHER(key)
cifrado = d.cifrar(datos, counter)
print("Texto cifrado:")
print(cifrado)
descifrado = d.descifrar(cifrado, counter)
print("Texto descifrado:")
print(descifrado)
Beispiel #47
0
    def upload(self, filename, dest=None, dest_filename=None):
        # determine storage node
        if dest is None:
            # if none set, upload to cloud drive node
            if not hasattr(self, 'root_id'):
                self.get_files()
            dest = self.root_id

        # request upload url, call 'u' method
        with open(filename, 'rb') as input_file:
            file_size = os.path.getsize(filename)
            ul_url = self._api_request({'a': 'u', 's': file_size})['p']

            # generate random aes key (128) for file
            ul_key = [random.randint(0, 0xFFFFFFFF) for _ in range(6)]
            k_str = a32_to_str(ul_key[:4])
            count = Counter.new(
                128, initial_value=((ul_key[4] << 32) + ul_key[5]) << 64)
            aes = AES.new(k_str, AES.MODE_CTR, counter=count)

            upload_progress = 0
            completion_file_handle = None

            mac_str = '\0' * 16
            mac_encryptor = AES.new(k_str, AES.MODE_CBC,
                                    mac_str.encode("utf8"))
            iv_str = a32_to_str([ul_key[4], ul_key[5], ul_key[4], ul_key[5]])
            if file_size > 0:
                for chunk_start, chunk_size in get_chunks(file_size):
                    chunk = input_file.read(chunk_size)
                    upload_progress += len(chunk)

                    encryptor = AES.new(k_str, AES.MODE_CBC, iv_str)
                    for i in range(0, len(chunk) - 16, 16):
                        block = chunk[i:i + 16]
                        encryptor.encrypt(block)

                    # fix for files under 16 bytes failing
                    if file_size > 16:
                        i += 16
                    else:
                        i = 0

                    block = chunk[i:i + 16]
                    if len(block) % 16:
                        block += makebyte('\0' * (16 - len(block) % 16))
                    mac_str = mac_encryptor.encrypt(encryptor.encrypt(block))

                    # encrypt file and upload
                    chunk = aes.encrypt(chunk)
                    output_file = requests.post(ul_url + "/" +
                                                str(chunk_start),
                                                data=chunk,
                                                timeout=self.timeout)
                    completion_file_handle = output_file.text
                    logger.info('%s of %s uploaded', upload_progress,
                                file_size)
            else:
                output_file = requests.post(ul_url + "/0",
                                            data='',
                                            timeout=self.timeout)
                completion_file_handle = output_file.text

            logger.info('Chunks uploaded')
            logger.info('Setting attributes to complete upload')
            logger.info('Computing attributes')
            file_mac = str_to_a32(mac_str)

            # determine meta mac
            meta_mac = (file_mac[0] ^ file_mac[1], file_mac[2] ^ file_mac[3])

            dest_filename = dest_filename or os.path.basename(filename)
            attribs = {'n': dest_filename}

            encrypt_attribs = base64_url_encode(
                encrypt_attr(attribs, ul_key[:4]))
            key = [
                ul_key[0] ^ ul_key[4], ul_key[1] ^ ul_key[5],
                ul_key[2] ^ meta_mac[0], ul_key[3] ^ meta_mac[1], ul_key[4],
                ul_key[5], meta_mac[0], meta_mac[1]
            ]
            encrypted_key = a32_to_base64(encrypt_key(key, self.master_key))
            logger.info('Sending request to update attributes')
            # update attributes
            data = self._api_request({
                'a':
                'p',
                't':
                dest,
                'i':
                self.request_id,
                'n': [{
                    'h': completion_file_handle,
                    't': 0,
                    'a': encrypt_attribs,
                    'k': encrypted_key
                }]
            })
            logger.info('Upload complete')
            return data
def do_decrypt(message):
    iv_int = int.from_bytes(IV, byteorder='big')
    new_counter = Counter.new(128, initial_value=iv_int)
    cipher = AES.new(key, AES.MODE_CTR, counter=new_counter)
    return cipher.decrypt(message)
pad = '# constant pad for short keys ##'

# Generate a random initialization vector, to be used by both encryptor and decryptor
# This may be sent in clear in a real communication

IV = 95914734

# Encryption steps

# Ask user for input and pad or truncate to a 32 bytes (256 bits) key
prompt = 'Input your key. It will padded or truncated at 32 bytes (256 bits).\n-: '
user_keye = raw_input(prompt)
keye = (user_keye + pad)[:32]

# Create counter for encryptor
ctr_e = Counter.new(64, prefix=IV)

# Create encryptor, ask for plaintext to encrypt, then encrypt and print ciphertext
encryptor = AES.new(keye, AES.MODE_CTR, counter=ctr_e)

#input from a file
file = open("C:\Users\Madhav\Desktop\MINOR PROJECT\image.txt", "r")
plaintext = file.read()

#plaintext = raw_input('Enter message to cipher: ')
ciphertext = encryptor.encrypt(plaintext)
#print repr(ciphertext)

print("The data in the file is encrypted and stored in file enc.txt.\n")

filen = open("C:\Users\Madhav\Desktop\MINOR PROJECT\enc.txt", "w")
Beispiel #50
0
    # compare against a known working implementation
    try:
        from Crypto.Cipher import AES as KAES
        from Crypto.Util import Counter as KCounter

        for key_size in (128, 192, 256):
            for text_length in [3, 16, 127, 128, 129, 1500]:

                # Try 10 different values
                for i in xrange(0, 10):
                    key = os.urandom(key_size // 8)
                    plaintext = os.urandom(text_length)

                    kaes = KAES.new(key,
                                    KAES.MODE_CTR,
                                    counter=KCounter.new(128, initial_value=0))
                    kenc = kaes.encrypt(plaintext)

                    aes = AESCounterModeOfOperation(key)
                    enc = aes.encrypt(plaintext)

                    result = {True: "pass", False: "fail"}[kenc == enc]
                    print(
                        "Test Encrypt: key_size=%d text_length=%d trial=%d result=%s"
                        % (key_size, text_length, i, result))

                    aes = AESCounterModeOfOperation(key)
                    result = {
                        True: "pass",
                        False: "fail"
                    }[plaintext == aes.decrypt(kenc)]
Beispiel #51
0
def decrypt(text):
    ctr = Counter.new(128, initial_value=bytes_to_long(iv))
    aes = AES.new(key, AES.MODE_CTR, counter=ctr)
    return aes.decrypt(text)
Beispiel #52
0
 def get_encryptor(self, nonce):
     ctr_value = int.from_bytes(nonce, byteorder='big')
     counter = Counter.new(128, initial_value=ctr_value)
     return AES.new(self.key, AES.MODE_CTR, counter=counter)
Beispiel #53
0
 def ctr_encrypt(data):
     key = random_key(16)
     ctr = Counter.new(128)
     return AES.new(key, mode=AES.MODE_CTR, counter=ctr).encrypt(data)
Beispiel #54
0
def encrypt_message(key, plaintext):
    iv = os.urandom(16)
    ctr = Counter.new(128, initial_value=int_of_string(iv))
    aes = AES.new(key, AES.MODE_CTR, counter=ctr)
    return iv + aes.encrypt(plaintext)
Beispiel #55
0
    def upload(self, filename, dest=None, dest_filename=None):
        #determine storage node
        if dest is None:
            #if none set, upload to cloud drive node
            if not hasattr(self, 'root_id'):
                self.get_files()
            dest = self.root_id

        #request upload url, call 'u' method
        input_file = open(filename, 'rb')
        file_size = os.path.getsize(filename)
        ul_url = self.api_request({'a': 'u', 's': file_size})['p']

        #generate random aes key (128) for file
        ul_key = [random.randint(0, 0xFFFFFFFF) for _ in range(6)]
        k_str = a32_to_str(ul_key[:4])
        count = Counter.new(
            128, initial_value=((ul_key[4] << 32) + ul_key[5]) << 64)
        aes = AES.new(k_str, AES.MODE_CTR, counter=count)

        upload_progress = 0
        completion_file_handle = None

        mac_str = '\0' * 16
        mac_encryptor = AES.new(k_str, AES.MODE_CBC, mac_str)
        iv_str = a32_to_str([ul_key[4], ul_key[5], ul_key[4], ul_key[5]])

        for chunk_start, chunk_size in get_chunks(file_size):
            chunk = input_file.read(chunk_size)
            upload_progress += len(chunk)

            encryptor = AES.new(k_str, AES.MODE_CBC, iv_str)
            for i in range(0, len(chunk) - 16, 16):
                block = chunk[i:i + 16]
                encryptor.encrypt(block)
            i += 16
            block = chunk[i:i + 16]
            if len(block) % 16:
                block += '\0' * (16 - len(block) % 16)
            mac_str = mac_encryptor.encrypt(encryptor.encrypt(block))

            #encrypt file and upload
            chunk = aes.encrypt(chunk)
            output_file = requests.post(ul_url + "/" + str(chunk_start),
                                        data=chunk,
                                        timeout=self.timeout)
            completion_file_handle = output_file.text

            if self.options.get('verbose') is True:
                # upload progress
                print('{0} of {1} uploaded'.format(upload_progress, file_size))

        file_mac = str_to_a32(mac_str)

        #determine meta mac
        meta_mac = (file_mac[0] ^ file_mac[1], file_mac[2] ^ file_mac[3])

        if dest_filename is not None:
            attribs = {'n': dest_filename}
        else:
            attribs = {'n': os.path.basename(filename)}

        encrypt_attribs = base64_url_encode(encrypt_attr(attribs, ul_key[:4]))
        key = [
            ul_key[0] ^ ul_key[4], ul_key[1] ^ ul_key[5],
            ul_key[2] ^ meta_mac[0], ul_key[3] ^ meta_mac[1], ul_key[4],
            ul_key[5], meta_mac[0], meta_mac[1]
        ]
        encrypted_key = a32_to_base64(encrypt_key(key, self.master_key))
        #update attributes
        data = self.api_request({
            'a':
            'p',
            't':
            dest,
            'n': [{
                'h': completion_file_handle,
                't': 0,
                'a': encrypt_attribs,
                'k': encrypted_key
            }]
        })
        #close input file and return API msg
        input_file.close()
        return data
Beispiel #56
0
def decrypt_message(key, ciphertext):
    iv = ciphertext[:16]
    ctr = Counter.new(128, initial_value=int_of_string(iv))
    aes = AES.new(key, AES.MODE_CTR, counter=ctr)
    return aes.decrypt(ciphertext[16:])
Beispiel #57
0
                tt_ksetup += time.time() - t0

                t0 = time.time()
                aes = AESModeOfOperationOFB(key, iv = iv)
                aes2 = AESModeOfOperationOFB(key, iv = iv)
                tt_setup += time.time() - t0

            elif mode == 'CTR':
                text_length = [None, 3, 16, 127, 128, 129, 1500, 10000, 100000, 10001, 10002, 10003, 10004, 10005, 10006, 10007, 10008][test]
                if test < 6:
                    plaintext = [ os.urandom(text_length) ]
                else:
                    plaintext = [ os.urandom(text_length) for x in xrange(0, test) ]

                t0 = time.time()
                kaes = KAES.new(key, KAES.MODE_CTR, counter = KCounter.new(128, initial_value = 0))
                kaes2 = KAES.new(key, KAES.MODE_CTR, counter = KCounter.new(128, initial_value = 0))
                tt_ksetup += time.time() - t0

                t0 = time.time()
                aes = AESModeOfOperationCTR(key, counter = Counter(initial_value = 0))
                aes2 = AESModeOfOperationCTR(key, counter = Counter(initial_value = 0))
                tt_setup += time.time() - t0

            count += 1

            t0 = time.time()
            kenc = [kaes.encrypt(p) for p in plaintext]
            tt_kencrypt += time.time() - t0

            t0 = time.time()
Beispiel #58
0
    print(wrappedkey.hex())

    payloadkey = aeskeywrap.unwrapiv(kek, wrappedkey, kekiv)
    print(payloadkey.hex())

    print('kek', len(kek))
    print('kekiv', len(kekiv))
    print('wrappedkey', len(wrappedkey))
    print('payloadiv', len(payloadiv))
    print('encryptedpayload', len(encryptedpayload))
    print('payloadkey', len(payloadkey))

    print(payloadiv.hex())
    counter = Counter.new(len(payloadiv) * 8,
                          initial_value=int.from_bytes(payloadiv, 'big'),
                          allow_wraparound=False)

    # test: dump the counter values
    #print('call counter:')
    #print(counter().hex());
    #print(counter().hex());
    #print(counter().hex());
    #print(counter().hex());
    #print(counter().hex());

    ctr = AES.new(payloadkey, AES.MODE_CTR, counter=counter)
    decryptedpayload = ctr.decrypt(bytes(encryptedpayload))

    # first 200 bytes
    print(decryptedpayload[0:200].decode())
Beispiel #59
0
 def runTest(self):
     for pt, ct, key, prefix in self.bindata:
         counter = Counter.new(32, prefix=prefix)
         cipher = AES.new(key, AES.MODE_CTR, counter=counter)
         result = cipher.encrypt(pt)
         self.assertEqual(ct, result)
Beispiel #60
-1
    def test_nonce_parameter(self):
        # Nonce parameter becomes nonce attribute
        cipher1 = AES.new(self.key_128, AES.MODE_CTR, nonce=self.nonce_64)
        self.assertEqual(cipher1.nonce, self.nonce_64)

        counter = Counter.new(64, prefix=self.nonce_64, initial_value=0)
        cipher2 = AES.new(self.key_128, AES.MODE_CTR, counter=counter)
        self.assertEqual(cipher1.nonce, cipher2.nonce)

        pt = get_tag_random("plaintext", 65536)
        self.assertEqual(cipher1.encrypt(pt), cipher2.encrypt(pt))

        # Nonce is implicitly created (for AES) when no parameters are passed
        nonce1 = AES.new(self.key_128, AES.MODE_CTR).nonce
        nonce2 = AES.new(self.key_128, AES.MODE_CTR).nonce
        self.assertNotEqual(nonce1, nonce2)
        self.assertEqual(len(nonce1), 8)

        # Nonce can be zero-length
        cipher = AES.new(self.key_128, AES.MODE_CTR, nonce=b"")
        self.assertEqual(b"", cipher.nonce)
        cipher.encrypt(b'0'*300)

        # Nonce and Counter are mutually exclusive
        self.assertRaises(TypeError, AES.new, self.key_128, AES.MODE_CTR,
                          counter=self.ctr_128, nonce=self.nonce_64)