Python Crypto.Cipher.AES.MODE_ECB Examples

The following are 30 code examples of Crypto.Cipher.AES.MODE_ECB(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module Crypto.Cipher.AES , or try the search function .
Example #1
Source File: encryptionencoding.py    From chepy with GNU General Public License v3.0 12 votes vote down vote up
def triple_des_encrypt(
        self,
        key: str,
        iv: str = "0000000000000000",
        mode: str = "CBC",
        hex_key: bool = False,
        hex_iv: bool = True,
    ):
        """Encrypt raw state with Triple DES

        Triple DES applies DES three times to each block to increase key size. Key: 
        Triple DES uses a key length of 24 bytes (192 bits).<br>DES uses a key length 
        of 8 bytes (64 bits).<br><br>You can generate a password-based key using one 
        of the KDF operations. IV: The Initialization Vector should be 8 bytes long. 
        If not entered, it will default to 8 null bytes. Padding: In CBC and ECB 
        mode, PKCS#7 padding will be used.
        
        Args:
            key (str): Required. The secret key
            iv (str, optional): IV for certain modes only. Defaults to '0000000000000000'.
            mode (str, optional): Encryption mode. Defaults to 'CBC'.
            hex_key (bool, optional): If the secret key is a hex string. Defaults to False.
            hex_iv (bool, optional): If the IV is a hex string. Defaults to True.
        
        Returns:
            Chepy: The Chepy object. 

        Examples:
            >>> Chepy("some data").triple_des_encrypt("super secret password !!", mode="ECB").o
            b"f8b27a0d8c837edc8fb00ea85f502fb4"
        """

        self.__check_mode(mode)

        key, iv = self._convert_key(key, iv, hex_key, hex_iv)

        if mode == "CBC":
            cipher = DES3.new(key, mode=DES3.MODE_CBC, iv=iv)
            self.state = cipher.encrypt(pad(self._convert_to_bytes(), 8))
            return self
        elif mode == "ECB":
            cipher = DES3.new(key, mode=DES3.MODE_ECB)
            self.state = cipher.encrypt(pad(self._convert_to_bytes(), 8))
            return self
        elif mode == "CTR":
            cipher = DES3.new(key, mode=DES3.MODE_CTR, nonce=b"")
            self.state = cipher.encrypt(self._convert_to_bytes())
            return self
        elif mode == "OFB":
            cipher = DES3.new(key, mode=DES3.MODE_OFB, iv=iv)
            self.state = cipher.encrypt(self._convert_to_bytes())
            return self 
Example #2
Source File: packet.py    From NintendoClients with MIT License 10 votes vote down vote up
def decrypt(self, data):
		key = self.session.get_session_key()
		
		method = self.settings.get("pia.encryption_method")
		if method == EncryptionMethod.AES_ECB:
			aes = AES.new(key, AES.MODE_ECB)
			return aes.decrypt(data)
		else:
			nonce = self.session.generate_nonce(self)
			aes = AES.new(key, AES.MODE_GCM, nonce=nonce)
			try:
				data = aes.decrypt_and_verify(data, self.signature)
			except ValueError:
				logger.warning("Received incorrect AES-GCM tag")
				return None
			return data 
Example #3
Source File: crypto.py    From LaZagneForensic with GNU Lesser General Public License v3.0 6 votes vote down vote up
def decrypt_lsa_key_nt6(lsakey, syskey):
	"""
	This function decrypts the LSA keys using the syskey
	"""
	dg = hashlib.sha256()
	dg.update(syskey)
	for i in xrange(1000):
		dg.update(lsakey[28:60])
	keys = AES.new(dg.digest(), AES.MODE_ECB).decrypt(lsakey[60:])
	size = struct.unpack_from("<L", keys)[0]
	keys = keys[16:16 + size]
	currentkey = "%0x-%0x-%0x-%0x%0x-%0x%0x%0x%0x%0x%0x" % struct.unpack("<L2H8B", keys[4:20])
	nb = struct.unpack("<L", keys[24:28])[0]
	off = 28
	kd = {}
	for i in xrange(nb):
		g = "%0x-%0x-%0x-%0x%0x-%0x%0x%0x%0x%0x%0x" % struct.unpack("<L2H8B", keys[off:off + 16])
		t, l = struct.unpack_from("<2L", keys[off + 16:])
		k = keys[off + 24:off + 24 + l]
		kd[g] = {"type": t, "key": k}
		off += 24 + l
	return (currentkey, kd) 
Example #4
Source File: encryptionencoding.py    From chepy with GNU General Public License v3.0 6 votes vote down vote up
def des_encrypt(
        self,
        key: str,
        iv: str = "0000000000000000",
        mode: str = "CBC",
        hex_key: bool = False,
        hex_iv: bool = True,
    ):
        """Encrypt raw state with DES

        DES is a previously dominant algorithm for encryption, and was published 
        as an official U.S. Federal Information Processing Standard (FIPS). It is 
        now considered to be insecure due to its small key size. DES uses a key 
        length of 8 bytes (64 bits).<br>Triple DES uses a key length of 24 bytes. 
        You can generate a password-based key using one of the KDF operations. 
        The Initialization Vector should be 8 bytes long. If not entered, it will 
        default to 8 null bytes. Padding: In CBC and ECB mode, PKCS#7 padding will be used.
        
        Args:
            key (str): Required. The secret key
            iv (str, optional): IV for certain modes only. Defaults to '0000000000000000'.
            mode (str, optional): Encryption mode. Defaults to 'CBC'.
            hex_key (bool, optional): If the secret key is a hex string. Defaults to False.
            hex_iv (bool, optional): If the IV is a hex string. Defaults to True.
        
        Returns:
            Chepy: The Chepy object. 

        Examples:
            >>> Chepy("some data").des_encrypt("70617373776f7264", hex_key=True).o
            b"1ee5cb52954b211d1acd6e79c598baac"

            To encrypt using a differnt mode

            >>> Chepy("some data").des_encrypt("password", mode="CTR").o
            b"0b7399049b0267d93d"
        """

        self.__check_mode(mode)

        key, iv = self._convert_key(key, iv, hex_key, hex_iv)

        if mode == "CBC":
            cipher = DES.new(key, mode=DES.MODE_CBC, iv=iv)
            self.state = cipher.encrypt(pad(self._convert_to_bytes(), 8))
            return self
        elif mode == "ECB":
            cipher = DES.new(key, mode=DES.MODE_ECB)
            self.state = cipher.encrypt(pad(self._convert_to_bytes(), 8))
            return self
        elif mode == "CTR":
            cipher = DES.new(key, mode=DES.MODE_CTR, nonce=b"")
            self.state = cipher.encrypt(self._convert_to_bytes())
            return self
        elif mode == "OFB":
            cipher = DES.new(key, mode=DES.MODE_OFB, iv=iv)
            self.state = cipher.encrypt(self._convert_to_bytes())
            return self 
Example #5
Source File: crypto.py    From LaZagneForensic with GNU Lesser General Public License v3.0 6 votes vote down vote up
def decrypt_lsa_secret(secret, lsa_keys):
	"""
	This function replaces SystemFunction005 for newer Windows
	"""
	keyid = "%0x-%0x-%0x-%0x%0x-%0x%0x%0x%0x%0x%0x" % struct.unpack("<L2H8B", secret[4:20])
	if keyid not in lsa_keys:
		return None
	algo = struct.unpack("<L", secret[20:24])[0]
	dg = hashlib.sha256()
	dg.update(lsa_keys[keyid]["key"])
	for i in xrange(1000):
		dg.update(secret[28:60])

	clear = AES.new(dg.digest(), AES.MODE_ECB).decrypt(secret[60:])
	size = struct.unpack_from("<L", clear)[0]
	return clear[16:16 + size] 
Example #6
Source File: test_ecb.py    From CryptoAttacks with MIT License 6 votes vote down vote up
def encryption_oracle_aes(payload):
    global constant, prefix_len, suffix_len, secret
    if secret:
        if constant:
            payload = random_bytes(prefix_len) + payload + secret
        else:
            payload = random_bytes(random.randint(1, 50)) + payload + secret
    else:
        if constant:
            payload = random_bytes(prefix_len) + payload + random_bytes(suffix_len)
        else:
            payload = random_bytes(random.randint(1, 50)) + payload + random_bytes(random.randint(1, 50))

    payload = add_padding(payload, AES.block_size)
    cipher = AES.new(key_AES, AES.MODE_ECB)
    return cipher.encrypt(payload) 
Example #7
Source File: test_ecb.py    From CryptoAttacks with MIT License 6 votes vote down vote up
def encryption_oracle_des(payload):
    global constant, prefix_len, suffix_len, secret
    if secret:
        if constant:
            payload = random_bytes(prefix_len) + payload + secret
        else:
            payload = random_bytes(random.randint(1, 50)) + payload + secret
    else:
        if constant:
            payload = random_bytes(prefix_len) + payload + random_bytes(suffix_len)
        else:
            payload = random_bytes(random.randint(1, 50)) + payload + random_bytes(random.randint(1, 50))

    payload = add_padding(payload, DES3.block_size)
    cipher = DES3.new(key_DES3, DES3.MODE_ECB)
    return cipher.encrypt(payload) 
Example #8
Source File: cryptutils.py    From edl with MIT License 6 votes vote down vote up
def change_key(self, master_key):
                if master_key >= (1 << 128):
                    raise InvalidInputException('Master key should be 128-bit')

                self.__master_key = long_to_bytes(master_key, 16)
                self.__aes_ecb = AES.new(self.__master_key, AES.MODE_ECB)
                self.__auth_key = bytes_to_long(self.__aes_ecb.encrypt(b'\x00' * 16))

                # precompute the table for multiplication in finite field
                table = []  # for 8-bit
                for i in range(16):
                    row = []
                    for j in range(256):
                        row.append(self.gf_2_128_mul(self.__auth_key, j << (8 * i)))
                    table.append(tuple(row))
                self.__pre_table = tuple(table)

                self.prev_init_value = None  # reset 
Example #9
Source File: solve.py    From programming-challenges with GNU General Public License v2.0 6 votes vote down vote up
def main():
    with open(F,'r') as f:
      b64 = f.read()
      enc = tools.fromB64(b64)
    
    encBlocks = tools.split(enc, 16, False)

    iv = IV
    result = b''
    
    cipher=AES.new(KEY, AES.MODE_ECB)
    
    for block in encBlocks:
      decBlock = cipher.decrypt(block)
      dec = crypto.xor(decBlock, iv)
      iv = block
      result += dec
    
    print(tools.toStr(tools.stripPadding(result))) 
Example #10
Source File: mycrypt.py    From codo-tools with GNU General Public License v3.0 5 votes vote down vote up
def my_decrypt(self, text):
        """
        解密方法
        :param text: 加密后的密文
        :return:
        """
        # 初始化加密器
        aes = AES.new(self.add_to_16(self.key), AES.MODE_ECB)
        # 优先逆向解密base64成bytes
        base64_decrypted = base64.decodebytes(text.encode(encoding='utf-8'))
        # 执行解密密并转码返回str
        decrypted_text = str(aes.decrypt(base64_decrypted), encoding='utf-8').replace('\0', '')
        # print('[INFO]: 你的解密为:{}'.format(decrypted_text))
        return decrypted_text 
Example #11
Source File: dauth.py    From NintendoClients with MIT License 5 votes vote down vote up
def decrypt_key(self, key, kek):
		aes = AES.new(kek, AES.MODE_ECB)
		return aes.decrypt(key) 
Example #12
Source File: __init__.py    From ops_sdk with GNU General Public License v3.0 5 votes vote down vote up
def my_encrypt(self, text):
        """
        加密方法
        :param text: 密码
        :return:
        """
        aes = AES.new(self.add_to_16(self.key), AES.MODE_ECB)
        # 先进行aes加密

        encrypt_aes = aes.encrypt(self.add_to_16(text))
        # 用base64转成字符串形式
        encrypted_text = str(base64.encodebytes(encrypt_aes), encoding='utf-8').replace('\n', '')  # 执行加密并转码返回bytes
        # print('[INFO]: 你的加密为:{}'.format(encrypted_text))
        return encrypted_text 
Example #13
Source File: __init__.py    From ops_sdk with GNU General Public License v3.0 5 votes vote down vote up
def my_decrypt(self, text):
        """
        解密方法
        :param text: 加密后的密文
        :return:
        """
        # 初始化加密器
        aes = AES.new(self.add_to_16(self.key), AES.MODE_ECB)
        # 优先逆向解密base64成bytes
        base64_decrypted = base64.decodebytes(text.encode(encoding='utf-8'))
        # 执行解密密并转码返回str
        decrypted_text = str(aes.decrypt(base64_decrypted), encoding='utf-8').replace('\0', '')
        # print('[INFO]: 你的解密为:{}'.format(decrypted_text))
        return decrypted_text 
Example #14
Source File: mycrypt.py    From codo-tools with GNU General Public License v3.0 5 votes vote down vote up
def my_encrypt(self, text):
        """
        加密方法
        :param text: 密码
        :return:
        """
        aes = AES.new(self.add_to_16(self.key), AES.MODE_ECB)
        # 先进行aes加密

        encrypt_aes = aes.encrypt(self.add_to_16(text))
        # 用base64转成字符串形式
        encrypted_text = str(base64.encodebytes(encrypt_aes), encoding='utf-8').replace('\n', '')# 执行加密并转码返回bytes
        # print('[INFO]: 你的加密为:{}'.format(encrypted_text))
        return encrypted_text 
Example #15
Source File: crypto.py    From programming-challenges with GNU General Public License v2.0 5 votes vote down vote up
def decryptECB(key, data):
    cipher = AES.new(key, AES.MODE_ECB)
    dec = cipher.decrypt(data)
    return tools.stripPadding(dec)

#########################################################################
###               AES CBC crypto with PKCS#7 padding                  ###
######################################################################### 
Example #16
Source File: emoji.py    From wechat-dump with GNU General Public License v3.0 5 votes vote down vote up
def _decrypt_emoji(self, fname):
        cipher = AES.new(self.encryption_key, AES.MODE_ECB)
        with open(fname, 'rb') as f:
            head = f.read(1024)
            plain_head = cipher.decrypt(head)
            data = plain_head + f.read()
        return data 
Example #17
Source File: crypto.py    From programming-challenges with GNU General Public License v2.0 5 votes vote down vote up
def encryptCBC(key, data, iv = b'\000' * 16):
    data = tools.addPadding(data)
    blocks = tools.split(data, 16, False)

    result = b''
    
    cipher=AES.new(key, AES.MODE_ECB)
    
    for block in blocks:
      inBlock = xor(block, iv)
      encBlock = cipher.encrypt(inBlock)
      iv = encBlock
      result += encBlock
    
    return result 
Example #18
Source File: cryptutils.py    From edl with MIT License 5 votes vote down vote up
def aes_ecb(self,key,data,decrypt=True):
            if decrypt:
                return AES.new(key, AES.MODE_ECB).decrypt(data)
            else:
                return AES.new(key, AES.MODE_ECB).encrypt(data) 
Example #19
Source File: unlock-nokelock.py    From snippets with MIT License 5 votes vote down vote up
def setKey(self,key):
        self.key=key
        self.aes=AES.new(key, AES.MODE_ECB) 
Example #20
Source File: unlock-bozzys.py    From snippets with MIT License 5 votes vote down vote up
def setKey(self,key):
        self.key=key
        self.aes=AES.new(key, AES.MODE_ECB) 
Example #21
Source File: prob7.py    From cryptopals with Apache License 2.0 5 votes vote down vote up
def aes_ecb_dec(rawCipher, rawKey):
    aes = AES.new(rawKey, AES.MODE_ECB); 
    return aes.decrypt(rawCipher); 
Example #22
Source File: packet.py    From NintendoClients with MIT License 5 votes vote down vote up
def encrypt(self, data):
		key = self.session.get_session_key()
		
		method = self.settings.get("pia.encryption_method")
		if method == EncryptionMethod.AES_ECB:
			aes = AES.new(key, AES.MODE_ECB)
			return aes.encrypt(data)
		else:
			if len(data) % 16:
				data += b"\xFF" * (16 - len(data) % 16)
			nonce = self.session.generate_nonce(self)
			aes = AES.new(key, AES.MODE_GCM, nonce=nonce)
			data, self.signature = aes.encrypt_and_digest(data)
			return data 
Example #23
Source File: lan.py    From NintendoClients with MIT License 5 votes vote down vote up
def decrypt_challenge_key(self, key):
		aes = AES.new(self.key, AES.MODE_ECB)
		return aes.decrypt(key) 
Example #24
Source File: lan.py    From NintendoClients with MIT License 5 votes vote down vote up
def generate_challenge_key(self, key):
		aes = AES.new(self.key, AES.MODE_ECB)
		return aes.encrypt(key) 
Example #25
Source File: base.py    From MiBand2 with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def _encrypt(self, message):
        aes = AES.new(self._KEY, AES.MODE_ECB)
        return aes.encrypt(message) 
Example #26
Source File: models.py    From pycopia with Apache License 2.0 5 votes vote down vote up
def _get_password(self):
        from Crypto.Cipher import AES
        eng = AES.new(get_key(), AES.MODE_ECB)
        return eng.decrypt(unhexdigest(self._password.encode("ascii"))).strip(b"\0") 
Example #27
Source File: models.py    From pycopia with Apache License 2.0 5 votes vote down vote up
def _set_password(self, passwd):
        # Using pycrypto package.
        from Crypto.Cipher import AES
        eng = AES.new(get_key(), AES.MODE_ECB)
        self._password = hexdigest(eng.encrypt((passwd + b"\0"*(16 - len(passwd)))[:16])) 
Example #28
Source File: debugtalk.py    From Joy_QA_Platform with Apache License 2.0 5 votes vote down vote up
def get_aes_with_key(key,*args):
    text = ''
    for index,value in enumerate(args):
        if index%2 == 0:
#           print(str(args[index]),"----",str(args[index+1]))
            text += "&" + parse.quote_plus(str(args[index])) + "=" + parse.quote_plus(str(args[index+1]))
    text = text[1:]
    mode = AES.MODE_ECB
    cryptor = AES.new(key, mode, key)
    #这里密钥key 长度必须为16(AES-128)、24(AES-192)、或32(AES-256)Bytes 长度.目前AES-128足够用
    length = 16
    count = len(text)
    if(count % length != 0) :
        add = length - (count % length)
    else:
        add = 0
    # text = text + ('\0' * add)
    text = pad(text)
#   print('--aes加密前--',text)
    ciphertext = cryptor.encrypt(text)
    ciphertext = base64.b64encode(ciphertext)
#   print('--aes加密hou--',ciphertext)
    
    #因为AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题
    #所以这里统一把加密后的字符串转化为16进制字符串
    return ciphertext 
Example #29
Source File: pycrypto.py    From wechatpy with MIT License 5 votes vote down vote up
def __init__(self, key):
        super().__init__(AES.new(key, AES.MODE_ECB)) 
Example #30
Source File: prob10.py    From cryptopals with Apache License 2.0 5 votes vote down vote up
def aes_ecb_enc(rawCipher, rawKey):
    aes = AES.new(rawKey, AES.MODE_ECB); 
    return aes.encrypt(rawCipher);