Ejemplo n.º 1
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)
Ejemplo n.º 2
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))
Ejemplo n.º 3
0
Archivo: loki.py Proyecto: 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, '-')
Ejemplo n.º 4
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
    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 []
Ejemplo n.º 6
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
Ejemplo n.º 7
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)
Ejemplo n.º 8
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)
Ejemplo n.º 9
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()
Ejemplo n.º 10
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))
Ejemplo n.º 11
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()
Ejemplo n.º 12
0
Archivo: loki.py Proyecto: 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
Ejemplo n.º 13
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])
Ejemplo n.º 14
0
 def test_vector(self, key, cleartext):
     self.cipher = Blowfish(key)
     self.cipher.encrypt(cleartext)
Ejemplo n.º 15
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))
Ejemplo n.º 16
0
def f_function(half_block, subkey):
    bf = Blowfish(subkey)
    result = bf.encrypt(half_block)
    return result
Ejemplo n.º 17
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
Ejemplo n.º 18
0
 def __init__(self, cipher=Blowfish(KEY), filename=".cdb"):
     self.docs = {}
     self.cipher = cipher
     self.filename = filename
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):
Ejemplo n.º 20
0
 def __init__(self, socket):
     self.socket = socket
     self.cipher = Blowfish(KEY)
Ejemplo n.º 21
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))
Ejemplo n.º 22
0
 def __init__(self, key):
     self.key = key
     self.cipher = Blowfish(self.key)
Ejemplo n.º 23
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()