Пример #1
0
def minify_website(args):
    css_in = ' '.join(get_css_in(args))
    css_out = f'{args.output_dir}/css/base.css'
    if args.minify:
        command = f"purifycss -w '*algolia*' --min {css_in} '{args.output_dir}/*.html' " \
            f"'{args.output_dir}/docs/en/**/*.html' '{args.website_dir}/js/**/*.js' > {css_out}"
    else:
        command = f'cat {css_in} > {css_out}'
    logging.info(command)
    output = subprocess.check_output(command, shell=True)
    logging.debug(output)
    with open(css_out, 'rb') as f:
        css_digest = hashlib.sha3_224(f.read()).hexdigest()[0:8]

    js_in = get_js_in(args)
    js_out = f'{args.output_dir}/js/base.js'
    if args.minify:
        js_in = [js[1:-1] for js in js_in]
        closure_args = [
            '--js', *js_in, '--js_output_file', js_out, '--compilation_level',
            'SIMPLE', '--dependency_mode', 'NONE', '--third_party',
            '--use_types_for_optimization', '--isolation_mode', 'IIFE'
        ]
        logging.info(closure_args)
        if closure.run(*closure_args):
            raise RuntimeError('failed to run closure compiler')

    else:
        logging.info(command)
        js_in = ' '.join(js_in)
        output = subprocess.check_output(f'cat {js_in} > {js_out}', shell=True)
        logging.debug(output)
    with open(js_out, 'rb') as f:
        js_digest = hashlib.sha3_224(f.read()).hexdigest()[0:8]
        logging.info(js_digest)

    if args.minify:
        logging.info('Minifying website')
        for root, _, filenames in os.walk(args.output_dir):
            for filename in filenames:
                path = os.path.join(root, filename)
                if not (filename.endswith('.html')
                        or filename.endswith('.css')):
                    continue

                logging.info('Minifying %s', path)
                with open(path, 'rb') as f:
                    content = f.read().decode('utf-8')
                if filename.endswith('.html'):
                    content = htmlmin.minify(content, remove_empty_space=False)
                    content = content.replace('base.css?css_digest',
                                              f'base.css?{css_digest}')
                    content = content.replace('base.js?js_digest',
                                              f'base.js?{js_digest}')
                elif filename.endswith('.css'):
                    content = cssmin.cssmin(content)
                elif filename.endswith('.js'):
                    content = jsmin.jsmin(content)
                with open(path, 'wb') as f:
                    f.write(content.encode('utf-8'))
Пример #2
0
def minify_website(args):
    css_in = " ".join(get_css_in(args))
    css_out = f"{args.output_dir}/docs/css/base.css"
    os.makedirs(f"{args.output_dir}/docs/css")

    command = f"cat {css_in}"
    output = subprocess.check_output(command, shell=True)
    with open(css_out, "wb+") as f:
        f.write(output)

    with open(css_out, "rb") as f:
        css_digest = hashlib.sha3_224(f.read()).hexdigest()[0:8]

    js_in = " ".join(get_js_in(args))
    js_out = f"{args.output_dir}/docs/js/base.js"
    os.makedirs(f"{args.output_dir}/docs/js")

    command = f"cat {js_in}"
    output = subprocess.check_output(command, shell=True)
    with open(js_out, "wb+") as f:
        f.write(output)

    with open(js_out, "rb") as f:
        js_digest = hashlib.sha3_224(f.read()).hexdigest()[0:8]
        logging.info(js_digest)
Пример #3
0
def test_duid_mint():

    mhash = hashlib.sha3_224(b"0123456789abcdef").hexdigest()
    dhash = hashlib.sha3_224(b"fedcba9876543210").hexdigest()
    print(mhash)
    print(dhash)

    uid = DcmUIDMint().content_hash_uid(hex_mhash=mhash, hex_dhash=dhash)
    assert uid == "1.2.826.0.1.3680043.10.43.4.62.0.806243101896.283258269229"

    res = DcmUIDMint().hashes_from_duid(uid)
    pprint(res)

    assert res.get("duid") == uid
    assert res.get("dlvl") == DLv.INSTANCE
    assert mhash.startswith(res["mhash_s"])
    assert dhash.startswith(res["dhash_s"])
    assert "namespace" in res
    assert res.get("namespace") == DcmUIDMint.namespace

    uid2 = DcmUIDMint().content_hash_uid(namespace="testing",
                                         hex_mhash=mhash,
                                         dlvl=DLv.STUDY)
    assert uid2 == "1.2.826.0.1.3680043.10.43.4.16.2.806243101896.0"

    res2 = DcmUIDMint().hashes_from_duid(uid2)
    pprint(res2)

    assert res2["dlvl"] == DLv.STUDY
    assert res2['ns_hash'] != res["ns_hash"]
    assert res2["dhash_s"] == "0"
    assert "namespace" not in res2
Пример #4
0
def type_7():
    if verbose == True:
        startTime = time.time()
        with open(wordlist, "r", encoding="ISO-8859-1") as FileObj:
            for line in FileObj:
                passwd1 = line.replace("\n", "")
                passwd_h = hashlib.sha3_224(passwd1.encode())
                passwd_hash = passwd_h.hexdigest()
                print("Trying \"{}\"".format(str(passwd1)))
                if user_hash == passwd_hash:
                    print("[+] Hash cracked! Results: " + str(line))
                    endTime = time.time()
                    deltaTime = endTime - startTime
                    print("[+] Cracking finished in {}s".format(
                        str(format(deltaTime, ".2f"))))
                    sys.exit()
            print("[-] Hash not found! Maybe try an other wordlist.")
            sys.exit()

    else:
        startTime = time.time()
        with open(wordlist, "r", encoding="ISO-8859-1") as FileObj:
            for line in FileObj:
                passwd1 = line.replace("\n", "")
                passwd_h = hashlib.sha3_224(passwd1.encode())
                passwd_hash = passwd_h.hexdigest()
                if user_hash == passwd_hash:
                    print("[+] Hash cracked! Results: " + str(line))
                    endTime = time.time()
                    deltaTime = endTime - startTime
                    print("[+] Cracking finished in {}s".format(
                        str(format(deltaTime, ".2f"))))
                    sys.exit()
            print("[-] Hash not found! Maybe try an other wordlist.")
            sys.exit()
Пример #5
0
def generate_s3_key(user_id, file_name):
    if user_id:
        return hashlib.sha3_224(user_id.encode() +
                                file_name.encode()).hexdigest()
    else:
        return hashlib.sha3_224(
            str(random.randint(1, 2**10)).encode() +
            file_name.encode()).hexdigest()
Пример #6
0
def sha3_224(s=None, f=None):
    if (s != None):
        now = datetime.now()
        time = datetime.strftime(now, "%X")
        time1 = datetime.strftime(now, "%X"
                                  "_"
                                  "%d"
                                  "_"
                                  "%m"
                                  "_"
                                  "%y").replace(":", "_")
        time2 = time1.replace("_", ":")
        hashed = hashlib.sha3_224(s.encode('utf-8')).hexdigest()
        print(
            "\33[36m{}\33[0m \33[32m{}\33[0m".format(time, hashed),
            " \33[30m\33[42m[ Encrypted ]\33[0m \33[0m \33[0m <- {} ".format(
                s), "\n")
        file = open("logs/" + time2 + "--sha3_224-enc.txt",
                    "a",
                    encoding="utf-8".format(time2))
        file.write("""
    LOG DATA :    
    [Encrypted : SHA3_224 ] [ Date : {} ] 
    ------------------------------------------------------------

{} [>] {} """.format(now, s, hashed))
        file.close()

    elif (f != None):
        with open(f, "r", encoding="utf-8") as file:
            for i in file:
                now = datetime.now()
                time = datetime.strftime(now, "%X")
                time1 = datetime.strftime(now, "%X"
                                          "_"
                                          "%d"
                                          "_"
                                          "%m"
                                          "_"
                                          "%y").replace(":", "_")
                time2 = time1.replace("_", ":")
                data = i.replace('\n', '')
                hashed = hashlib.sha3_224(data.encode('utf-8')).hexdigest()
                print(
                    "\33[36m{}\33[0m \33[32m{}\33[0m".format(time, hashed),
                    " \33[30m\33[42m[ Encrypted ]\33[0m \33[0m \33[0m <- {} ".
                    format(data))
                file = open("logs/" + time2 + "--sha3_224-enc.txt",
                            "a",
                            encoding="utf-8".format(time2))
                file.write("""
            LOG DATA :    
            [Encrypted : SHA3_224 ] [ Date : {} ] 
            ------------------------------------------------------------
{} [>] {}\n
        """.format(now, data, hashed))
            file.close()
    print("\n")
Пример #7
0
def word_hash(word):
    # It takes one argument word and will create hash """
    md5 = hashlib.md5(word.encode()).hexdigest()
    sha1 = hashlib.sha1(word.encode()).hexdigest()
    sha224 = hashlib.sha224(word.encode()).hexdigest()
    blake2s = hashlib.blake2s(word.encode()).hexdigest()
    blake2b = hashlib.blake2b(word.encode()).hexdigest()
    sha3_384 = hashlib.sha3_384(word.encode()).hexdigest()
    sha384 = hashlib.sha384(word.encode()).hexdigest()
    sha3_512 = hashlib.sha3_512(word.encode()).hexdigest()
    sha3_224 = hashlib.sha3_224(word.encode()).hexdigest()
    sha512 = hashlib.sha512(word.encode()).hexdigest()
    sha256 = hashlib.sha256(word.encode()).hexdigest()
    sha3_256 = hashlib.sha3_224(word.encode()).hexdigest()
    ntlm = (binascii.hexlify(
        hashlib.new('md4', word.encode('utf-16le')).digest())).decode()

    print('md5     :', md5)
    print()
    print('sha1    :', sha1)
    print()
    print('sha224  :', sha224)
    print()
    print('blake2s :', blake2s)
    print()
    print('blake2b :', blake2b)
    print()
    print('sha3_384:', sha3_384)
    print()
    print('sha384  :', sha384)
    print()
    print('sha3_512:', sha3_512)
    print()
    print('sha3_224:', sha3_224)
    print()
    print('sha512  :', sha512)
    print()
    print('sha256  :', sha256)
    print()
    print('sha3_256:', sha3_256)
    print()
    print('ntlm    :', ntlm)
    print()

    # check if word alrady exists into database
    chk = check_me(word)

    if chk is False:
        # Store all hashes into database
        choice = input("Enter y to store word in database : ")
        if choice == 'y':
            sql.execute(
                'insert into Hashes_Table(name, md5 , sha1, sha224 , blake2s , blake2b , sha3_384 , sha384 , sha3_512, sha3_224, sha512, sha256, sha3_256, ntlm) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)',
                (word, md5, sha1, sha224, blake2s, blake2b, sha3_384, sha384,
                 sha3_512, sha3_224, sha512, sha256, sha3_256, ntlm))
            sql.commit()
            print("word : " + word)
        return
Пример #8
0
 def hashIt(self):
     inp = [str(self.pcollid), str(self.x), str(self.y)]
     s = hashlib.sha3_224()
     for item in inp:
         hasher = hashlib.sha3_224()
         hasher.update(str(item))
         s.update(hasher.hexdigest()[self.hindexi:self.hindexj])
         s.update(str(s))
     return s.hexdigest()[self.hindexi:self.hindexj]
Пример #9
0
def minify_website(args):
    css_in = ' '.join(get_css_in(args))
    css_out = f'{args.output_dir}/css/base.css'
    if args.minify:
        command = f"purifycss -w '*algolia*' --min {css_in} '{args.output_dir}/*.html' " \
            f"'{args.output_dir}/docs/en/**/*.html' '{args.website_dir}/js/**/*.js' > {css_out}"
    else:
        command = f'cat {css_in} > {css_out}'

    logging.info(command)
    output = subprocess.check_output(command, shell=True)
    logging.debug(output)
    with open(css_out, 'rb') as f:
        css_digest = hashlib.sha3_224(f.read()).hexdigest()[0:8]

    js_in = get_js_in(args)
    js_out = f'{args.output_dir}/js/base.js'
    if args.minify:
        js_in = [js[1:-1] for js in js_in]
        closure_args = [
            '--js', *js_in, '--js_output_file', js_out,
            '--compilation_level', 'SIMPLE',
            '--dependency_mode', 'NONE',
            '--third_party', '--use_types_for_optimization',
            '--isolation_mode', 'IIFE'
        ]
        logging.info(closure_args)
        if closure.run(*closure_args):
            raise RuntimeError('failed to run closure compiler')
        with open(js_out, 'r') as f:
            js_content = jsmin.jsmin(f.read())
        with open(js_out, 'w') as f:
            f.write(js_content)

    else:
        js_in = ' '.join(js_in)
        command = f'cat {js_in} > {js_out}'
        logging.info(command)
        output = subprocess.check_output(command, shell=True)
        logging.debug(output)
    with open(js_out, 'rb') as f:
        js_digest = hashlib.sha3_224(f.read()).hexdigest()[0:8]
        logging.info(js_digest)

    if args.minify:
        logging.info('Minifying website')
        with concurrent.futures.ThreadPoolExecutor() as executor:
            futures = []
            for root, _, filenames in os.walk(args.output_dir):
                for filename in filenames:
                    path = os.path.join(root, filename)
                    futures.append(executor.submit(minify_file, path, css_digest, js_digest))
            for future in futures:
                exc = future.exception()
                if exc:
                    logging.error(exc)
                    sys.exit(1)
Пример #10
0
    def checkChange(self):
        """ check memory for change and save them.
            returns what changed so Hyxtalker can send updates to Hyx
        """
        def findChanges():
            from itertools import count
            start = 0
            length = 0
            result = []
            for old, new, ind in zip(self.heapbytes, buf, count()):
                if old == new:
                    if length > 0:
                        data = buf[start:start + length]
                        # if length == 1:     # if data is a single byte, python converts it to an int
                        #    data= bytes([data])
                        result.append((start, data))
                    length = 0
                    start = ind + 1
                else:
                    length += 1

            if self.heapbytes[-1] != buf[
                    -1]:  # edge case for very last byte in heap
                data = buf[start:start + length]
                result.append((start, data))
            return result

        # check if something changed
        newstart, newstop = self.getStartStop()
        if newstart == self.start and newstop == self.stop:
            with open("/proc/%d/mem" % self.pid, "rb") as mem:
                mem.seek(self.start)
                buf = bytearray(self.stop - self.start)
                assert self.stop - self.start == mem.readinto(buf)
            newhash = hashlib.sha3_224(buf).digest()

            if newhash != self.hash:
                self.hash = newhash
                tuplelist = findChanges()
                self.heapbytes = buf
                return "bytes", tuplelist
            else:
                return "same", 0

        else:
            ret = self.start, self.stop
            self.start = newstart
            self.stop = newstop

            with open("/proc/%d/mem" % self.pid, "rb") as mem:
                mem.seek(self.start)
                self.heapbytes = bytearray(self.stop - self.start)
                assert self.stop - self.start == mem.readinto(self.heapbytes)
            self.hash = hashlib.sha3_224(self.heapbytes).digest()

            return "length", ret
Пример #11
0
    def hashIt(self):
        inp = [str(self.k), str(self.nk), str(self.val), str(self.stype)]
        s = hashlib.sha3_224()
        #ToDO this type of hashing only string values of k,nk,val can generate same hash for different k,nk,val.
        #TODO for example, (1,11,2) and (11,1,2) can give same hash.

        #this method concat hashes of k,nk & v and then takes hash of the string.
        for item in inp:
            hasher = hashlib.sha3_224()
            hasher.update(str(item))
            s.update(hasher.hexdigest()[self.hindexi:self.hindexj])
        return s.hexdigest()[self.hindexi:self.hindexj]
Пример #12
0
def add_data(word_file, salt_value=None, post_value=None, rep=0):
    n = 0
    # it will create rainbow table with given file
    fp = open(word_file, 'r', encoding="Latin-1")
    for word in fp:
        try:
            n += 1
            word = word.strip(string.whitespace)
            if salt_value is not None:
                word = salt_value + word  # Prepend the salt value
            if post_value is not None:
                word += post_value  # append the salt value
            if arg.verbose:
                print(word)

            if rep == 1:
                chk = check_me(word)

            if rep == 0:
                chk = False

            if chk is False:
                # this function will create hashes
                md5 = hashlib.md5(word.encode()).hexdigest()
                sha1 = hashlib.sha1(word.encode()).hexdigest()
                sha224 = hashlib.sha224(word.encode()).hexdigest()
                blake2s = hashlib.blake2s(word.encode()).hexdigest()
                blake2b = hashlib.blake2b(word.encode()).hexdigest()
                sha3_384 = hashlib.sha3_384(word.encode()).hexdigest()
                sha384 = hashlib.sha384(word.encode()).hexdigest()
                sha3_512 = hashlib.sha3_512(word.encode()).hexdigest()
                sha3_224 = hashlib.sha3_224(word.encode()).hexdigest()
                sha512 = hashlib.sha512(word.encode()).hexdigest()
                sha256 = hashlib.sha256(word.encode()).hexdigest()
                sha3_256 = hashlib.sha3_224(word.encode()).hexdigest()
                ntlm = (binascii.hexlify(
                    hashlib.new('md4',
                                word.encode('utf-16le')).digest())).decode()

                sql.execute(
                    'insert into Hashes_Table(name, md5 , sha1, sha224 , blake2s , blake2b , sha3_384 , sha384 , sha3_512, '
                    'sha3_224, sha512, sha256, sha3_256, ntlm ) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)',
                    (word, md5, sha1, sha224, blake2s, blake2b, sha3_384,
                     sha384, sha3_512, sha3_224, sha512, sha256, sha3_256,
                     ntlm))

        except Exception:
            print(Exception)
    sql.commit()
    print('WORD: ', n)
Пример #13
0
    def _load_sdf(self, sdf_str):
        """
        Adds the appropriate SDF to the sprite cache.

        """
        kwargs, sdf_t = parse_sdf_str(sdf_str)
        arg_str = ''.join([f'{k}={kwargs[k]}' for k in sorted(kwargs)])
        cache_name = hashlib.sha3_224(arg_str.encode()).hexdigest()
        path = os.path.join(
            self.cache_dir,
            f'SDF/{sdf_t}/{cache_name[:2]}/{cache_name[2:]}.png'
        )
        if path not in self._sprite_cache:
            if not os.path.isfile(path):
                cache_dir = os.path.split(path)[0]
                if not os.path.isdir(cache_dir):
                    os.makedirs(cache_dir)
                if sdf_t == 'box':
                    image = sdf.framed_box_im(**kwargs)
                elif sdf_t == 'circle':
                    image = sdf.framed_circle_im(**kwargs)
                else:
                    raise ValueError(f'Unknown SDF type: "{sdf_t}"')
                image.save(path)
                self._sprite_cache[path] = _image2sprite(image, self.factory)
            else:
                self._sprite_cache[path] = _image2sprite(
                    Image.open(path),
                    self.factory
                )
        return self._sprite_cache[path]
Пример #14
0
def test_hash_bytes():
    test_string = b'hi there'
    assert j.data.hash.md5(test_string) == hashlib.md5(test_string).hexdigest()
    assert j.data.hash.sha1(test_string) == hashlib.sha1(
        test_string).hexdigest()
    assert j.data.hash.sha224(test_string) == hashlib.sha224(
        test_string).hexdigest()
    assert j.data.hash.sha256(test_string) == hashlib.sha256(
        test_string).hexdigest()
    assert j.data.hash.sha384(test_string) == hashlib.sha384(
        test_string).hexdigest()
    assert j.data.hash.sha512(test_string) == hashlib.sha512(
        test_string).hexdigest()
    assert j.data.hash.sha3_224(test_string) == hashlib.sha3_224(
        test_string).hexdigest()
    assert j.data.hash.sha3_256(test_string) == hashlib.sha3_256(
        test_string).hexdigest()
    assert j.data.hash.sha3_384(test_string) == hashlib.sha3_384(
        test_string).hexdigest()
    assert j.data.hash.sha3_512(test_string) == hashlib.sha3_512(
        test_string).hexdigest()
    assert j.data.hash.blake2b(test_string) == hashlib.blake2b(
        test_string).hexdigest()
    assert j.data.hash.blake2s(test_string) == hashlib.blake2s(
        test_string).hexdigest()
    assert j.data.hash.shake_128(test_string) == hashlib.shake_128(
        test_string).hexdigest(16)
    assert j.data.hash.shake_256(test_string) == hashlib.shake_256(
        test_string).hexdigest(16)
Пример #15
0
def test_hash_strings():
    test_string = "my company is codescalers"
    assert j.data.hash.md5(test_string) == hashlib.md5(
        test_string.encode()).hexdigest()
    assert j.data.hash.sha1(test_string) == hashlib.sha1(
        test_string.encode()).hexdigest()
    assert j.data.hash.sha224(test_string) == hashlib.sha224(
        test_string.encode()).hexdigest()
    assert j.data.hash.sha256(test_string) == hashlib.sha256(
        test_string.encode()).hexdigest()
    assert j.data.hash.sha384(test_string) == hashlib.sha384(
        test_string.encode()).hexdigest()
    assert j.data.hash.sha512(test_string) == hashlib.sha512(
        test_string.encode()).hexdigest()
    assert j.data.hash.sha3_224(test_string) == hashlib.sha3_224(
        test_string.encode()).hexdigest()
    assert j.data.hash.sha3_256(test_string) == hashlib.sha3_256(
        test_string.encode()).hexdigest()
    assert j.data.hash.sha3_384(test_string) == hashlib.sha3_384(
        test_string.encode()).hexdigest()
    assert j.data.hash.sha3_512(test_string) == hashlib.sha3_512(
        test_string.encode()).hexdigest()
    assert j.data.hash.blake2b(test_string) == hashlib.blake2b(
        test_string.encode()).hexdigest()
    assert j.data.hash.blake2s(test_string) == hashlib.blake2s(
        test_string.encode()).hexdigest()
    assert j.data.hash.shake_128(test_string) == hashlib.shake_128(
        test_string.encode()).hexdigest(16)
    assert j.data.hash.shake_256(test_string) == hashlib.shake_256(
        test_string.encode()).hexdigest(16)
Пример #16
0
 def hashpassword(self, password):
     salt = hashlib.sha3_512()
     salt.update("$%&^&*())(&*^&%%$##$$#$%&^^(*(*++===".encode())
     password += salt.hexdigest()
     passw = hashlib.sha3_224()
     passw.update(password.encode())
     return passw.hexdigest()
Пример #17
0
def sha3_224_hex(hexstr):
    if len(hexstr) % 2 != 0:
        raise ValueError("Error: Length of hex string should be even")
    m = hashlib.sha3_224()
    data = binascii.a2b_hex(str(hexstr))
    m.update(data)
    return m.hexdigest()
Пример #18
0
async def MainParser(args):
    user = args.user

    server_conf = parse_config.parse()["Server"]

    db = await create_pool.create(server_conf.get("mysql_db"))

    logging.warning(_("Borrando usuario '%s' :-("), user)

    userid = await db.return_first_result("extract_userid", user)

    if (userid is None):
        logging.error(_("El usuario no existe"))
        return

    else:
        (userid, ) = userid

    await db.return_first_result("delete_user", userid)

    public_key_dst = "%s/pubkeys/%s" % (server_conf.get("init_path"),
                                        hashlib.sha3_224(
                                            user.encode()).hexdigest())

    logging.debug(_("Borrando clave pública: %s"), public_key_dst)

    if (os.path.isfile(public_key_dst)):
        os.remove(public_key_dst)

    else:
        logging.warning(
            _("No se pudo eliminar la clave pública porque no existe"))

    logging.info(_("Usuario '%s' eliminado."), user)
def getImage(save_dir_path, img_list):
    make_dir(save_dir_path)
    save_img_path = os.path.join(save_dir_path, 'imgs')
    make_dir(save_img_path)

    opener = urllib.request.build_opener()
    http = httplib2.Http(".cache")

    for i in range(len(img_list)):
        try:
            url = img_list[i]
            extension = os.path.splitext(img_list[i])[-1]

            if extension.lower() in ('.jpg', '.jpeg', '.gif', '.png', '.bmp'):
                encoded_url = url.encode(
                    'utf-8')  # required encoding for hashed
                a = hashlib.sha3_224()

                hashed_url = hashlib.sha3_256(encoded_url).hexdigest()
                full_path = os.path.join(save_img_path,
                                         hashed_url + extension.lower())

                response, content = http.request(url)
                with open(full_path, 'wb') as f:
                    f.write(content)
                print('saved image... {}'.format(url))

                make_correspondence_table(correspondence_table, url,
                                          hashed_url)

        except Exception as e:
            print(e)
            print("failed to download images.")
            continue
Пример #20
0
    async def insert_user(user: str,
                          password: str,
                          token_limit: int = 1,
                          guest_user: bool = False,
                          *,
                          cursor) -> None:
        """Añade un nuevo usuario
        
        Args:
            user:
              El nombre de usuario

            password:
              La contraseña

            token_limit:
              El límite de token's permitidos

            guest_user:
              **True** si es un usuario invitado; **False** si no.
        """

        logging.debug(_("Creando nuevo usuario: %s"), user)

        user_hash = hashlib.sha3_224(user.encode()).hexdigest()

        await cursor.execute(
            "INSERT INTO users(user, password, token_limit, user_hash, guest_user) VALUES (%s, %s, %s, %s, %s)",
            (user, password, token_limit, user_hash, guest_user))

        logging.debug(_("Usuario %s (%s) creado satisfactoriamente"), user,
                      user_hash)
Пример #21
0
def sha3_224(fname):
    """ """
    hash_sha3_224 = hashlib.sha3_224()
    with open(fname, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hash_sha3_224.update(chunk)
    return hash_sha3_224.hexdigest()
 def test_content_access(self):
     """
     Test access content from hard disk vs cache
     Applies to cache versus web content & database store
     """
     # test without memcached -- load from hard disk
     trials = BoazBase.get_trial_size()
     content = BoazBase.get_content_file()
     start_time = time.perf_counter_ns()
     for i in range(0, trials):
         fd = open(content, "rb")
         fd.read()  # read from disk
     end_time = time.perf_counter_ns()
     BoazBase.print_time("\nContent from HD", trials, end_time - start_time)
     # load content from cache
     self.mc.flush_all()
     key = str(
         int(hashlib.sha3_224(content.encode('utf-8')).hexdigest()[:5],
             16)).encode('utf-8')
     fd = open(content, "rb")
     bytes = fd.read()  # read from disk once
     self.mc.set(key, bytes)  # store bytes in cache
     start_time = time.perf_counter_ns()
     for i in range(0, trials):
         self.mc.get(key)  # read from cache
     end_time = time.perf_counter_ns()
     BoazBase.print_time("\nContent from Cache", trials,
                         end_time - start_time)
     fd.close()
Пример #23
0
def hasherFromString(s):
    import hashlib
    if s == 'sha1':
        return hashlib.sha1()
    elif s == 'sha224':
        return hashlib.sha224()
    elif s == 'sha256':
        return hashlib.sha256()
    elif s == 'sha384':
        return hashlib.sha384()
    elif s == 'sha512':
        return hashlib.sha512()
    elif s == 'blake2b':
        return hashlib.blake2b()
    elif s == 'blake2s':
        return hashlib.blake2s()
    elif s == 'md5':
        return hashlib.md5()
    elif s == 'sha3_224':
        return hashlib.sha3_224()
    elif s == 'sha3_256':
        return hashlib.sha3_256()
    elif s == 'sha3_384':
        return hashlib.sha3_384()
    elif s == 'sha3_512':
        return hashlib.sha3_512()
    elif s == 'shake_128':
        return hashlib.shake_128()
    elif s == 'shake_256':
        return hashlib.shake_256()
    else:
        raise ValueError('Unknown hash type ' + s)
Пример #24
0
def hashing(name, string):
    if name == 'SHA1':
        return hashlib.sha1(string.encode('utf-8')).hexdigest()
    elif name == 'SHA3_224':
        return hashlib.sha3_224(string.encode('utf-8')).hexdigest()
    elif name == 'SHA3_256':
        return hashlib.sha3_256(string.encode('utf-8')).hexdigest()
    elif name == 'SHA3_384':
        return hashlib.sha3_384(string.encode('utf-8')).hexdigest()
    elif name == 'SHA3_512':
        return hashlib.sha3_512(string.encode('utf-8')).hexdigest()
    elif name == 'SHA224':
        return hashlib.sha224(string.encode('utf-8')).hexdigest()
    elif name == 'SHA256':
        return hashlib.sha256(string.encode('utf-8')).hexdigest()
    elif name == 'SHA384':
        return hashlib.sha384(string.encode('utf-8')).hexdigest()
    elif name == 'SHA512':
        return hashlib.sha512(string.encode('utf-8')).hexdigest()
    elif name == 'MD5':
        return hashlib.md5(string.encode('utf-8')).hexdigest()
    elif name == 'BLAKE2b':
        return hashlib.blake2b(string.encode('utf-8')).hexdigest()
    elif name == 'BLAKE2s':
        return hashlib.blake2s(string.encode('utf-8')).hexdigest()
Пример #25
0
def hashfun(text):
    """
    Converts a str object to a hash which was configured in modules.conf of the cobbler settings.

    :param text: The text to hash.
    :type text: str
    :return: The hash of the text. This should output the same hash when entered the same text.
    """
    hashfunction = get_module_name("authentication", "hash_algorithm",
                                   "sha3_512")
    if hashfunction == "sha3_224":
        hashalgorithm = hashlib.sha3_224(text.encode('utf-8'))
    elif hashfunction == "sha3_384":
        hashalgorithm = hashlib.sha3_384(text.encode('utf-8'))
    elif hashfunction == "sha3_256":
        hashalgorithm = hashlib.sha3_256(text.encode('utf-8'))
    elif hashfunction == "sha3_512":
        hashalgorithm = hashlib.sha3_512(text.encode('utf-8'))
    elif hashfunction == "blake2b":
        hashalgorithm = hashlib.blake2b(text.encode('utf-8'))
    elif hashfunction == "blake2s":
        hashalgorithm = hashlib.blake2s(text.encode('utf-8'))
    elif hashfunction == "shake_128":
        hashalgorithm = hashlib.shake_128(text.encode('utf-8'))
    elif hashfunction == "shake_256":
        hashalgorithm = hashlib.shake_256(text.encode('utf-8'))
    else:
        errortext = "The hashfunction (Currently: %s) must be one of the defined in /etc/cobbler/modules.conf!" \
                    % hashfunction
        raise ValueError(errortext)
    return hashalgorithm.hexdigest()
Пример #26
0
def s(n):
    _h = hashlib.sha3_224()
    buf = n.encode()
    _h.update(buf)
    H = _h.hexdigest()
    print('SHA3 224:        ' + H)
    return H
Пример #27
0
def cmd_passwordSearch():

    # initialize a string
    password = input("\n Enter your password:"******"\nSHA3-224 Hash: ", obj_sha3_224.hexdigest())
    print("\nSHA3-256 Hash: ", obj_sha3_256.hexdigest())
    print("\nSHA3-384 Hash: ", obj_sha3_384.hexdigest())
    print("\nSHA3-512 Hash: ", obj_sha3_512.hexdigest())
    print("\nSHA3-keccak-512 Hash: ", keccak_hash.hexdigest())
    sha3k512 = keccak_hash.hexdigest()

    sub_pass = sha3k512[0:10]

    #print("First 10 characters from the password:"******"https://passwords.xposedornot.com/api/v1/pass/anon/" + sub_pass)
    json_data = json.loads(response.text)
    print("\nOutput:", json_data)
Пример #28
0
    def get_hash(self):
        if exists(self.stdin) and isfile(self.stdin):
            print(f"File: {self.stdin}")
            with open(self.stdin, "rb") as f:
                self.stdin = f.read()

        if type(self.stdin) == str:
            self.stdin = bytes(self.stdin.strip(), "utf8")

        for h in self.hash_functions:
            if h == "md5": yield ("MD5:", md5(self.stdin).hexdigest())
            if h == "sha1": yield ("SHA1:", sha1(self.stdin).hexdigest())
            if h == "sha224": yield ("SHA224:", sha224(self.stdin).hexdigest())
            if h == "sha256": yield ("SHA256:", sha256(self.stdin).hexdigest())
            if h == "sha384": yield ("SHA256:", sha384(self.stdin).hexdigest())
            if h == "sha512": yield ("SHA512:", sha512(self.stdin).hexdigest())
            if h == "sha3_224":
                yield ("SHA3_224:", sha3_224(self.stdin).hexdigest())
            if h == "sha3_256":
                yield ("SHA3_256:", sha3_256(self.stdin).hexdigest())
            if h == "sha3_384":
                yield ("SHA3_384:", sha3_384(self.stdin).hexdigest())
            if h == "sha3_512":
                yield ("SHA3_512", sha3_512(self.stdin).hexdigest())
            if h == "blake2b":
                yield ("BLAKE2B:", blake2b(self.stdin).hexdigest())
            if h == "blake2s":
                yield ("BLAKE2S:", blake2s(self.stdin).hexdigest())
Пример #29
0
def hasherFromString(s):
    import hashlib
    if s == 'sha1':
        return hashlib.sha1()
    elif s == 'sha224':
        return hashlib.sha224()
    elif s == 'sha256':
        return hashlib.sha256()
    elif s == 'sha384':
        return hashlib.sha384()
    elif s == 'sha512':
        return hashlib.sha512()
    elif s == 'blake2b':
        return hashlib.blake2b()
    elif s == 'blake2s':
        return hashlib.blake2s()
    elif s == 'md5':
        return hashlib.md5()
    elif s == 'sha3_224':
        return hashlib.sha3_224()
    elif s == 'sha3_256':
        return hashlib.sha3_256()
    elif s == 'sha3_384':
        return hashlib.sha3_384()
    elif s == 'sha3_512':
        return hashlib.sha3_512()
    elif s == 'shake_128':
        return hashlib.shake_128()
    elif s == 'shake_256':
        return hashlib.shake_256()
    else:
        return None
Пример #30
0
def haszowanie_sha3_224(tekst):
    start = time.time()
    wynik = hashlib.sha3_224(tekst.encode("utf8")).hexdigest()
    end = time.time() - start
    print("Skrot wygenerowany dzieki funkcji SHA3-224: " + wynik +
          ", czas generacji to: " + str(end * 1000) + " ms" +
          ", a dlugosc ciagu wyjsciowego to: " + str(len(wynik)))
Пример #31
0
    def hash(self, data):
        '''!
        Method to generate a series of 12 hashes for a given data 
        string, in the format of <MD5>:<SHA1>:<SHA224>:<SHA3 
        244>:<SHA256>:<SHA3 256>:<SHA384>:<SHA3 384>:<SHA512>:<SHA3 
        215>:<Blake 2b>:<Blake 2s>.

        @param data String: Data string to generate hash.
        @return: Hash
        '''
        data = str(data)
        data = bytes(data, 'utf-8')
        x = [
            hashlib.md5(data).hexdigest(),
            hashlib.sha1(data).hexdigest(),
            hashlib.sha224(data).hexdigest(),
            hashlib.sha3_224(data).hexdigest(),
            hashlib.sha256(data).hexdigest(),
            hashlib.sha3_256(data).hexdigest(),
            hashlib.sha384(data).hexdigest(),
            hashlib.sha3_384(data).hexdigest(),
            hashlib.sha512(data).hexdigest(),
            hashlib.sha3_512(data).hexdigest(),
            hashlib.blake2b(data).hexdigest(),
            hashlib.blake2s(data).hexdigest()
        ]
        return ':'.join(x)
Пример #32
0
 def test_sha3224(self):
     """
     Test SHA3-224 hash.
     """
     if "sha3_224" not in hashlib.algorithms_available:
         pass
     else:
         assert bh.hashlib_hash("tempfile.txt", hashlib.sha3_224()) == "93cc89107b9bd807dead1ae95ce8c4b0f9b8acb2a3eef704e2fad109"
Пример #33
0
    def run(self, parent, blocks):
        block = blocks.pop(0)
        match = self.RE.search(block)

        if match:
            # If there's a match, then this is a labeled paragraph. We'll add
            # the paragraph tag, label id, and initial text, then process the
            # rest of the blocks normally.
            label, text = match.group('label'), match.group('text')
            # Labeled paragraphs without text should use a div element
            if text == '':
                el = util.etree.SubElement(parent, 'div')
            else:
                el = util.etree.SubElement(parent, 'p')
            el.set('id', label)

            # We use CSS classes to indent paragraph text. To get the correct
            # class, we count the number of dashes in the label to determine
            # how deeply nested the paragraph is. Inline interps have special
            # prefixes that are removed before counting the dashes.
            # e.g. 6-a-Interp-1 becomes 1 and gets a `level-0` class
            # e.g. 12-b-Interp-2-i becomes 2-i and gets a `level-1` class
            label = re.sub(
                r'^(\w+\-)+interp\-', '', label, flags=re.IGNORECASE
            )

            # Appendices also have special prefixes that need to be stripped.
            # e.g. A-1-a becomes a and gets a `level-0` class
            # e.g. A-2-d-1 becomes d-1 and gets a `level-1` class
            label = re.sub(r'^[A-Z]\d?\-\w+\-?', '', label)
            level = label.count('-')
            class_name = 'regdown-block level-{}'.format(level)
            el.set('class', class_name)

            el.text = text.lstrip()

        elif block.strip():
            if self.parser.state.isstate('list'):
                # Pass off to the ParagraphProcessor for lists
                super(ParagraphProcessor, self).run(
                    parent, blocks
                )  # pragma: no cover
            else:
                # Generate a label that is a hash of the block contents. This
                # way it won't change unless the rest of this block changes.
                text = block.lstrip()
                label = sha3_224(text.encode('utf-8')).hexdigest()
                class_name = 'regdown-block'
                p = util.etree.SubElement(parent, 'p')
                p.set('id', label)
                p.set('class', class_name)

                p.text = text
Пример #34
0
def get_engine(hashtype):
    """
    Get hashlib engine from hash type.

    :param hashtype: Hash type.
    :type hashtype: str
    """
    hashengines = {"md5": hashlib.md5(),
                   "sha1": hashlib.sha1(),
                   "sha224": hashlib.sha224(),
                   "sha256": hashlib.sha256(),
                   "sha384": hashlib.sha384(),
                   "sha512": hashlib.sha512()}
    if utilities.new_enough(6):
        hashengines.update({"sha3224": hashlib.sha3_224(),
                            "sha3256": hashlib.sha3_256(),
                            "sha3384": hashlib.sha3_384(),
                            "sha3512": hashlib.sha3_512()})
    return hashengines[hashtype]
Пример #35
0
import sys
import hashlib
import sha3

# User is offered choice of input (file/string)
print("Welcome to hash checker. This program can calculate the hash of a string or file.")
question = input("Do you wish to check the hash of a string (S) or file (F)? Enter S or F: ")

# If user choses file, accept filename as input, open, read file, compute hashes
if question == "F" or question == "f":
	filename = input("Enter a file name: ")
	contents = open(filename, 'rb').read()
	yoursha1 = hashlib.sha1(contents)
	yoursha256 = hashlib.sha256(contents)
	yoursha512 = hashlib.sha512(contents)
	yoursha3224 = hashlib.sha3_224(contents)
	yoursha3256 = hashlib.sha3_256(contents)
	yoursha3384 = hashlib.sha3_384(contents)
	yoursha3512 = hashlib.sha3_512(contents)
else:
	# Prompt user to enter string and compute hashes
	guess = input("\nPlease enter a string: ")
	yoursha1 = hashlib.sha1(guess.encode())
	yoursha256 = hashlib.sha256(guess.encode())
	yoursha512 = hashlib.sha512(guess.encode())
	yoursha3224 = hashlib.sha3_224(guess.encode())
	yoursha3256 = hashlib.sha3_256(guess.encode())
	yoursha3384 = hashlib.sha3_384(guess.encode())
	yoursha3512 = hashlib.sha3_512(guess.encode())

# Convert hashes to readable form and print