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()
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:
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_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))
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
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)
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))
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()
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" print "\tOptions can also be passed in short form as [-d] -m and -k"
def decrypt(key, edata): h = hashlib.sha1() h.update(key) cipher = Blowfish(h.hexdigest()) cipher.initCTR() return cipher.decryptCTR(edata)
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
def encrypt(unencoded_str): b = Blowfish(greentea_gingerale) b.initCTR() return b64encode(b.encryptCTR(unencoded_str))
def decrypt(encoded_str): b = Blowfish(greentea_gingerale) b.initCTR() return b.decryptCTR(b64decode(encoded_str))