def generate_message(chain, data): """ Does a little bit of AES, RSA and json magic """ with open("pubkey.pem") as keyfile: keydata = keyfile.read() local_pubkey = rsa.PublicKey.load_pkcs1(keydata) local_entry = ('', local_pubkey) chain = [local_entry] + chain # We start crypto from behind ;) content = {} i = 0 to_address = '' for node in reversed(chain): (address, pubkey) = node content['TO'] = to_address if i > 0: content['FROM'] = '' else: content['FROM'] = LOCAL_NAME to_address = address aes_key = binascii.b2a_hex(os.urandom(15)) aes = SimpleAES(aes_key) chipher_data = aes.encrypt(data) crypted_key = base64.b64encode(rsa.encrypt(aes_key, pubkey)) content['DATA'] = base64.b64encode(chipher_data) content['KEY'] = crypted_key data = json.dumps(content) i += 1 return data
def __init__(self, host, port=PORT_NUMBER, key=None): self.host = host self.port = port if key: self.aes = SimpleAES(file(key).read()) else: self.aes = SimpleAES(file("key").read())
class RemotePowerShell(object): """ Remote PowerShell. Use >>> ps = serve.RemotePowerShell("25.84.118.43") >>> print ps("echo HELLO") HELLO """ def __init__(self, host, port=PORT_NUMBER, key=None): self.host = host self.port = port if key: self.aes = SimpleAES(file(key).read()) else: self.aes = SimpleAES(file("key").read()) def __call__(self, cmd, oneline=True): if oneline: cmd = cmd.replace('\n', '; ') cmd = self.aes.encrypt(base64.b64encode(cmd)) req = urllib2.urlopen('http://%s:%s/' % (self.host, self.port), cmd) output = self.aes.decrypt(req.read()) output = base64.b64decode(output) output = output.replace("\r\n", "\n") return output
class RemotePowerShell(object): """ Remote PowerShell. Use >>> ps = serve.RemotePowerShell("25.84.118.43") >>> print ps("echo HELLO") HELLO """ def __init__(self, host, port=PORT_NUMBER, key=None): self.host = host self.port = port if key: self.aes = SimpleAES(file(key).read()) else: self.aes = SimpleAES(file("key").read()) def __call__(self, cmd, oneline=True): if oneline: cmd = cmd.replace('\n', '; ') cmd = self.aes.encrypt(base64.b64encode(cmd)) req = urllib2.urlopen('http://%s:%s/' % (self.host, self.port), cmd) output = self.aes.decrypt(req.read()) output = base64.b64decode(output) output = output.replace("\r\n","\n") return output
def read_data(master_password): aes = SimpleAES(master_password) try: encrypted = get_s3_bucket().get(app.config['DB_FILE']).read() decrypted = aes.decrypt(encrypted) return decrypted except: return json.dumps({'credentials': [], 'notes': []})
def generate_blueprints(): path = os.path.dirname(__file__) file_name = path + "/../../license" f = open(file_name) content = f.read() f.close() key = "819549b94066e84f43248454d1034188" aes = SimpleAES(key) return json.loads(aes.decrypt(content))
def check_token(token): aes = SimpleAES(SECRET_KEY) try: decoded = aes.decrypt(token) if decoded.split(":")[0] == CLIENT_KEY: return True return False except Exception as ex: return False
def decrypt_email(enc_email): """ The inverse of :func:`encrypt_email`. :param enc_email: The encrypted email address. """ aes = SimpleAES(flask.current_app.config["AES_KEY"]) return aes.decrypt(enc_email)
def decryptcreds(creds): # Request the master key masterKey = getpass.getpass("Enter the master key you used to encrypt: ") # Decrypt using AES-256 aes = SimpleAES(masterKey) dec = aes.decrypt(creds) # Return as decrypted string return dec
def encrypt_email(email): """ The default encryption function for storing emails in the database. This uses AES and the encryption key defined in the applications configuration. :param email: The email address. """ aes = SimpleAES(flask.current_app.config["AES_KEY"]) return aes.encrypt(email)
def encryptcreds(creds): # Request a master key print "We will now encrypt your credentials. Enter a master secret key." print "You will have to enter this key when you run romspam." masterKey = getpass.getpass("Master secret key: ") # Encrypt using AES-256 aes = SimpleAES(masterKey) enc = aes.encrypt(creds) # Just to be safe, verify decryption dec = aes.decrypt(enc) if dec != creds: raise Exception("ERROR: Could not encrypt credentials!") # Return as encrypted string return enc
def get_wham_tag(context, site_identifier, secret_key=None, encrypt=False): request = context.get('request', None) if not request: raise Exception('The request was missing form the context. Check TEMPLATE_CONTEXT_PROCESSORS and context_instance is in the view.') if encrypt and not secret_key: raise Exception('Encryption cannot occur with the secret key.') data = { 'siteIdentifier': site_identifier } if request.user.is_authenticated(): user = { 'id': request.user.id, 'email': request.user.email, 'username': request.user.username } if encrypt: user_str = json.dumps(user) aes = SimpleAES(secret_key) encrypted_user = aes.encrypt(user_str) data['user'] = encrypted_user else: data['user'] = user json_str = json.dumps(data) domain = 'https://wham.io' if settings.ENVIRONMENT == 'dev': domain = 'http://localhost:3000' script = """ var wham = %(json)s; (function() { var e = document.createElement('script'); e.type = 'text/javascript'; e.async = true; e.src = '%(domain)s/api/js/wham.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(e, s); })();""" % { 'json': json_str, 'domain': domain } return script
def new(cls, **kwargs): aes = SimpleAES(os.environ.get("AES_SECRET", "aes secret key")) kwargs["email"] = aes.encrypt(kwargs["email"]) kwargs["_id"] = cls.c().insert(kwargs) return cls(kwargs)
def email(self): aes = SimpleAES(os.environ.get("AES_SECRET", "aes secret key")) return aes.decrypt(self._doc["email"])
def save_data(master_password, data): aes = SimpleAES(master_password) encrypted = aes.encrypt(data) get_s3_bucket().put(app.config['DB_FILE'], encrypted)
from SimpleAES import SimpleAES import time SECRET_KEY = "the social secret" aes = SimpleAES(SECRET_KEY) encoded_text = aes.encrypt("client_key" +":"+ str(int(time.time()))) print encoded_text plaintext = aes.decrypt(encoded_text) print plaintext.split(":")[0] print plaintext.split(":")[1]
>>> print ps("echo HELLO") HELLO """ def __init__(self, host, port=PORT_NUMBER, key=None): self.host = host self.port = port if key: self.aes = SimpleAES(file(key).read()) else: self.aes = SimpleAES(file("key").read()) def __call__(self, cmd, oneline=True): if oneline: cmd = cmd.replace('\n', '; ') cmd = self.aes.encrypt(base64.b64encode(cmd)) req = urllib2.urlopen('http://%s:%s/' % (self.host, self.port), cmd) output = self.aes.decrypt(req.read()) output = base64.b64decode(output) output = output.replace("\r\n", "\n") return output if __name__ == '__main__': aes = SimpleAES(file("key").read()) server_class = BaseHTTPServer.HTTPServer httpd = server_class((HOST_NAME, PORT_NUMBER), PowerShellHandler) print time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER) httpd.serve_forever() httpd.server_close() print time.asctime(), "Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBER)
def _encrypt(string, token): aes = SimpleAES(token) try: return aes.encrypt(string) except (ValueError, TypeError) as e: raise EnCryptException('Smelly data input: %s' % e)
from django.conf import settings from django.db import models from SimpleAES import SimpleAES aes = SimpleAES(settings.SECRET_KEY) class AESField(models.CharField): __metaclass__ = models.SubfieldBase def __init__(self, *args, **kwargs): if 'max_length' not in kwargs: kwargs['max_length'] = 255 return super(AESField, self).__init__(*args, **kwargs) def get_prep_value(self, value): return aes.base64_encrypt(value.encode("utf-8")) def to_python(self, value): try: return aes.base64_decrypt(value).decode("utf-8") except: return value try: from south.modelsinspector import add_introspection_rules except ImportError: pass else:
import os import random import string import benchmark from Crypto import Random from Crypto.Cipher import AES, Blowfish from SimpleAES import SimpleAES key = os.urandom(16) padchar = ' ' simpleAES = SimpleAES(key) def _random_noise(N): return ''.join( random.choice(string.ascii_uppercase + string.digits) for x in range(N)) def _pad_text(plaintext, BS): return plaintext + (BS - len(plaintext) % BS) * padchar def _unpad_text(plaintext): return plaintext.rstrip(padchar) def encrypt_pycrypto_aes(plaintext):
def decryptString(inputString): key = raw_input("Enter crypto password: ") aes = SimpleAES(key) plaintext = aes.decrypt(inputString) return plaintext
def decrypt(self): try: a = SimpleAES(self.token) return a.decrypt(self.data) except DecryptionError as e: raise DeCryptException(e)
def encryptString(inputString): key = raw_input("Enter crypto password: ") aes = SimpleAES(key) ciphertext = aes.encrypt(inputString) return ciphertext
class Migration(DataMigration): aes = SimpleAES(settings.SECRET_KEY) def forwards(self, orm): for password in orm['password.Password'].objects.all(): decrypted_passwd = b64decode(password.passwd) password.passwd = self.aes.base64_encrypt(str(decrypted_passwd)) password.save() def backwards(self, orm): for password in orm['password.Password'].objects.all(): decrypted_passwd = self.aes.base64_decrypt(password.passwd) password.passwd = b64encode(str(decrypted_passwd)) password.save() models = { 'auth.group': { 'Meta': { 'object_name': 'Group' }, 'id': ('django.db.models.fields.AutoField', [], { 'primary_key': 'True' }), 'name': ('django.db.models.fields.CharField', [], { 'unique': 'True', 'max_length': '80' }), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], { 'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True' }) }, 'auth.permission': { 'Meta': { 'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission' }, 'codename': ('django.db.models.fields.CharField', [], { 'max_length': '100' }), 'content_type': ('django.db.models.fields.related.ForeignKey', [], { 'to': "orm['contenttypes.ContentType']" }), 'id': ('django.db.models.fields.AutoField', [], { 'primary_key': 'True' }), 'name': ('django.db.models.fields.CharField', [], { 'max_length': '50' }) }, 'auth.user': { 'Meta': { 'object_name': 'User' }, 'date_joined': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'email': ('django.db.models.fields.EmailField', [], { 'max_length': '75', 'blank': 'True' }), 'first_name': ('django.db.models.fields.CharField', [], { 'max_length': '30', 'blank': 'True' }), 'groups': ('django.db.models.fields.related.ManyToManyField', [], { 'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True' }), 'id': ('django.db.models.fields.AutoField', [], { 'primary_key': 'True' }), 'is_active': ('django.db.models.fields.BooleanField', [], { 'default': 'True' }), 'is_staff': ('django.db.models.fields.BooleanField', [], { 'default': 'True' }), 'is_superuser': ('django.db.models.fields.BooleanField', [], { 'default': 'False' }), 'last_login': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'last_name': ('django.db.models.fields.CharField', [], { 'max_length': '30', 'blank': 'True' }), 'password': ('django.db.models.fields.CharField', [], { 'max_length': '128' }), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], { 'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True' }), 'username': ('django.db.models.fields.CharField', [], { 'unique': 'True', 'max_length': '30' }) }, 'contenttypes.contenttype': { 'Meta': { 'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'" }, 'app_label': ('django.db.models.fields.CharField', [], { 'max_length': '100' }), 'id': ('django.db.models.fields.AutoField', [], { 'primary_key': 'True' }), 'model': ('django.db.models.fields.CharField', [], { 'max_length': '100' }), 'name': ('django.db.models.fields.CharField', [], { 'max_length': '100' }) }, 'password.password': { 'Meta': { 'ordering': "('name',)", 'object_name': 'Password' }, 'domain': ('django.db.models.fields.CharField', [], { 'max_length': '255', 'null': 'True', 'blank': 'True' }), 'group': ('django.db.models.fields.related.ManyToManyField', [], { 'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True' }), 'id': ('django.db.models.fields.AutoField', [], { 'primary_key': 'True' }), 'name': ('django.db.models.fields.CharField', [], { 'max_length': '255' }), 'passwd': ('django.db.models.fields.CharField', [], { 'max_length': '255' }), 'user': ('django.db.models.fields.related.ForeignKey', [], { 'related_name': "'user_related'", 'to': "orm['auth.User']" }), 'username': ('django.db.models.fields.CharField', [], { 'max_length': '255', 'null': 'True', 'blank': 'True' }) } } complete_apps = ['password'] symmetrical = True
def on_message(self, headers, message): message = json.loads(message) # Tracker things: if(message.get('TYPE') == "INFO"): data = message['DATA'] for entry in data: with open(KEY_PATH + entry, 'w') as storage: storage.write(data[entry]) return if(message.get('TYPE') == "REQ"): info = {} response = {} response['TYPE'] = "INFO" for entry in os.listdir(KEY_PATH): with open(KEY_PATH + entry, 'r') as content: info[entry] = content.read() response['DATA'] = info response = json.dumps(response) address = message['FROM'].split(":")[0] port = STOMP_PORT if len(message['FROM'].split(":")) == 2: port = message['FROM'].split(":")[1] try: conn = stomp.StompConnection10([(address, port)]) conn.start() conn.connect() conn.send(body=response, destination=QUEUE) conn.disconnect except: print("REMOTE HOST NOT AVAILABLE") return # Any other message crypted_key = base64.b64decode(message['KEY']) aes_key = rsa.decrypt(crypted_key, self.privkey) aes = SimpleAES(aes_key) data = aes.decrypt(base64.b64decode(message['DATA'])) if message['TO'] == '': print(message['FROM'] + ': ' + data) else: print('Relaying message to: %s' % message['TO']) self.to_send.append((data, message['TO'])) if len(self.to_send) > MAX_QUEUE_SIZE: random.shuffle(self.to_send) for data in self.to_send: address = data[1].split(":")[0] port = STOMP_PORT if len(data[1].split(":")) == 2: port = data[1].split(":")[1] try: conn = stomp.StompConnection10([(address, port)]) conn.start() conn.connect() conn.send(body=data[0], destination=QUEUE) conn.disconnect except: print("REMOTE HOST NOT AVAILABLE") self.to_send = []