Python Crypto.Cipher.DES3.new() Examples

The following are 30 code examples of Crypto.Cipher.DES3.new(). 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.DES3 , 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: Util.py    From PyMicroChat with GNU General Public License v3.0 6 votes vote down vote up
def SignWith3Des(src):
    # 首先对字符串取MD5
    raw_buf = hashlib.md5(src.encode()).digest()
    # 对16字节的md5做bcd2ascii
    bcd_to_ascii = bytearray(32)
    for i in range(len(raw_buf)):
        bcd_to_ascii[2*i]   = raw_buf[i]>>4
        bcd_to_ascii[2*i+1] = raw_buf[i] & 0xf
    # hex_to_bin转换加密key
    key = bytes.fromhex('3ECA2F6FFA6D4952ABBACA5A7B067D23')
    # 对32字节的bcd_to_ascii做Triple DES加密(3DES/ECB/NoPadding)
    des3 = DES3.new(key, DES3.MODE_ECB)
    enc_bytes = des3.encrypt(bcd_to_ascii)
    # bin_to_hex得到最终加密结果
    enc_buf = ''.join(["%02X" % x for x in enc_bytes]).strip()
    return enc_buf

# 根据svrid查询client_msg_id 
Example #3
Source File: encryptionencoding.py    From chepy with GNU General Public License v3.0 6 votes vote down vote up
def rc4_encrypt(self, key: str, hex_key: bool = False):
        """Encrypt raw state with RC4
        
        Args:
            key (str): Required. Secret key
            hex_key (bool, optional): If key is in hex. Defaults to False.
        
        Returns:
            Chepy: The Chepy object. 

        Examples:
            >>> Chepy("some data").rc4_encrypt("736563726574", hex_key=True).o
            b"9e59bf79a2c0b7d253"
        """
        if hex_key:
            key = binascii.unhexlify(key)
        if isinstance(key, str):
            key = key.encode()
        cipher = ARC4.new(key)
        self.state = binascii.hexlify(cipher.encrypt(self._convert_to_bytes()))
        return self 
Example #4
Source File: encryptionencoding.py    From chepy with GNU General Public License v3.0 6 votes vote down vote up
def rc4_decrypt(self, key: str, hex_key: bool = False):
        """Decrypt raw state with RC4
        
        Args:
            key (str): Required. Secret key
            hex_key (bool, optional): If key is in hex. Defaults to False.
        
        Returns:
            Chepy: The Chepy object. 

        Examples:
            >>> Chepy("9e59bf79a2c0b7d253").hex_to_str().rc4_decrypt("secret").o
            b"some data"
        """
        if hex_key:
            key = binascii.unhexlify(key)
        if isinstance(key, str):
            key = key.encode()
        cipher = ARC4.new(key)
        self.state = cipher.decrypt(self._convert_to_bytes())
        return self 
Example #5
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 #6
Source File: crypto.py    From CVE-2017-7494 with GNU General Public License v3.0 6 votes vote down vote up
def decrypt(cls, key, keyusage, ciphertext):
        if len(ciphertext) < 24:
            raise ValueError('ciphertext too short')
        cksum, basic_ctext = ciphertext[:16], ciphertext[16:]
        ki = HMAC.new(key.contents, cls.usage_str(keyusage), MD5).digest()
        ke = HMAC.new(ki, cksum, MD5).digest()
        basic_plaintext = ARC4.new(ke).decrypt(basic_ctext)
        exp_cksum = HMAC.new(ki, basic_plaintext, MD5).digest()
        ok = _mac_equal(cksum, exp_cksum)
        if not ok and keyusage == 9:
            # Try again with usage 8, due to RFC 4757 errata.
            ki = HMAC.new(key.contents, pack('<I', 8), MD5).digest()
            exp_cksum = HMAC.new(ki, basic_plaintext, MD5).digest()
            ok = _mac_equal(cksum, exp_cksum)
        if not ok:
            raise InvalidChecksum('ciphertext integrity failure')
        # Discard the confounder.
        return basic_plaintext[8:] 
Example #7
Source File: jrat.py    From CIRTKit with MIT License 6 votes vote down vote up
def messy_split(long_line):
    # this is a messy way to split the data but it works for now.
    '''
    Split on = gives me the right sections but deletes the b64 padding
    use modulo math to restore padding.
    return new list.
    '''
    new_list = []
    old_list = long_line.split('=')
    for line in old_list:
        if len(line) != 0:
            line += "=" * ((4 - len(line) % 4) % 4)
            new_list.append(line)
    return new_list

# AES Decrypt 
Example #8
Source File: crypto.py    From cracke-dit with MIT License 6 votes vote down vote up
def decrypt(cls, key, keyusage, ciphertext):
        if len(ciphertext) < 24:
            raise ValueError('ciphertext too short')
        cksum, basic_ctext = ciphertext[:16], ciphertext[16:]
        ki = HMAC.new(key.contents, cls.usage_str(keyusage), MD5).digest()
        ke = HMAC.new(ki, cksum, MD5).digest()
        basic_plaintext = ARC4.new(ke).decrypt(basic_ctext)
        exp_cksum = HMAC.new(ki, basic_plaintext, MD5).digest()
        ok = _mac_equal(cksum, exp_cksum)
        if not ok and keyusage == 9:
            # Try again with usage 8, due to RFC 4757 errata.
            ki = HMAC.new(key.contents, pack('<I', 8), MD5).digest()
            exp_cksum = HMAC.new(ki, basic_plaintext, MD5).digest()
            ok = _mac_equal(cksum, exp_cksum)
        if not ok:
            raise InvalidChecksum('ciphertext integrity failure')
        # Discard the confounder.
        return basic_plaintext[8:] 
Example #9
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 #10
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 #11
Source File: RSA.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def _get_randfunc(self, randfunc):
        if randfunc is not None:
            return randfunc
        elif self._current_randfunc is None:
            self._current_randfunc = Random.new().read
        return self._current_randfunc 
Example #12
Source File: RSA.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, implementation, key, randfunc=None):
        self.implementation = implementation
        self.key = key
        if randfunc is None:
            randfunc = Random.new().read
        self._randfunc = randfunc 
Example #13
Source File: RSA.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, **kwargs):
        """Create a new RSA key factory.

        :Keywords:
         use_fast_math : bool
                                Specify which mathematic library to use:

                                - *None* (default). Use fastest math available.
                                - *True* . Use fast math.
                                - *False* . Use slow math.
         default_randfunc : callable
                                Specify how to collect random data:

                                - *None* (default). Use Random.new().read().
                                - not *None* . Use the specified function directly.
        :Raise RuntimeError:
            When **use_fast_math** =True but fast math is not available.
        """
        use_fast_math = kwargs.get('use_fast_math', None)
        if use_fast_math is None:   # Automatic
            if _fastmath is not None:
                self._math = _fastmath
            else:
                self._math = _slowmath

        elif use_fast_math:     # Explicitly select fast math
            if _fastmath is not None:
                self._math = _fastmath
            else:
                raise RuntimeError("fast math module not available")

        else:   # Explicitly select slow math
            self._math = _slowmath

        self.error = self._math.error

        self._default_randfunc = kwargs.get('default_randfunc', None)
        self._current_randfunc = None 
Example #14
Source File: crypto.py    From cracke-dit with MIT License 5 votes vote down vote up
def prf(cls, key, string):
        return HMAC.new(key.contents, string, SHA).digest() 
Example #15
Source File: Util.py    From PyMicroChat with GNU General Public License v3.0 5 votes vote down vote up
def compress_and_rsa(src):
    compressData = zlib.compress(src)
    rsakey = RSA.construct((int(define.__LOGIN_RSA_VER158_KEY_N__, 16), define.__LOGIN_RSA_VER158_KEY_E__))
    cipher = Cipher_pkcs1_v1_5.new(rsakey)
    encrypt_buf = cipher.encrypt(compressData)
    return encrypt_buf

# 不压缩RSA2048加密 
Example #16
Source File: TDES.py    From msldap with MIT License 5 votes vote down vote up
def setup_cipher(self):
		if self.mode == cipherMODE.ECB:
			self._cipher = _pyCryptoDES3.new(self.key, _pyCryptoDES3.MODE_ECB)
		
		elif self.mode == cipherMODE.CBC:
			self._cipher = _pyCryptoDES3.new(self.key, _pyCryptoDES3.MODE_CBC, self.IV)
		else:
			raise Exception('Unknown cipher mode!') 
Example #17
Source File: Util.py    From PyMicroChat with GNU General Public License v3.0 5 votes vote down vote up
def compress_and_aes(src, key):
    compressData = zlib.compress(src)
    aes_obj = AES.new(key, AES.MODE_CBC, key)                                                   # IV与key相同
    encrypt_buf = aes_obj.encrypt(pad(compressData))
    return (encrypt_buf, len(compressData))                                                     # 需要返回压缩后protobuf长度,组包时使用

# 不压缩AES-128-CBC加密 
Example #18
Source File: Util.py    From PyMicroChat with GNU General Public License v3.0 5 votes vote down vote up
def aes(src, key):
    aes_obj = AES.new(key, AES.MODE_CBC, key)                                                   # IV与key相同
    encrypt_buf = aes_obj.encrypt(pad(src))
    return encrypt_buf

# 先压缩后RSA加密 
Example #19
Source File: Util.py    From PyMicroChat with GNU General Public License v3.0 5 votes vote down vote up
def decompress_and_aesDecrypt(src, key):
    aes_obj = AES.new(key, AES.MODE_CBC, key)                                                   # IV与key相同
    decrypt_buf = aes_obj.decrypt(src)
    return zlib.decompress(unpad(decrypt_buf))

# AES-128-CBC解密 
Example #20
Source File: Transform.py    From deprecated-binaryninja-python with GNU General Public License v2.0 5 votes vote down vote up
def aes_encrypt_transform(data, key, mode, iv):
	aes = AES.new(key, mode, iv)
	return aes.encrypt(data) 
Example #21
Source File: crypto.py    From cracke-dit with MIT License 5 votes vote down vote up
def checksum(cls, key, keyusage, text):
        kc = cls.enc.derive(key, pack('>IB', keyusage, 0x99))
        hmac = HMAC.new(kc.contents, text, cls.enc.hashmod).digest()
        return hmac[:cls.macsize] 
Example #22
Source File: mozilla.py    From LaZagneForensic with GNU Lesser General Public License v3.0 5 votes vote down vote up
def decrypt(self, key, iv, ciphertext):
		"""
		Decrypt ciphered data (user / password) using the key previously found
		"""
		data = DES3.new(key, DES3.MODE_CBC, iv).decrypt(ciphertext)
		return self.remove_padding(data) 
Example #23
Source File: crypto.py    From cracke-dit with MIT License 5 votes vote down vote up
def encrypt(cls, key, keyusage, plaintext, confounder):
        if confounder is None:
            confounder = get_random_bytes(8)
        ki = HMAC.new(key.contents, cls.usage_str(keyusage), MD5).digest()
        cksum = HMAC.new(ki, confounder + plaintext, MD5).digest()
        ke = HMAC.new(ki, cksum, MD5).digest()
        return cksum + ARC4.new(ke).encrypt(confounder + plaintext) 
Example #24
Source File: crypto.py    From cracke-dit with MIT License 5 votes vote down vote up
def string_to_key(cls, string, salt, params):
        utf16string = string.decode('UTF-8').encode('UTF-16LE')
        return Key(cls.enctype, MD4.new(utf16string).digest()) 
Example #25
Source File: crypto.py    From cracke-dit with MIT License 5 votes vote down vote up
def basic_encrypt(cls, key, plaintext):
        assert len(plaintext) >= 16
        aes = AES.new(key.contents, AES.MODE_CBC, '\0' * 16)
        ctext = aes.encrypt(_zeropad(plaintext, 16))
        if len(plaintext) > 16:
            # Swap the last two ciphertext blocks and truncate the
            # final block to match the plaintext length.
            lastlen = len(plaintext) % 16 or 16
            ctext = ctext[:-32] + ctext[-16:] + ctext[-32:-16][:lastlen]
        return ctext 
Example #26
Source File: crypto.py    From cracke-dit with MIT License 5 votes vote down vote up
def string_to_key(cls, string, salt, params):
        (iterations,) = unpack('>L', params or '\x00\x00\x10\x00')
        prf = lambda p, s: HMAC.new(p, s, SHA).digest()
        seed = PBKDF2(string, salt, cls.seedsize, iterations, prf)
        tkey = cls.random_to_key(seed)
        return cls.derive(tkey, 'kerberos') 
Example #27
Source File: crypto.py    From cracke-dit with MIT License 5 votes vote down vote up
def basic_decrypt(cls, key, ciphertext):
        assert len(ciphertext) % 8 == 0
        des3 = DES3.new(key.contents, AES.MODE_CBC, '\0' * 8)
        return des3.decrypt(ciphertext) 
Example #28
Source File: crypto.py    From cracke-dit with MIT License 5 votes vote down vote up
def basic_encrypt(cls, key, plaintext):
        assert len(plaintext) % 8 == 0
        des3 = DES3.new(key.contents, AES.MODE_CBC, '\0' * 8)
        return des3.encrypt(plaintext) 
Example #29
Source File: crypto.py    From cracke-dit with MIT License 5 votes vote down vote up
def basic_decrypt(cls, key, ciphertext):
        assert len(ciphertext) % 8 == 0
        des = DES.new(key.contents, DES.MODE_CBC, '\0' * 8)
        return des.decrypt(ciphertext) 
Example #30
Source File: Mozilla.py    From Radium with Apache License 2.0 5 votes vote down vote up
def decrypt3DES(self, globalSalt, masterPassword, entrySalt, encryptedData):
        hp = sha1(globalSalt + masterPassword).digest()
        pes = entrySalt + '\x00' * (20 - len(entrySalt))
        chp = sha1(hp + entrySalt).digest()
        k1 = hmac.new(chp, pes + entrySalt, sha1).digest()
        tk = hmac.new(chp, pes, sha1).digest()
        k2 = hmac.new(chp, tk + entrySalt, sha1).digest()
        k = k1 + k2
        iv = k[-8:]
        key = k[:24]

        return DES3.new(key, DES3.MODE_CBC, iv).decrypt(encryptedData)