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 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()
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" print "\tThe key must be a multiple of 8 bytes (up to a maximum of 56)." if __name__ == "__main__":
def encrypt(key, data): h = hashlib.sha1() h.update(key) cipher = Blowfish(h.hexdigest()) cipher.initCTR() return cipher.encryptCTR(data)
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 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