Python Crypto.Cipher.Blowfish.new() Examples

The following are 30 code examples of Crypto.Cipher.Blowfish.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.Blowfish , 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: 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 #3
Source File: bfcrypt.py    From SecureSnaps with MIT License 6 votes vote down vote up
def encrypt(imagename,password):
    img = Image.open( imagename )
    img.load()
    data = np.asarray( img, dtype="int32" )
    H, W = len(data), len(data[0])
    print(H)
    print(W)
    pixelstring= ""
    for t in data:
        for p in t:
            for i in p:
                pixelstring= pixelstring + str(100+i)
    pixelstring= pixelstring+','+str(H)+','+str(W)
    
    crypt_obj = Blowfish.new(password, Blowfish.MODE_ECB)
    ciphertext = crypt_obj.encrypt(pad_string(pixelstring))

    cipher= open(imagename+'.crypt', 'w')
    cipher.write(ciphertext) 
Example #4
Source File: bfcrypt.py    From SecureSnaps with MIT License 6 votes vote down vote up
def decrypt(ciphername,password):  
    cipher= open(ciphername, 'r')
    ciphertext= cipher.read()

    crypt_obj = Blowfish.new(password, Blowfish.MODE_ECB)
    pixelstring= crypt_obj.decrypt(ciphertext)

    x= pixelstring.split(',')
    H,W= int(x[-2]),int(x[-1])
    pixelstring= x[0]
    pixelstring= [int(pixelstring[i:i+3])-100 for i in range(0, len(pixelstring), 3)]

    data = np.zeros((H, W, 3), dtype=np.uint8)
    c= 0
    for i in range(H):
        for j in range(W):
            data[i,j]= pixelstring[c], pixelstring[c+1], pixelstring[c+2]
            c=c+3

    img = Image.fromarray(data, 'RGB')
    x= ciphername.split('.')
    img.save(x[0]+'_dec.'+x[-2])
    img.show() 
Example #5
Source File: thoughtcrime.py    From fame_modules with GNU General Public License v3.0 6 votes vote down vote up
def run(self, module):
        if not HAVE_PYCRYPTO:
            module.log('warning', 'thoughtcrime: missing dependency: pycrypto')
            return None

        if self.zipfile and 'res/raw/blfs.key' in self.zipfile.namelist() and 'res/raw/config.cfg' in self.zipfile.namelist():
            iv = "12345678"  # this has to be done better
            key = self.zipfile.open('res/raw/blfs.key').read()
            key = ''.join(['%x' % ord(x) for x in key])[0:50]
            cipher = Blowfish.new(key, Blowfish.MODE_CBC, iv)
            decode = base64.b64decode(self.zipfile.open('res/raw/config.cfg').read())
            config = cipher.decrypt(decode)
            config = config[:config.find('</config>') + 9]
            config = ET.fromstring(config)
            c2 = config.findall('.//data')[0].get('url_main').split(';')
            phone = config.findall('.//data')[0].get('phone_number')

            module.add_ioc(c2, ['thoughtcrime', 'c2'])

            return json.dumps({'c2': c2, 'phone': phone}, indent=2)
        else:
            return None 
Example #6
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 #7
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 #8
Source File: thoughtcrime.py    From maldrolyzer with MIT License 6 votes vote down vote up
def extract(self):
		raw_resources = filter(lambda x: x.startswith('res/raw'), self.zipfile.namelist())
		iv = "12345678" # this has to be done better
		key = self.zipfile.open('res/raw/blfs.key').read()
		key = ''.join(['%x' % ord(x) for x in key])[0:50]
		cipher = Blowfish.new(key, Blowfish.MODE_CBC, iv)
		decode = base64.b64decode(self.zipfile.open('res/raw/config.cfg').read())
		config = cipher.decrypt(decode)
		config = config[:config.find('</config>')+9]
		config = ET.fromstring(config)
		c2 = config.findall('.//data')[0].get('url_main').split(';')
		phone = config.findall('.//data')[0].get('phone_number')
		return {'c2': c2, 'phone': phone} 
Example #9
Source File: security.py    From kansha with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def cookie_encode(self, *ids):
        cookie = super(Authentication, self).cookie_encode(*ids)

        bs = Blowfish.block_size
        iv = Random.new().read(bs)
        cipher = Blowfish.new(self.KEY, Blowfish.MODE_CBC, iv)
        # pad cookie to block size.
        # Cookie is ascii base64 + ':', so we can safely pad with '@'.
        missing_bytes = bs - (len(cookie) % bs)
        cookie += '@' * missing_bytes

        return '%s:%s' % (
            b64encode(iv),
            b64encode(cipher.encrypt(cookie))
        )

        return cookie 
Example #10
Source File: data_channel.py    From pyopenvpn with MIT License 6 votes vote down vote up
def encrypt(self, key, iv, plaintext):
        cipher = Blowfish.new(key=key[:self.keysize_bytes], IV=iv, mode=Blowfish.MODE_CBC)
        ciphertext = cipher.encrypt(plaintext)
        return ciphertext 
Example #11
Source File: data_channel.py    From pyopenvpn with MIT License 6 votes vote down vote up
def decrypt(self, key, iv, ciphertext):
        cipher = Blowfish.new(key=key[:self.keysize_bytes], IV=iv, mode=Blowfish.MODE_CBC)
        plaintext = cipher.decrypt(ciphertext)
        return plaintext 
Example #12
Source File: data_channel.py    From pyopenvpn with MIT License 6 votes vote down vote up
def encrypt(self, key, iv, plaintext):
        cipher = AES.new(key=key[:self.keysize_bytes], IV=iv, mode=AES.MODE_CBC)
        ciphertext = cipher.encrypt(plaintext)
        return ciphertext 
Example #13
Source File: data_channel.py    From pyopenvpn with MIT License 6 votes vote down vote up
def decrypt(self, key, iv, ciphertext):
        cipher = AES.new(key=key[:self.keysize_bytes], IV=iv, mode=AES.MODE_CBC)
        plaintext = cipher.decrypt(ciphertext)
        return plaintext 
Example #14
Source File: Transform.py    From deprecated-binaryninja-python with GNU General Public License v2.0 5 votes vote down vote up
def blowfish_encrypt_transform(data, key, mode, iv):
	blowfish = Blowfish.new(key, mode, iv)
	return blowfish.encrypt(data) 
Example #15
Source File: test_Blowfish.py    From FODI with GNU General Public License v3.0 5 votes vote down vote up
def runTest(self):
        self.assertRaises(ValueError, Blowfish.new, bchr(0) * 3,
                          Blowfish.MODE_ECB)
        self.assertRaises(ValueError, Blowfish.new, bchr(0) * 57,
                          Blowfish.MODE_ECB) 
Example #16
Source File: Transform.py    From deprecated-binaryninja-python with GNU General Public License v2.0 5 votes vote down vote up
def blowfish_decrypt_transform(data, key, mode, iv):
	blowfish = Blowfish.new(key, mode, iv)
	return blowfish.decrypt(data) 
Example #17
Source File: Transform.py    From deprecated-binaryninja-python with GNU General Public License v2.0 5 votes vote down vote up
def cast_encrypt_transform(data, key, mode, iv):
	cast = CAST.new(key, mode, iv)
	return cast.encrypt(data) 
Example #18
Source File: Transform.py    From deprecated-binaryninja-python with GNU General Public License v2.0 5 votes vote down vote up
def des_encrypt_transform(data, key, mode, iv):
	des = DES.new(key, mode, iv)
	return des.encrypt(data) 
Example #19
Source File: Transform.py    From deprecated-binaryninja-python with GNU General Public License v2.0 5 votes vote down vote up
def des_decrypt_transform(data, key, mode, iv):
	des = DES.new(key, mode, iv)
	return des.decrypt(data) 
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_decrypt_transform(data, key, mode, iv):
	aes = AES.new(key, mode, iv)
	return aes.decrypt(data) 
Example #21
Source File: Transform.py    From deprecated-binaryninja-python with GNU General Public License v2.0 5 votes vote down vote up
def des3_encrypt_transform(data, key, mode, iv):
	des = DES3.new(key, mode, iv)
	return des.encrypt(data) 
Example #22
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 #23
Source File: cipher.py    From python-proxy with MIT License 5 votes vote down vote up
def setup(self):
        from Crypto.Cipher import CAST
        self.cipher = CAST.new(self.key, CAST.MODE_CFB, iv=self.iv, segment_size=64) 
Example #24
Source File: Transform.py    From deprecated-binaryninja-python with GNU General Public License v2.0 5 votes vote down vote up
def des3_decrypt_transform(data, key, mode, iv):
	des = DES3.new(key, mode, iv)
	return des.decrypt(data) 
Example #25
Source File: Transform.py    From deprecated-binaryninja-python with GNU General Public License v2.0 5 votes vote down vote up
def rc2_encrypt_transform(data, key, mode, iv):
	arc2 = ARC2.new(key, mode, iv)
	return arc2.encrypt(data) 
Example #26
Source File: Transform.py    From deprecated-binaryninja-python with GNU General Public License v2.0 5 votes vote down vote up
def rc4_transform(data, key):
	arc4 = ARC4.new(key)
	return arc4.encrypt(data) 
Example #27
Source File: blowfish.py    From darkc0de-old-stuff with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, pword):
        self.__cipher = Blowfish.new(pword) 
Example #28
Source File: cipher.py    From python-proxy with MIT License 5 votes vote down vote up
def setup(self):
        from Crypto.Cipher import AES
        self.cipher = AES.new(self.key, AES.MODE_CTR, nonce=b'', initial_value=self.iv) 
Example #29
Source File: test_Blowfish.py    From FODI with GNU General Public License v3.0 5 votes vote down vote up
def runTest(self):
        # Encrypt/Decrypt data and test output parameter

        cipher = Blowfish.new(b'4'*16, Blowfish.MODE_ECB)

        pt = b'5' * 16
        ct = cipher.encrypt(pt)

        output = bytearray(16)
        res = cipher.encrypt(pt, output=output)
        self.assertEqual(ct, output)
        self.assertEqual(res, None)
        
        res = cipher.decrypt(ct, output=output)
        self.assertEqual(pt, output)
        self.assertEqual(res, None)

        import sys
        if sys.version[:3] != '2.6':
            output = memoryview(bytearray(16))
            cipher.encrypt(pt, output=output)
            self.assertEqual(ct, output)
        
            cipher.decrypt(ct, output=output)
            self.assertEqual(pt, output)

        self.assertRaises(TypeError, cipher.encrypt, pt, output=b'0'*16)
        self.assertRaises(TypeError, cipher.decrypt, ct, output=b'0'*16)

        shorter_output = bytearray(7)
        self.assertRaises(ValueError, cipher.encrypt, pt, output=shorter_output)
        self.assertRaises(ValueError, cipher.decrypt, ct, output=shorter_output) 
Example #30
Source File: pycarwings2.py    From pycarwings2 with Apache License 2.0 5 votes vote down vote up
def connect(self):
		self.custom_sessionid = None
		self.logged_in = False

		response = self._request("InitialApp.php", {
			"RegionCode": self.region_code,
			"lg": "en-US",
		})
		ret = CarwingsInitialAppResponse(response)

		c1  = Blowfish.new(ret.baseprm, Blowfish.MODE_ECB)
		packedPassword = _PKCS5Padding(self.password)
		encryptedPassword = c1.encrypt(packedPassword)
		encodedPassword = base64.standard_b64encode(encryptedPassword)

		response = self._request("UserLoginRequest.php", {
			"RegionCode": self.region_code,
			"UserId": self.username,
			"Password": encodedPassword,
		})

		ret = CarwingsLoginResponse(response)

		self.custom_sessionid = ret.custom_sessionid

		self.gdc_user_id = ret.gdc_user_id
		log.debug("gdc_user_id: %s" % self.gdc_user_id)
		self.dcm_id = ret.dcm_id
		log.debug("dcm_id: %s" % self.dcm_id)
		self.tz = ret.tz
		log.debug("tz: %s" % self.tz)
		self.language = ret.language
		log.debug("language: %s" % self.language)
		log.debug("vin: %s" % ret.vin)
		log.debug("nickname: %s" % ret.nickname)

		self.leaf = Leaf(self, ret.leafs[0])

		self.logged_in = True

		return ret