Example #1
2
class UDPSocket(object):
    """Abstraction over socket object. Implements (de)encryption and (de)serialization."""

    def __init__(self, socket):
        self.socket = socket
        self.cipher = Blowfish(KEY)


    def recv(self):
        self.cipher.initCTR()
        yield ReadWait(self.socket) # put socket to waitforread buffer
        packet, addr = self.socket.recvfrom(PACKET_SIZE)
        yield (pickle.loads(self.cipher.decryptCTR(packet)) , addr)
            

    def send(self, packet, addr):
        self.cipher.initCTR()
        #yield WriteWait(self.socket) # put socket to waitforwrite buffer(TCP)
        if len(addr) > 2:
            addr = (addr[0], addr[1])
        self.socket.sendto(self.cipher.encryptCTR(pickle.dumps(packet)), addr)
        

    def close(self):
        self.socket.close()
Example #2
0
File: loki.py Project: gaphex/Hydra
    def encryptFile(self, input_f):
        try:
            key = self.key
            delimiter = self.delimiter
            size=int(self.GetSize(input_f))
            crypt_f=input_f+'.crypt'
            cipher = Blowfish(key)
            print ''
            
            decorate(' Encrypting ' + input_f + '...', 64, '-') 
            with open(input_f,'rb') as f1:
                with open(crypt_f,'wb') as f2:
                    for i in tqdm(range(size)):
                        t= f1.read(1)
                        u = cipher.encrypt(str(base64.b64encode(t)*2))+delimiter
                        f2.write(u)

            f1.close()
            f2.close()
            self.cleanUp(input_f)

        except Exception as e:
            print e, 'exception caught while encrypting', input_f

        finally:
            decorate('Success', 64, '-')
Example #3
0
class AppdataManager(Pyro.core.SynchronizedObjBase):
    def __init__(self,
                 appdataFileName=abspath('data/appdata.xml'),
                 encryptionKey=''):
        PsLogger().info('AppdataTag', 'AppdataManager initialization')
        global _
        _ = lambda translationString: self.translateString(translationString)

        Pyro.core.SynchronizedObjBase.__init__(self)
        self.appdataRoot = None
        self.encryptionKey = encryptionKey
        self.publicCipher = Blowfish(self.encryptionKey)
        self.appdataFileName = appdataFileName

        self.lock = threading.RLock()

    def publicEncryptDecryptString(self, inputValue, operation):
        PsLogger().info('AppdataTag', "publicEncryptDecryptString")
        self.lock.acquire()
        try:
            PsLogger().info('AppdataLockTag', "lock acquired")
            self.publicCipher.initCTR()

            if operation == 'encrypt':
                inputValue = inputValue.encode('utf-8')
                outputValue = self.publicCipher.encryptCTR(inputValue)
            else:
                outputValue = self.publicCipher.decryptCTR(inputValue)
                outputValue = outputValue.decode('utf-8')
        except BaseException, e:
            PsLogger().warning(['AppdataTag', 'ExceptionTag'], str(e))
            outputValue = None
            PsLogger().info('AppdataTag', str(e))
        finally:
Example #4
0
def decrypt_file(fn, offset=0):
    bc = 0
    pb = None
    bf = Blowfish(settings.BLOWFISH_KEY)
    log.info("Decrypting from offset {}".format(offset))
    of = fn + ".tmp"
    with open(fn, 'rb') as f:
        f.seek(offset)
        with open(of, 'wb') as out:
            while True:
                b = f.read(8)
                if not b:
                    break

                if len(b) < 8:
                    b += '\x00' * (8 - len(b))  # pad for correct blocksize

                if bc > 0:
                    db = bf.decrypt(b)
                    if pb:
                        db = ''.join([chr(int(b2a_hex(a), 16) ^ int(b2a_hex(b), 16)) for a, b in zip(db, pb)])

                    pb = db
                    out.write(db)
                bc += 1
            return of
    return None
Example #5
0
def _decrypt_yaml(e_yaml_stream, key):
    """
    Function that does the decryption of the YAML document with the specified key.
    The stream can be any of the types of streams support by the PyYaml module (strings,
    unicode strings, or file objects)
    """
    ##We have to read the file so ensure we can reset it to where it was when passed
    if type(e_yaml_stream) == types.FileType:
        curr_poss = e_yaml_stream.tell()
        e_yaml_data = e_yaml_stream.read()
    else:
        e_yaml_data = e_yaml_stream

    ##Skip first line as it's the magic header
    pos = e_yaml_data.find("\n\n")
    if pos != -1:
        e_yaml_data = e_yaml_data[pos + 2:]

    ##Decrypt stream
    try:
        bfish = Blowfish(key)
        bfish.initCTR()
        yaml_data = bfish.decryptCTR(e_yaml_data)
    except Exception, err:
        raise EncryptedYamlException("Problem decrypting the YAML file - %s" %
                                     (err))
Example #6
0
def decrypt_file(fn, offset=0):
	key = ''.join(['\xDE', '\x72', '\xBE', '\xA0', '\xDE', '\x04', '\xBE', '\xB1', '\xDE', '\xFE', '\xBE', '\xEF', '\xDE', '\xAD', '\xBE', '\xEF'])
	bc = 0
	pb = None
	from blowfish import Blowfish
	from binascii import b2a_hex
	bf = Blowfish(key)
	printmessage("Decrypting from offset {}".format(offset))
	of = fn + ".tmp"
	with open(fn, 'rb') as f:

		f.seek(offset)
		with open(of, 'wb') as out:
			while True:
				b = f.read(8)
				if not b:
					break
	
				if len(b) < 8:
					b += '\x00' * (8 - len(b))  # pad for correct blocksize
	
				if bc > 0:
					db = bf.decrypt(b)
					if pb:
						db = ''.join([chr(int(b2a_hex(a), 16) ^ int(b2a_hex(b), 16)) for a, b in zip(db, pb)])
	
					pb = db
					out.write(db)
				bc += 1
	        return of
	return None
Example #7
0
    def connect(self, client, user, password):
        self.partnerId = self.userId = self.partnerAuthToken = None
        self.userAuthToken = self.time_offset = None

        self.rpcUrl = client['rpcUrl']
        self.blowfish_encode = Blowfish(client['encryptKey'])
        self.blowfish_decode = Blowfish(client['decryptKey'])

        partner = self.json_call('auth.partnerLogin', {
            'deviceModel': client['deviceModel'],
            'username': client['username'], # partner username
            'password': client['password'], # partner password
            'version': client['version']
            },https=True, blowfish=False)

        self.partnerId = partner['partnerId']
        self.partnerAuthToken = partner['partnerAuthToken']

        pandora_time = int(self.pandora_decrypt(partner['syncTime'])[4:14])
        self.time_offset = pandora_time - time.time()
        logging.info("Time offset is %s", self.time_offset)

        user = self.json_call('auth.userLogin', {'username': user, 'password': password, 'loginType': 'user'}, https=True)
        self.userId = user['userId']
        self.userAuthToken = user['userAuthToken']

        self.get_stations(self)
Example #8
0
File: loki.py Project: gaphex/Hydra
    def encryptFile(self, input_f):
        try:
            key = self.key
            delimiter = self.delimiter
            size = int(self.GetSize(input_f))
            crypt_f = input_f + '.crypt'
            cipher = Blowfish(key)
            print ''

            decorate(' Encrypting ' + input_f + '...', 64, '-')
            with open(input_f, 'rb') as f1:
                with open(crypt_f, 'wb') as f2:
                    for i in tqdm(range(size)):
                        t = f1.read(1)
                        u = cipher.encrypt(str(
                            base64.b64encode(t) * 2)) + delimiter
                        f2.write(u)

            f1.close()
            f2.close()
            self.cleanUp(input_f)

        except Exception as e:
            print e, 'exception caught while encrypting', input_f

        finally:
            decorate('Success', 64, '-')
    def _getRemote(self, method, params={}):
        postData = {
            "method": method,
            "sessionid": self._sessionID,
            "parameters": params
        }
        postData = simplejson.dumps(postData)

        cipher = Blowfish(self._key)
        cipher.initCTR()
        encryptedPostData = cipher.encryptCTR(postData)
        encryptedPostData = base64.urlsafe_b64encode(encryptedPostData)
        url = WEB_APP_URL + "?postData=" + encryptedPostData
        req = urllib2.Request(url)
        response = urllib2.urlopen(req)
        result = response.read()
        if self._debugging:
            print "Request..."
            pprint.pprint(result)
        response.close()
        try:
            result = simplejson.loads(result)
            return result
        except:
            return []
def decrypt_file(fn, offset=0):
	key = ''.join(['\xDE', '\x72', '\xBE', '\xA0', '\xDE', '\x04', '\xBE', '\xB1', '\xDE', '\xFE', '\xBE', '\xEF', '\xDE', '\xAD', '\xBE', '\xEF'])
	bc = 0
	pb = None
	from blowfish import Blowfish
	from binascii import b2a_hex
	bf = Blowfish(key)
	printmessage("Decrypting from offset {}".format(offset))
	of = fn + ".tmp"
	with open(fn, 'rb') as f:
	    f.seek(offset)
	    with open(of, 'wb') as out:
	        while True:
	            b = f.read(8)
	            if not b:
	                break
	
	            if len(b) < 8:
	                b += '\x00' * (8 - len(b))  # pad for correct blocksize
	
	            if bc > 0:
	                db = bf.decrypt(b)
	                if pb:
	                    db = ''.join([chr(int(b2a_hex(a), 16) ^ int(b2a_hex(b), 16)) for a, b in zip(db, pb)])
	
	                pb = db
	                out.write(db)
	            bc += 1
	        return of
	return None
Example #11
0
class Crypto:
    def __init__(self, key):
        self.key = key
        self.cipher = Blowfish(self.key)
        
    def encrypt(self, data):
        return "".join([self.cipher.encrypt(pad(data[i:i + 8], 8)).encode('hex') for i in xrange(0, len(data), 8)])
    
    def decrypt(self, data):
        return "".join([self.cipher.decrypt(pad(data[i:i + 16].decode('hex'), 8)) for i in xrange(0, len(data), 16)]).rstrip('\x08')
Example #12
0
class BCipher:

    prefix = "CRYP="

    def __init__(self, key=None):
        if not key:
            key = getattr(settings, "CIPHER_KEY", settings.SECRET_KEY)
        if len(key) < 8:
            raise Exception("Key length must be greater than 8")
        self.__cipher = Blowfish(key)

    def encrypt(self, text):
        padtext = self.__pad_text(text)
        res = []
        for n in range(0, len(padtext), 8):
            part = padtext[n : n + 8]
            res.append(self.__cipher.encrypt(part))
        ciphertext = "".join(res)
        return self.prefix + base64.b64encode(ciphertext)

    def decrypt(self, b64text):
        if not b64text.startswith(self.prefix):
            return b64text
        enctext = b64text[len(self.prefix) :]
        try:
            ciphertext = base64.b64decode(enctext)
        except TypeError:
            # text is not encrypted
            return enctext
        res = []
        for n in range(0, len(ciphertext), 8):
            part = ciphertext[n : n + 8]
            res.append(self.__cipher.decrypt(part))
        cleartext = "".join(res)
        return self.__depad_text(cleartext)

    # Blowfish cipher needs 8 byte blocks to work with
    def __pad_text(self, text):
        pad_bytes = 8 - (len(text) % 8)
        # try to deal with unicode strings
        asc_text = str(text)
        for i in range(pad_bytes - 1):
            asc_text += chr(randrange(0, 256))
        # final padding byte; % by 8 to get the number of padding bytes
        bflag = randrange(6, 248)
        bflag -= bflag % 8 - pad_bytes
        asc_text += chr(bflag)
        return asc_text

    def __depad_text(self, text):
        pad_bytes = ord(text[-1]) % 8
        if not pad_bytes:
            pad_bytes = 8
        return text[:-pad_bytes]
Example #13
0
def main():

    pt = "Hi There!!!"
    print(pt)
    blowfish = Blowfish("dsadasdasda", pt)
    ct = blowfish.encrypt(pt)
    print(ct)
    StegEncrypt("tiger.png", ct, "enc_tiger.png")

    ct = StegDecrypt("enc_tiger.png")
    pt = blowfish.decrypt(ct)
    print(pt)
Example #14
0
def encrypt(args, eurikey = None):
	import blowfish.Blowfish
	pkey = 'JE87z39322aiscpqpzx94KJ29SN400mndhqn7198zfgQQAZMKLP6478A'
	if eurikey: pkey = eurikey
	cipher = Blowfish(pkey)

	# create the URI
	al = []
	for (k,v) in args.itervalues():
		al.append( k + "=" + v )
	arg_string = string.join(al,"&")

	return cipher.encrypt(arg_string)
Example #15
0
class TestRunningTime(unittest.TestCase):
    def setUp(self):
        self.n = 1

    def test_ntimes(self):
        zero_key = bytearray(b'\x00' * Blowfish.keySize())
        self.cipher = Blowfish(zero_key)
        for i in range(self.n):
            self.test_once()

    def test_once(self):
        zero_block = bytearray(b'\x00' * Blowfish.blockSize())
        self.cipher.encrypt(zero_block)
Example #16
0
class TestVectors(unittest.TestCase):
    def setUp(self):
        pass

    def test_all(self):
        for key, cleartext, ciphertext in [
                ('0000000000000000', '0000000000000000', '4EF997456198DD78'),
                ('FFFFFFFFFFFFFFFF', 'FFFFFFFFFFFFFFFF', '51866FD5B85ECB8A'),
                ('3000000000000000', '1000000000000001', '7D856F9A613063F2'),
                ('1111111111111111', '1111111111111111', '2466DD878B963C9D'),
                ('0123456789ABCDEF', '1111111111111111', '61F9C3802281B096'),
                ('1111111111111111', '0123456789ABCDEF', '7D0CC630AFDA1EC7'),
                ('0000000000000000', '0000000000000000', '4EF997456198DD78'),
                ('FEDCBA9876543210', '0123456789ABCDEF', '0ACEAB0FC6A0A28D'),
                ('7CA110454A1A6E57', '01A1D6D039776742', '59C68245EB05282B'),
                ('0131D9619DC1376E', '5CD54CA83DEF57DA', 'B1B8CC0B250F09A0'),
                ('07A1133E4A0B2686', '0248D43806F67172', '1730E5778BEA1DA4'),
                ('3849674C2602319E', '51454B582DDF440A', 'A25E7856CF2651EB'),
                ('04B915BA43FEB5B6', '42FD443059577FA2', '353882B109CE8F1A'),
                ('0113B970FD34F2CE', '059B5E0851CF143A', '48F4D0884C379918'),
                ('0170F175468FB5E6', '0756D8E0774761D2', '432193B78951FC98'),
                ('43297FAD38E373FE', '762514B829BF486A', '13F04154D69D1AE5'),
                ('07A7137045DA2A16', '3BDD119049372802', '2EEDDA93FFD39C79'),
                ('04689104C2FD3B2F', '26955F6835AF609A', 'D887E0393C2DA6E3'),
                ('37D06BB516CB7546', '164D5E404F275232', '5F99D04F5B163969'),
                ('1F08260D1AC2465E', '6B056E18759F5CCA', '4A057A3B24D3977B'),
                ('584023641ABA6176', '004BD6EF09176062', '452031C1E4FADA8E'),
                ('025816164629B007', '480D39006EE762F2', '7555AE39F59B87BD'),
                ('49793EBC79B3258F', '437540C8698F3CFA', '53C55F9CB49FC019'),
                ('4FB05E1515AB73A7', '072D43A077075292', '7A8E7BFA937E89A3'),
                ('49E95D6D4CA229BF', '02FE55778117F12A', 'CF9C5D7A4986ADB5'),
                ('018310DC409B26D6', '1D9D5C5018F728C2', 'D1ABB290658BC778'),
                ('1C587F1C13924FEF', '305532286D6F295A', '55CB3774D13EF201'),
                ('0101010101010101', '0123456789ABCDEF', 'FA34EC4847B268B2'),
                ('1F1F1F1F0E0E0E0E', '0123456789ABCDEF', 'A790795108EA3CAE'),
                ('E0FEE0FEF1FEF1FE', '0123456789ABCDEF', 'C39E072D9FAC631D'),
                ('0000000000000000', 'FFFFFFFFFFFFFFFF', '014933E0CDAFF6E4'),
                ('FFFFFFFFFFFFFFFF', '0000000000000000', 'F21E9A77B71C49BC'),
                ('0123456789ABCDEF', '0000000000000000', '245946885754369A'),
                ('FEDCBA9876543210', 'FFFFFFFFFFFFFFFF', '6B5C5A9C5D9E0A5A')]:
            key = bytes.fromhex(key)
            cleartext = bytes.fromhex(cleartext)
            ciphertext = bytes.fromhex(ciphertext)

            self.test_vector(key, cleartext) # in-place encrypt
            print(hex(struct.unpack('>Q',cleartext)[0]))
            self.assertEqual(cleartext, ciphertext)

    def test_vector(self, key, cleartext):
        self.cipher = Blowfish(key)
        self.cipher.encrypt(cleartext)
Example #17
0
    def __init__(self,
                 appdataFileName=abspath('data/appdata.xml'),
                 encryptionKey=''):
        PsLogger().info('AppdataTag', 'AppdataManager initialization')
        global _
        _ = lambda translationString: self.translateString(translationString)

        Pyro.core.SynchronizedObjBase.__init__(self)
        self.appdataRoot = None
        self.encryptionKey = encryptionKey
        self.publicCipher = Blowfish(self.encryptionKey)
        self.appdataFileName = appdataFileName

        self.lock = threading.RLock()
Example #18
0
 def key_prepare(self, key, encryption_key, store=True):
     key_crypt = key
     if encryption_key is not None:
         try:
             engine = Blowfish(encryption_key)
             engine.initCTR()
             key_crypt = engine.encryptCTR(key)
         except:
             pass
     try:
         if store:
             key_ready = base64.standard_b64encode(key_crypt)
         else:
             key_ready = base64.standard_b64decode(key_crypt)
     except:
         key_ready = key_crypt
     return key_ready
Example #19
0
def _encrypt_yaml(yaml_stream, key):
    """
    Function that does the encryption of the YAML document with the specified key.
    The stream is always a string object.
    Return the encrypted version of the string with the ENCRYPTED_YAML_HEADER prepended.
    """
    ##Blow the fish
    try:
        bfish = Blowfish(key)
        bfish.initCTR()
        crypto_yaml = bfish.encryptCTR(yaml_stream)

        ##Add in our header to indicate we're encrypted
        crypto_yaml = "%s%s" % (ENCRYPTED_YAML_HEADER, crypto_yaml)

    except Exception, err:
        raise EncryptedYamlException("Problem encrypting the YAML file - %s" %
                                     (err))
Example #20
0
File: loki.py Project: gaphex/Hydra
    def decryptFile(self, crypt_f):
        key = self.key
        delimiter = self.delimiter
        c_file = crypt_f + '.crypt'
        if os.path.isfile(c_file):
            try:
                cipher = Blowfish(key)

                decorate(' Decrypting ' + c_file + '...', 64, '-')
                with open(c_file, 'rb') as f1:
                    with open(crypt_f, 'wb') as f2:
                        dt = f1.read().split(delimiter)
                        tot = len(dt) - 1
                        for i in tqdm(range(tot)):

                            f2.write(
                                (base64.b64decode(cipher.decrypt(dt[i])[4:])))
                f1.close()
                f2.close()

                decorate('Success', 64, '-')

            except Exception as e:
                if str(e) == 'Incorrect padding':
                    print 'ACCESS DENIED'
                    self.retryDecrypting(crypt_f)
                else:
                    print e, 'exception caught while decrypting', crypt_f
        elif os.path.isfile(crypt_f):
            print 'encrypting keychain with a new key...'
            new_pass = raw_input('enter new pass --->>')
            if isinstance(new_pass, str):
                try:
                    self.key = new_pass
                    self.encryptFile(crypt_f)
                    self.retryDecrypting(crypt_f)
                except Exception as e:
                    print e
Example #21
0
File: loki.py Project: gaphex/Hydra
    def decryptFile(self, crypt_f):
        key = self.key
        delimiter = self.delimiter
        c_file = crypt_f + '.crypt'
        if os.path.isfile(c_file):
            try:
                cipher = Blowfish(key)
                
                decorate(' Decrypting ' + c_file + '...', 64, '-')
                with open(c_file, 'rb') as f1:
                    with open(crypt_f, 'wb') as f2:
                        dt = f1.read().split(delimiter)
                        tot = len(dt)-1
                        for i in tqdm(range(tot)):

                            f2.write((base64.b64decode(cipher.decrypt(dt[i])[4:])))
                f1.close()
                f2.close()

                decorate('Success', 64, '-')

            except Exception as e:
                if str(e) == 'Incorrect padding':
                    print 'ACCESS DENIED'
                    self.retryDecrypting(crypt_f)
                else:
                    print e, 'exception caught while decrypting', crypt_f
        elif os.path.isfile(crypt_f):
            print 'encrypting keychain with a new key...'
            new_pass = raw_input('enter new pass --->>')
            if isinstance(new_pass, str):
                try:
                    self.key = new_pass
                    self.encryptFile(crypt_f)
                    self.retryDecrypting(crypt_f)
                except Exception as e:
                    print e
Example #22
0
class Helper:
    blowfish_instance = Blowfish()
    key_schedule_time = 0.000
    encryption_time = 0.000
    decryption_time = 0.000

    @staticmethod
    def initialize_blowfish(key):
        key_array = [ord(x) for x in key]
        start = time.time()
        Helper.blowfish_instance.initialize_blowfish(key_array, len(key_array))
        Helper.key_schedule_time = time.time() - start

    @staticmethod
    def encipher(image_path, key, no_of_cores):
        index = image_path.rindex("/") if "/" in image_path else -1
        image = image_path[index + 1:]
        Helper.initialize_blowfish(key)
        start = time.time()
        Helper.blowfish_instance.encrypt_image(image_path, no_of_cores)
        Helper.encryption_time = time.time() - start
        shutil.move("enciphered_image.jpeg",
                    image_path[:index] + "/enciphered-" + image[:])
        print("Successful, File save in " + image_path[:index])

    @staticmethod
    def decipher(image_path, key, no_of_cores):
        index = image_path.rindex("/") if "/" in image_path else -1
        image = image_path[index + 1:]
        image = image.replace("enciphered-",
                              "") if "enciphered-" in image else image
        Helper.initialize_blowfish(key)
        start = time.time()
        Helper.blowfish_instance.decrypt_image(image_path, no_of_cores)
        Helper.decryption_time = time.time() - start
        shutil.move("deciphered_image.jpeg",
                    image_path[:index] + "/deciphered-" + image[:])
        print("Successful, File save in " + image_path[:index])
Example #23
0
class BlowfishWrapper(object):
    """ Create Blowfish crypto object """
    def __init__(self, key):
        self.name = 'blowfish'
        key_448 = self.__generate448key(key)
        self.blowfish = Blowfish(key_448)
        
    def __generate448key(self, key):
        sha512password = hashlib.sha512(key).digest()
        return sha512password[:56] # Using the first 56 bytes only (448 bits)
        
    def encrypt(self, message):
        self.blowfish.initCTR()
        return self.blowfish.encryptCTR(message)

    def decrypt(self, encrypted):
        self.blowfish.initCTR()
        return self.blowfish.decryptCTR(encrypted)
Example #24
0
def main(mode, key, infile, outfile):

    cipher = Blowfish(bytearray.fromhex(key))
    text = infile.read()

    size = Blowfish.blockSize()

    for i in range(0, len(text), size):
        block = bytearray(text[i:(i + size)])

        if len(block) < size:
            for _ in range(size - len(block)):
                block.append(0)

        if mode == MODE_ENCRYPT:
            cipher.encrypt(block)

        elif mode == MODE_DECRYPT:
            cipher.decrypt(block)

        outfile.write(block)
        outfile.flush()
Example #25
0
class UDPSocket(object):
    """Abstraction over socket object. Implements (de)encryption and (de)serialization."""
    def __init__(self, socket):
        self.socket = socket
        self.cipher = Blowfish(KEY)

    def recv(self):
        self.cipher.initCTR()
        yield ReadWait(self.socket)  # put socket to waitforread buffer
        packet, addr = self.socket.recvfrom(PACKET_SIZE)
        yield (pickle.loads(self.cipher.decryptCTR(packet)), addr)

    def send(self, packet, addr):
        self.cipher.initCTR()
        #yield WriteWait(self.socket) # put socket to waitforwrite buffer(TCP)
        if len(addr) > 2:
            addr = (addr[0], addr[1])
        self.socket.sendto(self.cipher.encryptCTR(pickle.dumps(packet)), addr)

    def close(self):
        self.socket.close()
Example #26
0
def main(mode, key, infile, outfile):

    cipher = Blowfish(bytearray.fromhex(key))
    text = infile.read()
    
    size = Blowfish.blockSize()
    
    for i in range(0,len(text),size):
        block = bytearray(text[i:(i+size)])
        
        if len(block)<size:
            for _ in range(size-len(block)):
                block.append(0)
        
        if mode==MODE_ENCRYPT:
            cipher.encrypt(block)
                    
        elif mode==MODE_DECRYPT:
            cipher.decrypt(block)
    
        outfile.write(block)
        outfile.flush()
Example #27
0
    def __init__(self, key):
        Blowfish.__init__(self, key)
        ORIG_P = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

        self._keygen(key, ORIG_P)
Example #28
0
	text = ''
	decrypt = False
	for o, a in opts:
		if o in ("-m", "--message"):
			text = a
		elif o in ("-k", "--key"):
			key = a
			keylen = len(key)
			if keylen not in (8,16,24,32,40,48,56):
				print "\tKey must be a multiple of 8 bytes (up to a maximum of 56"
				sys.exit(3)
		elif o in ("-d", "--decrypt"):
			decrypt = True
		else:
			assert False, "unhandled option"
	cipher = Blowfish(key)
	cipher.initCTR()
	if decrypt == False:
		crypted = binascii.hexlify(cipher.encryptCTR(text))
		if (len(crypted) < 140):
			client = twitter.Api(username=twitter_user, password=twitter_password)
			update = client.PostUpdate(crypted)
		else:
			print "\tYour message was too long, it should be less than 140 characters. It was\t", len(crypted)
		print "\tEncrypted message:\t", crypted
	else:
		decrypted = cipher.decryptCTR(binascii.unhexlify(text))
		print "\tDecrypted message:\t", decrypted

def usage():
	print "\tUsage:\t twit.py [--decrypt] --message=\"My message\" --key=key"
Example #29
0
 def test_ntimes(self):
     zero_key = bytearray(b'\x00' * Blowfish.keySize())
     self.cipher = Blowfish(zero_key)
     for i in range(self.n):
         self.test_once()
Example #30
0
 def test_vector(self, key, cleartext):
     self.cipher = Blowfish(key)
     self.cipher.encrypt(cleartext)
Example #31
0
    def __init__(self, key):
        Blowfish.__init__(self, key)
        ORIG_P = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

        self._keygen(key, ORIG_P)
Example #32
0
 def __init__(self, cipher=Blowfish(KEY), filename=".cdb"):
     self.docs = {}
     self.cipher = cipher
     self.filename = filename
Example #33
0
def encrypt_data_if_needed(data_to_hide, cipher_key):
    if cipher_key:
        cipher = Blowfish(cipher_key)
        return cipher.encryptCTR(data_to_hide)
    else:
        return data_to_hide
Example #34
0
 def __init__(self, socket):
     self.socket = socket
     self.cipher = Blowfish(KEY)
Example #35
0
 def __init__(self, socket):
     self.socket = socket
     self.cipher = Blowfish(KEY)
Example #36
0
 def __init__(self, key):
     self.name = 'blowfish'
     key_448 = self.__generate448key(key)
     self.blowfish = Blowfish(key_448)
Example #37
0
def encrypt(unencoded_str):
	b = Blowfish(greentea_gingerale)
	b.initCTR()
	return b64encode(b.encryptCTR(unencoded_str))
Example #38
0
 def __init__(self, key=None):
     if not key:
         key = getattr(settings, "CIPHER_KEY", settings.SECRET_KEY)
     if len(key) < 8:
         raise Exception("Key length must be greater than 8")
     self.__cipher = Blowfish(key)
Example #39
0
def decrypt(encoded_str):
	b = Blowfish(greentea_gingerale)
	b.initCTR()
	return b.decryptCTR(b64decode(encoded_str))
Example #40
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 16 05:24:54 2020

@author: deepak
"""

from blowfish import Blowfish
from time import time

#create object and initialize blowfish with 8 keys (parameter 1) and no. of keys (parameter 2)
bf = Blowfish()
key = 'This is a key'
key_array = [ord(x) for x in key]
t = time.time()
bf.initialize_blowfish(key_array, len(key_array))
print(time.time() - t)

print("time to encrypt = ", bf.encrypt_image("Mahi.jpeg", 4))
def f_function(half_block, subkey):
    bf = Blowfish(subkey)
    result = bf.encrypt(half_block)
    return result
Example #42
0
from blowfish import Blowfish

if __name__ == '__main__':
    if not Blowfish.testVectors():
        print "WARNING: The implementation doesn't pass algorithm test vectors!"
    else:
        print "The implementation passes algorithm test vectors (ECB)."

    key = open("key.txt", "r").read()
    cipher = Blowfish(key)

    # print "Testing block encrypt:"
    # text = 'testtest'
    # print "\tText:\t\t%s" % text
    # crypted = cipher.encrypt(text)
    # print "\tEncrypted:\t%s" % repr(crypted)
    # decrypted = cipher.decrypt(crypted)
    # print "\tDecrypted:\t%s" % decrypted

    print "Testing CTR encrypt:"
    cipher.initCTR()
    text = str(open("input.txt", "r").read())
    print "\tText:\t\t", text
    crypted = cipher.encryptCTR(text)
    print "\tEncrypted:\t", repr(crypted)
    cipher.initCTR()
    decrypted = cipher.decryptCTR(crypted)
    print "\tDecrypted:\t", decrypted
Example #43
0
# Usage of blowfish:
# plaintext = "The quick brown fox jumped over the lazy dog."
# blowfish = new Blowfish("key", plaintext)
#
# cyphertext = blowfish.encrypt(plaintext)
# print(cyphertext)
# plaintext = blowfish.decrypt(cyphertext)
# print(plaintext)
from blowfish import Blowfish

pt = "Nedim"

print('The plaintext is: {}'.format(pt))

blowfish = Blowfish("dsadasdasda", pt)
ct = blowfish.encrypt(pt)
print('The ciphertext is: {}'.format(ct))
pt = blowfish.decrypt(ct)
print('The decrypted ciphertext is: {}'.format(pt))
Example #44
0
def decrypt(key, edata):
    h = hashlib.sha1()
    h.update(key)
    cipher = Blowfish(h.hexdigest())
    cipher.initCTR()
    return cipher.decryptCTR(edata)
PLAYLIST_VALIDITY_TIME = 60*60*3

class PandoraError(IOError):
    def __init__(self, message, status=None, submsg=None):
        self.status = status
        self.message = message
        self.submsg = submsg

class PandoraAuthTokenInvalid(PandoraError): pass
class PandoraNetError(PandoraError): pass
class PandoraAPIVersionError(PandoraError): pass
class PandoraTimeout(PandoraNetError): pass


blowfish_encode = Blowfish(pandora_keys.out_key_p, pandora_keys.out_key_s)

def pad(s, l):
    return s + "\0" * (l - len(s))

def pandora_encrypt(s):
    return "".join([blowfish_encode.encrypt(pad(s[i:i+8], 8)).encode('hex') for i in xrange(0, len(s), 8)])

blowfish_decode = Blowfish(pandora_keys.in_key_p, pandora_keys.in_key_s)

def pandora_decrypt(s):
    return "".join([blowfish_decode.decrypt(pad(s[i:i+16].decode('hex'), 8)) for i in xrange(0, len(s), 16)]).rstrip('\x08')


class Pandora(object):
    def __init__(self):
Example #46
0
 def test_once(self):
     zero_block = bytearray(b'\x00' * Blowfish.blockSize())
     self.cipher.encrypt(zero_block)
Example #47
0
 def __init__(self, key):
     self.key = key
     self.cipher = Blowfish(self.key)
Example #48
0
def decrypt_data(decoded_data, cipher_key):
    cipher_decrypt = Blowfish(cipher_key)
    return cipher_decrypt.decryptCTR(decoded_data)