Ejemplo n.º 1
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
Ejemplo n.º 2
0
def convert_int_to_uuid(x: int) -> str:
    """Uses an integer as a seed to generate a UUID.

    This function first hashes the integer using the  `hashlib.shake_128 <https://docs.python.org/3/library/hashlib.html#shake-variable-length-digests>`_
    hashing algorithm. This allows us to generate a 128bit hash that the `uuid <https://docs.python.org/3/library/uuid.html>`_
    library requires as seed to generate a unique UUID.

    Parameters
    ----------
    x: int
        Integer as seed.

    Returns
    -------
    str
        UUID in string format.
    """
    x_byte = int_to_bytes(x)
    m = shake_128()
    m.update(x_byte)
    digest = m.digest(16)  # 16 bytes = 128 bits
    u = str(uuid.UUID(bytes=digest))
    return u
Ejemplo n.º 3
0
 async def _new_session_id(self):
     rv = self._session_id[:32] + hashlib.shake_128(
         os.urandom(16)).hexdigest(16)
     selector, validator = self._split(rv)
     new_nonce = self._make_nonce()
     to_del = self._get_del()
     ts = self._get_deadline()
     # noinspection PyUnresolvedReferences
     await self._update_with_new_validator(
         [
             selector,
             validator,
             str(ts).encode('utf-8'),
             int(ts * 1000),
             len(to_del),
             self._nonce,
         ],
         to_del + self._encode({NONCE: new_nonce}))
     self._nonce = new_nonce
     self._to_del.clear()
     self._values_changed.clear()
     self._cookie_deadline = ts
     return rv
Ejemplo n.º 4
0
def expand_m0(hp, m0seed):
    # use the 32 byte seed m0 to produce the shared key, the randomness r used in encryption and the
    # 'error' m used in encryption.  m should have the property that its first 256 positions modulo 2
    # are equal to the positions of m0seed, when the latter is expanded as a 256-bit string
    for i in range(0, 48, 1):
        m0seed.append(
            hp[i]
        )  # append first 48 positions of packed public key mod 256 to the msg
    full_hash = hashlib.shake_128(bytes(m0seed)).digest(
        DEG + 32)  # create H(msg,id(pk))
    shared_key = full_hash[0:32]  # first 32 bytes is the shared key
    rseed = full_hash[32:32 +
                      DEG // 2]  # next DEG//2 bytes makes the randomness
    r = gen_rand_poly(rseed)  # create a randomness polynomial
    mseed = full_hash[32 + DEG // 2:32 +
                      DEG]  # next DEG//2 bytes creates the message
    m = []  # the message
    # creating the first 256 positions of m such that mod 2 they are the 256 bits of m0seed
    # first, putting each bit of m0 into m
    for i in range(32):
        bitar = byte_to_bits(m0seed[i])
        m.extend(bitar)
    # next, supplementing the first bit with the correct distribution.  one byte is used to create two coefficients
    # this distribution should be the same as in gen_rand_poly()
    for i in range(128):
        bitar = byte_to_bits(mseed[i])
        m[2 * i] = (m[2 * i] - 2 * bitar[0] * bitar[1]) * (1 - 2 * bitar[2])
        m[2 * i +
          1] = (m[2 * i + 1] - 2 * bitar[3] * bitar[4]) * (1 - 2 * bitar[5])
    # the rest of the positions are generated normally as b0+b1-b2-b3
    for i in range(128, DEG // 2):
        bitar = byte_to_bits(mseed[i])
        m.append(bitar[0] + bitar[1] - bitar[2] -
                 bitar[3])  # convert first half byte to one coefficient
        m.append(bitar[4] + bitar[5] - bitar[6] -
                 bitar[7])  # convert second half of byte to second coeff
    return shared_key, np.int64(r), np.int64(m)
Ejemplo n.º 5
0
def _get_user_by_email_or_username(request, api_version):
    """
    Finds a user object in the database based on the given request, ignores all fields except for email and username.
    """
    is_api_v2 = api_version != API_V1
    login_fields = ['email', 'password']
    if is_api_v2:
        login_fields = ['email_or_username', 'password']

    if any(f not in request.POST.keys() for f in login_fields):
        raise AuthFailedError(_('There was an error receiving your login information. Please email us.'))

    email_or_username = request.POST.get('email', None) or request.POST.get('email_or_username', None)
    user = _get_user_by_email(email_or_username)

    if not user and is_api_v2:
        # If user not found with email and API_V2, try username lookup
        user = _get_user_by_username(email_or_username)

    if not user:
        digest = hashlib.shake_128(email_or_username.encode('utf-8')).hexdigest(16)  # pylint: disable=too-many-function-args
        AUDIT_LOG.warning(f"Login failed - Unknown user email or username {digest}")

    return user
Ejemplo n.º 6
0
    def parse_comments(self, bs, content, params):
        comments = session.query(models.Comment).\
                filter(models.Comment.cid == content.id).\
                all()

        if len(comments) > 0:
            print('alread updated')
            return
        
        comment_top = bs.find('div', id='comment_top')
        last_page = self.get_comment_last_page(comment_top)
        before_comment = None
        for i in range(last_page + 1):
            param = params
            params['cpage'] = i
            res = BeautifulSoup(requests.get(self.base_url, params).text, 'html.parser')
            comment_list = res.find('div', id='commentbox').find('div', attrs={'class': 'comment-list'})
            # for comment_box in comment_list.findAll(lambda x: x.name == 'div' and 'class' in x.attrs and 'depth' not in x.attrs['class'] and 'comment-item' in x.attrs['class']):
            for comment_box in comment_list.findAll(lambda x: x.name == 'div' and 'class' in x.attrs and 'comment-item' in x.attrs['class']):
                box = comment_box.select('> div')[0].select('> div')[0]

                try:
                    text = box.find('div', attrs={'class': 'xe_content'}).text
                except Exception as e:
                    continue
                if not text:
                    before_comment = None
                    print('continued')
                    break
                date = box.find('div').findAll('div')[-1].find('span').text
                delta = None
                if '일 전' in date:
                    delta = timedelta(days=int(date[0]))
                if '시간 전' in date:
                    delta = timedelta(hours=int(date[0]))
                if '분 전' in date:
                    delta = timedelta(minutes=int(date[0]))

                if delta is not None:
                    date = datetime.utcnow() + timedelta(hours=9) - delta
                else:
                    date = datetime.strptime(date, '%Y.%m.%d')
                
                selected = box.select('div.comment-bar > div')
                if len(selected) == 0:
                    selected = box.select('div.comment-bar-author > div')
                writer = selected[0].text.strip()
                # writer = box.select('a.ed.link-reset')[0].text
                writer = hashlib.shake_128(writer.encode()).hexdigest(length=4)

                user = session.query(models.User).\
                    filter(models.User.nickname == writer).\
                    first()
                
                if user is None:
                    user = models.User(nickname=writer)
                    session.add(user)
                    session.flush()
                
                comment = models.Comment(data=text, cid=content.id, created_at=date, uid=user.id)
                if 'depth' in comment_box.attrs['class'] and before_comment:
                    target = box.select('span.ed.label-primary')[0].text.strip()[1:]
                    target = hashlib.shake_128(target.encode()).hexdigest(length=4)
                    comment.data = f'@{target} {comment.data}'
                    comment.parent_id = before_comment.id
                else:
                    before_comment = comment
                
                exist = session.query(models.Comment).\
                    filter(models.Comment.uid == user.id).\
                    first()
                if not exist:
                    session.add(comment)
                    session.flush()
                    print(text)

        session.commit()
        return content
Ejemplo n.º 7
0
 def get_hash(obj):
     return hashlib.shake_128(json.dumps(obj).encode("utf-8")).hexdigest(16)
Ejemplo n.º 8
0
def main():
    method = str(
        console.input_alert(
            "iHashIt by GoDzM4TT3O",
            "Enter a hash method (type list to get a list of available hash methods, extra for more info.)\nExample: md5"
        ))
    if method == 'list':
        list = console.alert(
            "iHashIt by GoDzM4TT3O",
            "List of available hash methods:\n\n'blake2b'\n'sha384'\n'sha256'\n'sha512'\n'md5'\n'blake2s'\n'sha3_224'\n'sha1'\n'sha3_512'\n'sha3_256'\n'shake_256'\nsha224'\n'sha3_384'\n'shake_128'"
        )
    if method == 'extra':
        console.alert(
            "iHashIt by GoDzM4TT3O",
            "Created on Wednesday, 22 August 2018 by GoDzM4TT3O on Pythonista 3, for Python 3.\nMade using hashlib library.\nLICENSE: GNU GPL v3.0\n----------\nHow does it work?\n1. User input using console.input_alert(\"iHashIt\", \"Description of user input\") and putting it into a variable\n2. Converting user input (which is a string) to a bytearray (I called it bytestring lol) in order to make hashing with user input (string) possible.\n3. Using hashlib for the rest.\n----------\nHUGE SHOUTOUT to Omz::software for creating Pythonista! I\'m a total noob, but at least I created some cool scripts with it, also using its great documentation!"
        )
    string = console.input_alert("iHashIt", "Enter a string to hash")
    bytestring = bytearray(string, "utf-8")
    if method == 'md5':
        m = hashlib.md5()
        m.update(b"" + bytestring)
        print("Your [MD5] hashed string is:", m.hexdigest(), "\nDigest size: ",
              m.digest_size, "\nBlock size: ", m.block_size, "\n\n")
    elif method == 'blake2b':
        m = hashlib.blake2b()
        m.update(b"" + bytestring)
        print("Your [BLAKE2B] hashed string is:", m.hexdigest(),
              "\nDigest size: ", m.digest_size, "\nBlock size: ", m.block_size,
              "\n\n")
    elif method == 'sha384':
        m = hashlib.sha384()
        m.update(b"" + bytestring)
        print("Your [SHA384] hashed string is:", m.hexdigest(),
              "\nDigest size: ", m.digest_size, "\nBlock size: ", m.block_size,
              "\n\n")
    elif method == 'sha256':
        m = hashlib.sha256()
        m.update(b"" + bytestring)
        print("Your [SHA256] hashed string is:", m.hexdigest(),
              "\nDigest size: ", m.digest_size, "\nBlock size: ", m.block_size,
              "\n\n")
    elif method == 'sha512':
        m = hashlib.sha512()
        m.update(b"" + bytestring)
        print("Your [SHA512] hashed string is:", m.hexdigest(),
              "\nDigest size: ", m.digest_size, "\nBlock size: ", m.block_size,
              "\n\n")
    elif method == 'blake2s':
        m = hashlib.blake2s()
        m.update(b"" + bytestring)
        print("Your [BLAKE2S] hashed string is:", m.hexdigest(),
              "\nDigest size: ", m.digest_size, "\nBlock size: ", m.block_size,
              "\n\n")
    elif method == 'sha3_224':
        m = hashlib.sha3_224()
        m.update(b"" + bytestring)
        print("Your [SHA3_224] hashed string is:", m.hexdigest(),
              "\nDigest size: ", m.digest_size, "\nBlock size: ", m.block_size,
              "\n\n")
    elif method == 'sha1':
        m = hashlib.sha1()
        m.update(b"" + bytestring)
        print("Your [SHA1] hashed string is:", m.hexdigest(),
              "\nDigest size: ", m.digest_size, "\nBlock size: ", m.block_size,
              "\n\n")
    elif method == 'sha3_512':
        m = hashlib.sha3_512()
        m.update(b"" + bytestring)
        print("Your [SHA3_512] hashed string is:", m.hexdigest(),
              "\nDigest size: ", m.digest_size, "\nBlock size: ", m.block_size,
              "\n\n")
    elif method == 'sha3_256':
        m = hashlib.sha3_256()
        m.update(b"" + bytestring)
        print("Your [SHA3_256] hashed string is:", m.hexdigest(),
              "\nDigest size: ", m.digest_size, "\nBlock size: ", m.block_size,
              "\n\n")
    elif method == 'shake_256':
        m = hashlib.shake_256()
        m.update(b"" + bytestring)
        print("Your [SHAKE_256] hashed string is:", m.hexdigest(),
              "\nDigest size: ", m.digest_size, "\nBlock size: ", m.block_size,
              "\n\n")
    elif method == 'sha224':
        m = hashlib.sha224()
        m.update(b"" + bytestring)
        print("Your [SHA224] hashed string is:", m.hexdigest(),
              "\nDigest size: ", m.digest_size, "\nBlock size: ", m.block_size,
              "\n\n")
    elif method == 'sha3_384':
        m = hashlib.sha3_384()
        m.update(b"" + bytestring)
        print("Your [SHA3_384] hashed string is:", m.hexdigest(),
              "\nDigest size: ", m.digest_size, "\nBlock size: ", m.block_size,
              "\n\n")
    elif method == 'shake_128':
        m = hashlib.shake_128()
        m.update(b"" + bytestring)
        print("Your [SHAKE_128] hashed string is:", m.hexdigest(),
              "\nDigest size: ", m.digest_size, "\nBlock size: ", m.block_size,
              "\n\n")
    else:
        print("Unknown hashing method")
        return 1
    print("iHashIt by GoDzM4TT3O")
Ejemplo n.º 9
0
def main(args):
    """With fixed initial seed, generate instances and save as C files

    Args:
        args (argparse.Namespace), with attributes:
            num_instances (int): how many instances to generate
            outdir (str): path to directory to save instances; must exist
            seed (int): seed to use for random.seed(). If -1, then seed by
                default Python seeding

    Returns: 0 if no error
    """
    # check args
    outdir = args.outdir
    seed = int(args.seed)
    num_instances = int(args.num_instances)

    # check paths
    outdir = os.path.abspath(os.path.expanduser(outdir))
    if not os.path.isdir(outdir):
        raise OSError("outdir does not exist: '{}'".format(outdir))

    # set seed
    if seed != -1:
        random.seed(seed)

    # Generate metadata only if the metadata_file argument is present
    generate_metadata = args.metadata_file is not None
    # This dict is used to store instance metadata
    tag_metadata = {}
    inst_num = 0

    mutex_example_gens = [gen_race_cond_example, gen_cond_wait_example, gen_cond_signal_example, ]
    example_gens = [gen_mem_example, gen_strcpy_example]
    dummy_gens = [gen_mem_dummy, gen_control_flow_dummy, gen_ordinary_dummy]

    while inst_num < num_instances:
        # generate example
        instance_str, tags = _gen_examples(mutex_example_gens, example_gens, dummy_gens)

        # generate filename
        byte_obj = bytes(instance_str, 'utf-8')
        fname = hashlib.shake_128(byte_obj).hexdigest(FNAME_HASHLEN)
        fname = "{}.c".format(fname)
        if fname in tag_metadata:
            continue

        # insert record into metadata for this c file
        tag_metadata[fname] = [tag.value for tag in tags]
        inst_num += 1

        # write to file
        path = os.path.join(outdir, fname)
        with open(path, 'w') as f:
            f.write(instance_str)

    if generate_metadata:
        # construct the complete metadata
        metadata = {
            "working_dir": outdir,
            "num_instances": num_instances,
            "tags": tag_metadata
        }
        with open(args.metadata_file, 'w') as f:
            json.dump(metadata, f)

    return 0
Ejemplo n.º 10
0
def hash_shake128(s):
    shake128 = hashlib.shake_128()
    shake128.update(s.encode('utf-8'))
    return shake128.hexdigest(128)
Ejemplo n.º 11
0
 def _get_shake_128(self):
     """Hash a string using the shake_128 algo and return in hexdigested form."""
     return shake_128(self.string).hexdigest(128)
Ejemplo n.º 12
0
import hashlib #해시 함수
import secrets #CSPRNG
import sys


passwd = input('enter password :'******'rt',encoding = 'utf-8') as f:
    salt = f.readline()

salt = salt.strip()

passwd +=salt

encoded_string = passwd.encode()
KEK = hashlib.shake_128(encoded_string).hexdigest(8)
print(salt)
print(KEK.upper())
Ejemplo n.º 13
0
 def as_int(cls, text: str) -> int:
     seed = text.encode()
     hash_digest = hashlib.shake_128(seed).digest(cls.BYTES)
     hash_int = int.from_bytes(hash_digest, byteorder='big', signed=True)
     assert cls.MIN <= hash_int <= cls.MAX
     return hash_int
Ejemplo n.º 14
0
def _hash(s: str):
    """ bigint hash for random string, presents params ID for params storage """
    return int(hashlib.shake_128(s.encode()).hexdigest(7), 18)
Ejemplo n.º 15
0
def main():

    parser = argparse.ArgumentParser(
        prog='D-Hashes',
        usage='hashes.py [OPTIONS] STRING',
        description=
        'Thanks for used this tool. It\'s support me to make many tool others. This is script for hashes function in python using hashlib.',
        epilog="""
\033[31;1m[! NOTES ]\033[00;0m
If your input string use spaces the quote or double quotes symbol (\' or ").

FOR EXAMPLE: \'This is my query string input\'

and if your string include a quote use like this:

\033[32;1mExample1:\033[00;0m \'Hai namaku "Arya" salken.\'
\033[32;1mExample2:\033[00;0m "Hai namaku \'Arya\' salken."
\033[32;1mExample3:\033[00;0m "Hai namaku \\"Arya\\" salken."
\033[32;1mExample4:\033[00;0m \'Hai namaku \\\'Arya\\\' salken.\'
\n
OR YOUR TEXT CAN BE LIKE THIS:
\"\"\"
This is my textarea data
Hole of spaces and quote
with 3 doublequotes
\"\"\"""")

    parser.add_argument('-blake2b',
                        metavar='Blake2b',
                        help='blake2b hash algorithm')
    parser.add_argument('-blake2s',
                        metavar='Blake2s',
                        help='blake2s hash algorithm')
    parser.add_argument('-md5', help='MD5 hash algorithm')
    parser.add_argument('-sha1', help='Sha1 hash algorithm')
    parser.add_argument('-sha224', help='sha224 hash algorithm')
    parser.add_argument('-sha256', help='sha256 hash algorithm')
    parser.add_argument('-sha384', help='sha384 hash algorithm')
    parser.add_argument('-sha3-224', help='sha3/224 hash algorithm')
    parser.add_argument('-sha3-256', help='sha3/256 hash algorithm')
    parser.add_argument('-sha3-384', help='sha3/384 hash algorithm')
    parser.add_argument('-sha3-512', help='sha3/512 hash algorithm')
    parser.add_argument('-sha512', help='sha512 hash algorithm')
    parser.add_argument('-shake-128', help='shake-128 hash algorithm')
    parser.add_argument('-shake-256', help='shake-256 hash algorithm')

    arg = parser.parse_args()

    if len(sys.argv) < 2:
        print(parser.print_help())
    else:
        if arg.blake2b:
            hash = hashlib.blake2b(arg.blake2b.encode())
            hashing(hash)
        if arg.blake2s:
            hash = hashlib.blake2s(arg.blake2s.encode()).hexdigest()
            hashing(hash)
        if arg.md5:
            hash = hashlib.md5(arg.md5.encode()).hexdigest()
            hashing(hash)
        if arg.sha1:
            hash = hashlib.sha1(arg.sha1.encode()).hexdigest()
            hashing(hash)
        if arg.sha224:
            hash = haslib.sha224(arg.sha224.encode()).hexdigest()
            hashing(hash)
        if arg.sha384:
            hash = hashlib.sha384(arg.sha384.encode()).hexdigest()
            hashing(hash)
        if arg.sha512:
            hash = hashlib.sha512(arg.sha512.encode()).hexdigest()
            hashing(hash)
        if arg.sha3_224:
            hash = hashlib.sha3_224(arg.sha3_224.encode()).hexdigest()
            hashing(hash)
        if arg.sha3_256:
            hash = hashlib.sha3_256(arg.sha3_256.encode()).hexdigest()
            hashing(hash)
        if arg.sha3_384:
            hash = hashlib.sha3_384(arg.sha3_384.encode()).hexdigest()
            hashing(hash)
        if arg.sha3_512:
            hash = hashlib.sha3_512(arg.sha3_512.encode()).hexdigest()
            hashing(hash)
        if arg.sha512:
            hash = hashlib.sha512(arg.sha512.encode()).hexdigest()
            hashing(hash)
        if arg.shake_128:
            hash = hashlib.shake_128(arg.shake_128.encode()).hexdigest()
            hashing(hash)
        if arg.shake_256:
            hash = hashlib.shake_256(arg.shake_256.encode()).hexdigest()
            hashing(hash)
Ejemplo n.º 16
0
    def sign(self, message):

        # Initialize empty views[mpc_rounds][players]
        for _ in range(self.mpc_rounds):
            three_views = []
            for _ in range(3):
                single_view = View(self.blocksize, self.rounds, self.sboxes)
                three_views.append(single_view)
            self.__views.append(three_views)

        # Initialize empty commitments[mpc_rounds][players]
        for _ in range(self.mpc_rounds):
            three_commits = []
            for _ in range(3):
                single_commit = Commitment(self.hash_length, 0)
                three_commits.append(single_commit)
            self.__commitments.append(three_commits)

        # Initialize seeds
        # Get one long shake_128 hash with length (3 * mpc_rounds + 1) * (blocksize / 8)
        # and split it afterwards into seeds and one salt
        shake128 = hashlib.shake_128()
        shake128.update(bytes.fromhex(self.__priv_key.get_bitvector_in_hex()))
        shake128.update(message)
        shake128.update(
            bytes.fromhex(self.__pub_key.public_key.get_bitvector_in_hex()))
        shake128.update(bytes.fromhex(self.__pub_key.p.get_bitvector_in_hex()))
        shake128.update(bytes([self.blocksize, 0]))
        long_hash = shake128.digest(
            ((3 * self.mpc_rounds) + 1) * self.blocksize_bytes)

        count = 0
        for _ in range(self.mpc_rounds):
            three_seeds = []
            for _ in range(3):
                single_seed = BitVector(
                    rawbytes=long_hash[count:count + self.blocksize_bytes])
                count += self.blocksize_bytes
                three_seeds.append(single_seed)
            self.__seeds.append(three_seeds)
        self.__salt = BitVector(rawbytes=long_hash[count:count +
                                                   self.blocksize_bytes])

        # A hack for the last 5 bytes of the tmp_view_raw is needed
        # and this seems as a bug (or unwanted behaviour) in the ref-sourcecode so far.
        new_end_of_tmp_view = bytearray([0, 0, 0, 0, 0])

        # MPC Rounds
        for t in range(self.mpc_rounds):

            print("MPC round " + str(t))
            tapes = []
            self.__tapes_pos = 0

            # Create tapes[0..2] and i_shares
            for j in range(2):
                length = int(
                    (self.blocksize + 3 * self.rounds * self.sboxes) / 8)
                tmp_view_raw = self.mpc_create_random_tape(
                    self.__seeds[t][j], self.__salt, t, j,
                    length) + new_end_of_tmp_view
                self.__views[t][j].i_share = BitVector(
                    rawbytes=tmp_view_raw[0:self.blocksize_bytes])
                tapes.append(
                    BitVector(
                        rawbytes=tmp_view_raw[self.blocksize_bytes:length]))

            length_2 = int((3 * self.rounds * self.sboxes) / 8)
            tapes.append(
                BitVector(rawbytes=self.mpc_create_random_tape(
                    self.__seeds[t][2], self.__salt, t, 2, length_2)))
            self.__views[t][2].i_share = self.__priv_key ^ \
                                         self.__views[t][0].i_share ^ \
                                         self.__views[t][1].i_share

            # Run MPC
            new_end_of_tmp_view = self.run_mpc(t, tapes, tmp_view_raw)

            # Calculate the commitments
            self.mpc_commit(t)

        # Calculate challenges
        self.__challenges = self.h3(message)

        # Calculate proofs
        self.__proofs = self.prove()

        # Copy proofs, challenges and salt to self.__signature
        self.__signature.proofs = self.__proofs
        self.__signature.challenges = self.__challenges
        self.__signature.salt = self.__salt
Ejemplo n.º 17
0
def hash4(content: Union[bytes, str]) -> str:
    """Return a small 4 byte hash encoded as a hex string."""
    if isinstance(content, str):
        content = content.encode()
    return hashlib.shake_128(content).hexdigest(4)
Ejemplo n.º 18
0
def hash4(content: Union[bytes, str]) -> str:
    """Return a 4 byte hash encoded as a hex string."""
    if isinstance(content, str):
        content = content.encode()
    return hashlib.shake_128(content).hexdigest(4)  # pylint: disable=too-many-function-args
Ejemplo n.º 19
0
def aes256(x, y):
    A = bytearray()
    for Α, Ҙ in zip(x, hashlib.shake_128(y).digest(x.__len__())):
        A.append(Α ^ Ҙ)
    #print(A.decode("utf8"))
    return A
Ejemplo n.º 20
0
    def hash(self, string, hashtype='md5'):
        """
        def hash():
            Hashlib module wrapper.
        """

        string = string.encode()
        hashtype = hashtype.lower()
        if hashtype == 'blake2b':
            result = hashlib.blake2b(string).hexdigest()
            result = result.upper()
            return result

        elif hashtype == 'blake2s':
            result = hashlib.blake2s(string).hexdigest()
            result = result.upper()
            return result

        elif hashtype == 'sha3_224':
            result = hashlib.sha3_224(string).hexdigest()
            result = result.upper()
            return result

        elif hashtype == 'sha3_256':
            result = hashlib.sha3_256(string).hexdigest()
            result = result.upper()
            return result

        elif hashtype == 'sha3_384':
            result = hashlib.sha3_384(string).hexdigest()
            result = result.upper()
            return result

        elif hashtype == 'sha3_512':
            result = hashlib.sha3_512(string).hexdigest()
            result = result.upper()
            return result

        elif hashtype == 'shake_128':
            result = hashlib.shake_128(string).hexdigest()
            result = result.upper()
            return result

        elif hashtype == 'shake_256':
            result = hashlib.shake_256(string).hexdigest()
            result = result.upper()
            return result

        elif hashtype == 'md5':
            result = hashlib.md5(string).hexdigest()
            result = result.upper()
            return result

        elif hashtype == 'sha1':
            result = hashlib.sha1(string).hexdigest()
            result = result.upper()
            return result

        elif hashtype == 'sha224':
            result = hashlib.sha224(string).hexdigest()
            result = result.upper()
            return result

        elif hashtype == 'sha256':
            result = hashlib.sha256(string).hexdigest()
            result = result.upper()
            return result

        elif hashtype == 'sha384':
            result = hashlib.sha384(string).hexdigest()
            result = result.upper()
            return result

        elif hashtype == 'sha512':
            result = hashlib.sha512(string).hexdigest()
            result = result.upper()
            return result

        else:
            raise exceptions.UnknownHashTypeError("An unknown hash type is entered...")
Ejemplo n.º 21
0
import hashlib

# ハッシュ化する文字列(パスワード)など
password = '******'

print(hashlib.md5(password.encode("UTF-8")).hexdigest())
print(hashlib.sha1(password.encode("UTF-8")).hexdigest())
print(hashlib.sha224(password.encode("UTF-8")).hexdigest())
print(hashlib.sha256(password.encode("UTF-8")).hexdigest())
print(hashlib.sha384(password.encode("UTF-8")).hexdigest())
print(hashlib.sha512(password.encode("UTF-8")).hexdigest())
print(hashlib.blake2b(password.encode("UTF-8")).hexdigest())
print(hashlib.blake2s(password.encode("UTF-8")).hexdigest())
print(hashlib.sha3_224(password.encode("UTF-8")).hexdigest())
print(hashlib.sha3_256(password.encode("UTF-8")).hexdigest())
print(hashlib.sha3_384(password.encode("UTF-8")).hexdigest())
print(hashlib.sha3_512(password.encode("UTF-8")).hexdigest())
print(hashlib.shake_128(password.encode("UTF-8")).hexdigest(64))
print(hashlib.shake_256(password.encode("UTF-8")).hexdigest(64))
Ejemplo n.º 22
0
 def test_shake_128(self):
     hashlib_result = hashlib.shake_128(
         self.fpath.encode("utf-8")).hexdigest(32)
     copy2hash_result = copy2hash.HashTag(args={}).fpath2hash(
         self.fpath, sha_key="shake_128")
     assert hashlib_result == copy2hash_result
Ejemplo n.º 23
0
def round_fn(block_size, piece, key):
    # 16: 8 bits per byte, and 2 because half the block size
    return hashlib.shake_128(piece + key).digest(block_size //
                                                 16)  # XXX block size
Ejemplo n.º 24
0
 def _split(cls, token):
     return token[:32], hashlib.shake_128(binascii.unhexlify(
         token[32:])).hexdigest(16)
Ejemplo n.º 25
0
def api_shake_128():
    string_in = request.args.get("query")
    size = int(request.args.get("size"))
    res = hashlib.shake_128(string_in.encode()).digest(size)
    return jsonify({'result': str(res), 'algo': 'shake_128', 'size': size})
Ejemplo n.º 26
0
def _random_string():
    id_hash = hashlib.shake_128()
    id_hash.update(uuid.uuid4().bytes)
    id_bytes = id_hash.digest(ray_constants.ID_SIZE)
    assert len(id_bytes) == ray_constants.ID_SIZE
    return id_bytes
Ejemplo n.º 27
0
def passcode(game):
  return shake_128((SECRET_KEY + game.name).encode("utf8")).hexdigest(8)
Ejemplo n.º 28
0
 def checksum(self, data):
     h = hashlib.shake_128()
     h.update(data)
     return h.digest(CHECKSUM_SIZE)
Ejemplo n.º 29
0
def main(args):
    """With fixed initial seed, generate instances and save as C files

    Args:
        args (argparse.Namespace), with attributes:
            num_instances (int): how many instances to generate
            outdir (str): path to directory to save instances; must exist
            seed (int): seed to use for random.seed(). If -1, then seed by
                default Python seeding

    Returns: 0 if no error
    """
    # check args
    outdir = args.outdir
    seed = int(args.seed)
    num_instances = int(args.num_instances)
    taut_only = args.taut_only
    linear_only = args.linear_only

    # check paths
    outdir = os.path.abspath(os.path.expanduser(outdir))
    if not os.path.isdir(outdir):
        raise OSError("outdir does not exist: '{}'".format(outdir))

    # set seed
    if seed != -1:
        random.seed(seed)

    generators = [gen_cond_example_multi, gen_while_example_multi, gen_for_example_multi,
                  gen_fv_cond_example_multi, gen_fv_while_example_multi, gen_fv_for_example_multi]
    if linear_only:
        generators = [gen_tautonly_linear_example]
    num_generators = len(generators)

    # Generate metadata only if the metadata_file argument is present
    generate_metadata = args.metadata_file is not None
    # This dict is used to store instance metadata
    tag_metadata = {}
    inst_num = 0

    while inst_num < num_instances:
        # generate example
        gen = generators[inst_num % num_generators]
        if gen is gen_tautonly_linear_example:
            instance_str, tags = gen()
        else:
            include_cond_bufwrite = not taut_only
            instance_str, tags = gen(
                include_cond_bufwrite=include_cond_bufwrite)

        # generate filename
        byte_obj = bytes(instance_str, 'utf-8')
        fname = hashlib.shake_128(byte_obj).hexdigest(FNAME_HASHLEN)
        fname = "{}.c".format(fname)
        if fname in tag_metadata:
            # Collision, try again
            continue

        # insert record into metadata for this c file
        tag_metadata[fname] = [tag.value for tag in tags]
        inst_num += 1

        # write to file
        path = os.path.join(outdir, fname)
        with open(path, 'w') as f:
            f.write(instance_str)

    if generate_metadata:
        # construct the complete metadata
        metadata = {
            "working_dir": outdir,
            "num_instances": num_instances,
            "tags": tag_metadata
        }
        with open(args.metadata_file, 'w') as f:
            json.dump(metadata, f)
    return 0
Ejemplo n.º 30
0
    def parse_content(self, bs):
        print('parse content')
        try:
            new = bs
            print(bs)
            title = new.select('h4')[0].text

            m = hashlib.blake2b(digest_size=12)
            m.update(title.encode())
            hashed = m.hexdigest()

            date = None

            exist = session.query(models.Content).filter(models.Content.permanent_id == hashed).first()
            if exist:
                if date is None:
                    exist.created_at = datetime.utcnow() + timedelta(hours=9)
                else:
                    exist.created_at = date
                exist.origin = enums.DataOriginEnum.DOGDRIP
                session.commit()
                print('passed')
                return exist
            
            date = None
            for date_obj in new.select('div.ed.flex.flex-wrap.flex-left.flex-middle.title-toolbar span.ed.text-xsmall.text-muted'):
                text = date_obj.text
                delta = None
                if '일 전' in text:
                    delta = timedelta(days=int(text[0]))
                if '시간 전' in text:
                    delta = timedelta(hours=int(text[0]))
                if '분 전' in text:
                    delta = timedelta(minutes=int(text[0]))
                    
                if delta is not None:
                    date = datetime.utcnow() + timedelta(hours=9) - delta
                else:
                    try:
                        date = datetime.strptime(text, '%Y.%m.%d')
                    except:
                        print('continued')
                        continue
                    break
                    

            '''delta = None
            if '일 전' in date:
                delta = timedelta(days=int(date[0]))
            if '시간 전' in date:
                delta = timedelta(hours=int(date[0]))
            if '분 전' in date:
                delta = timedelta(minutes=int(date[0]))
            
            if delta is not None:
                date = datetime.utcnow() + timedelta(hours=9) - delta
            else:
                breakpoint()
                date = datetime.strptime(date, '%Y.%m.%d')'''
            
            # writer = new.select('div.ed.flex.flex-wrap.flex-left.flex-middle.title-toolbar > div.ed.flex.flex-wrap a')
            writer = new.select('div.title-toolbar span')[0].text.strip()
            writer = hashlib.shake_128(writer.encode()).hexdigest(length=4)

            user = models.User(nickname=writer)
            session.add(user)
            session.flush()

            # TODO 2: 작성자 아이디 구해와서 해싱
            # DOIT!

            content = new.select('div.ed.article-wrapper.inner-container > div.ed > div')[1]
            content = content.select('div')[0]
            # breakpoint()
            # content = new.select('div#article_1')[0]
            for img in content.select('img'):
                if 'img.sscroll.net' in img['src']:
                    print('continued')
                    continue
                if './' in img['src']:
                    img['src'] = img['src'].replace('./', 'http://www.dogdrip.net/')
                elif img['src'].startswith('/'):
                    img['src'] = 'https://www.dogdrip.net' + img['src']
                elif not img['src'].startswith('http'):
                    img['src'] = 'https://www.dogdrip.net/' + img['src']

                if 'transparent' in img['src']:
                    return

                for_img = hashlib.sha256(img['src'].encode())
                last = img['src'].split('.')[-1]
                rename = for_img.hexdigest()
                rename += '.' + last
                urllib.request.urlretrieve(img['src'], rename)
                s3.upload_file(rename, bucket, 'upload/' + rename, ExtraArgs={'ACL': 'public-read', 'CacheControl': 'max-age=2592000'})
                os.remove(rename)
                img['src'] = 'http://img.sscroll.net/upload/'+ rename
            
            for video in content.select('source'):
                if 'img.sscroll.net' in video['src']:
                    print('continued')
                    continue
                if './' in video['src']:
                    video['src'] = video['src'].replace('./', 'http://www.dogdrip.net/')
                elif video['src'].startswith('/'):
                    video['src'] = 'https://www.dogdrip.net' + video['src']
                elif not video['src'].startswith('http'):
                    video['src'] = 'https://www.dogdrip.net/' + video['src']

                if 'transparent' in video['src']:
                    return

                for_img = hashlib.sha256(video['src'].encode())
                last = video['src'].split('.')[-1]
                rename = for_img.hexdigest()
                rename += '.' + last
                urllib.request.urlretrieve(video['src'], rename)
                s3.upload_file(rename, bucket, 'upload/' + rename, ExtraArgs={'ACL': 'public-read', 'CacheControl': 'max-age=2592000'})
                os.remove(rename)
                video['src'] = 'http://img.sscroll.net/upload/'+ rename

            content = content.decode()
        except Exception as e:
            print('exit')
            traceback.print_tb(e.__traceback__)
            return
        item = models.Content(title=title, data=content, permanent_id=hashed, created_at=date, origin=enums.DataOriginEnum.DOGDRIP, uid=user.id)
        if item.created_at is None:
            item.created_at = datetime.utcnow() + timedelta(hours=9)
        
        data = new.select('script[type="text/javascript"]')[0].text
        try:
            up, down = filter(lambda x: x != '', re.compile('[0-9]*').findall(data))
            item.up = up
            item.down = down
        except:
            pass
        session.add(item)
        session.commit()
        print('added!')
        return item
Ejemplo n.º 31
0
def path_hash(path, length=8):
    return hashlib.shake_128(str(path.resolve()).encode()).hexdigest(length //
                                                                     2)