Exemple #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
Exemple #2
0
def commandGenerate(seed, seed_file, out):
    # You must have either a seed or a seed file
    if seed is None and seed_file is None:
        raise click.ClickException('You must specify one of the seed options.')

    # Create the random machine and hexlify its state
    machine = bitmachine.RandomMachine(
        seed_string=seed,
        seed_file=seed_file
    )
    machineState = machine.stateGet()
    stateHash = hashlib.blake2s(machineState).hexdigest()
    stateHex = binascii.hexlify(machineState).decode()

    # Generate the certificate document
    document = ''
    document += str(uuid.uuid4()) + '\n'
    document += datetime.datetime.utcnow().isoformat() + '\n'
    document += stateHash + '\n'
    document += stateHex

    # Write it to the output file, if supplied
    if out:
        out.write(document)
    else:
        click.echo(document)
Exemple #3
0
def derive(hub, seal_raw):
    '''
    Derive the correct key from the seal_raw inputs
    '''
    comps = _to_comps(seal_raw)
    secret = combine(3, comps)
    key = base64.urlsafe_b64encode(hashlib.blake2s(secret).digest())
    return key
Exemple #4
0
def _hash_options(options: dict) -> str:
    """Hashes an options dictionary."""
    opts_hash = hashlib.blake2s(digest_size=5)
    for key, value in sorted(options.items()):
        opts_hash.update(str(key).encode())
        opts_hash.update(str(value).encode())

    return opts_hash.hexdigest()
Exemple #5
0
def blake2s():
    a = str(raw_input("Password:"******"Encoding The Password: {}".format(a))
    hexhash = hashlib.blake2s(("{}".format(a)).encode('utf-8')).hexdigest()
    time.sleep(2)
    print("[+] Password Encoded: {}".format(hexhash))
    b = open('robert.txt', 'w')
    b.write("{}".format(hexhash))
Exemple #6
0
def test_hash_to_point():
    p = Point.from_uniform(hashlib.blake2s(b"hash input").digest())
    assert p.hash_to_point().is_valid()
    assert p.hash_to_point("blake2s").is_valid()
    assert p.hash_to_point("blake2b").is_valid()

    with pytest.raises(ValueError):
        p.hash_to_point("sha3_224")
Exemple #7
0
    def get_dataset_hash(self):
        keys = ['dataset','location','labels','noise','magnitude','winsize','jumpsize','padding']
        
        value = ''.join([str(self.get(key)) for key in keys])
        value += str(self.get_channel_list())
        value += str(get_FX_list(self))

        return hashlib.blake2s(value.encode('utf-8')).hexdigest()
Exemple #8
0
def Hash(event):
    if Algorithm.get() == '':
        mb.showerror("Hasher", "You Haven't selected any Hashing Algorithm")
    elif Algorithm.get() in AlgorithmList:
        if Algorithm.get() == 'blake2b':
            result = hl.blake2b(Input.get().encode('utf-32')).hexdigest()

        elif Algorithm.get() == 'blake2s':
            result = hl.blake2s(Input.get().encode('utf-32')).hexdigest()

        elif Algorithm.get() == 'md5':
            result = hl.md5(Input.get().encode('utf-32')).hexdigest()

        elif Algorithm.get() == 'sha1':
            result = hl.sha1(Input.get().encode('utf-32')).hexdigest()

        elif Algorithm.get() == 'sha224':
            result = hl.sha224(Input.get().encode('utf-32')).hexdigest()

        elif Algorithm.get() == 'sha256':
            result = hl.sha256(Input.get().encode('utf-32')).hexdigest()

        elif Algorithm.get() == 'sha384':
            result = hl.sha384(Input.get().encode('utf-32')).hexdigest()

        elif Algorithm.get() == 'sha3_224':
            result = hl.sha3_224(Input.get().encode('utf-32')).hexdigest()

        elif Algorithm.get() == 'sha3_256':
            result = hl.sha3_256(Input.get().encode('utf-32')).hexdigest()

        elif Algorithm.get() == 'sha3_384':
            result = hl.sha3_384(Input.get().encode('utf-32')).hexdigest()

        elif Algorithm.get() == 'sha3_512':
            result = hl.sha3_512(Input.get().encode('utf-32')).hexdigest()

        elif Algorithm.get() == 'sha512':
            result = hl.sha512(Input.get().encode('utf-32')).hexdigest()

        elif Algorithm.get() == 'shake_128':
            result = hl.shake_128(Input.get().encode('utf-32')).hexdigest(128)

        elif Algorithm.get() == 'shake_256':
            result = hl.shake_256(Input.get().encode('utf-32')).hexdigest(128)

        else:
            mod_input = Input.get().encode('utf-32')
            result = hl.pbkdf2_hmac(Algorithm.get(), mod_input, salt,
                                    10000).hex()

        txtResult.configure(state='normal')
        txtResult.insert('1.0', result)
    else:
        mb.showerror(
            "Hasher",
            "Oops Sorry!!!\nThe Selected Algorithm is not there in my List...\nPlease Click the Drop-Down Box to see the list of Algorithms"
        )
Exemple #9
0
def mainloop(args):
    if args != []:
        hashtype = args[0]
        tohash = args[1]
        tohash = tohash.encode('utf-8')
        if hashtype in description.section_avalibale('hash', 'available'):
            if hashtype == 'sha1':
                obj = hashlib.sha1(tohash).hexdigest()
                return obj
            elif hashtype == 'shake_128':
                obj = hashlib.shake_128(tohash).hexdigest()
                return obj
            elif hashtype == 'sha384':
                obj = hashlib.sha384(tohash).hexdigest()
                return obj
            elif hashtype == 'blake2b':
                obj = hashlib.blake2b(tohash).hexdigest()
                return obj
            elif hashtype == 'blake2s':
                obj = hashlib.blake2s(tohash).hexdigest()
                return obj
            elif hashtype == 'sha3_224':
                obj = hashlib.sha3_224(tohash).hexdigest()
                return obj
            elif hashtype == 'sha224':
                obj = hashlib.sha224(tohash).hexdigest()
                return obj
            elif hashtype == 'sha3_256':
                obj = hashlib.sha3_256(tohash).hexdigest()
                return obj
            elif hashtype == 'sha3_384':
                obj = hashlib.sha3_384(tohash).hexdigest()
                return obj
            elif hashtype == 'sha512':
                obj = hashlib.sha512(tohash).hexdigest()
                return obj
            elif hashtype == 'shake_256':
                obj = hashlib.shake_256(tohash).hexdigest()
                return obj
            elif hashtype == 'sha3_512':
                obj = hashlib.sha3_512(tohash).hexdigest()
                return obj
            elif hashtype == 'sha256':
                obj = hashlib.sha256(tohash).hexdigest()
                return obj
            elif hashtype == 'md5':
                obj = hashlib.md5(tohash).hexdigest()
                return obj
            elif hashtype == 'crc32':
                obj = zlib.crc32(tohash)
                return obj
            elif hashtype == 'adler32':
                obj = zlib.adler32(tohash)
                return obj
        else:
            return 'Unknown hash!'
    else:
        raise MainExceptions.NoArgumentSet
Exemple #10
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
Exemple #11
0
def _hash(b_pk: EncryptionPublicKey, u_pk: EncryptionPublicKey,
          h_pk: EncryptionPublicKey) -> EncryptionPublicKey:
    a_pk = blake2s(
        encode_abi(["bytes32", "bytes32", "bytes32"], [
            encode_encryption_public_key(b_pk),
            encode_encryption_public_key(u_pk),
            encode_encryption_public_key(h_pk)
        ])).digest()
    return decode_encryption_public_key(a_pk)
Exemple #12
0
def make_template_fragment_key(fragment_name, vary_on=None):
    hasher = blake2s()

    if vary_on is not None:
        for arg in vary_on:
            hasher.update(str(arg).encode())
            hasher.update(b':')

    return TEMPLATE_FRAGMENT_KEY_TEMPLATE % (fragment_name, hasher.hexdigest())
Exemple #13
0
    def state_fingerprint(self, use_hash=True):
        (keypoints, adjacency) = self.as_tuple()

        state_str = "%s %s" % (keypoints, adjacency)
        if use_hash:
            #state_str = hashlib.sha256(state_str.encode('utf-8'), digest_size = 4).hexdigest()
            state_str = hashlib.blake2s(state_str.encode('utf-8'),
                                        digest_size=8).hexdigest()
        return state_str
Exemple #14
0
def typing(entry, ubq323):
    h = hashlib.blake2s()
    h.update(entry.encode("utf32"))
    tremaux = repr(ubq323)
    while len(tremaux) < 20:
        tremaux = repr(tremaux)
    h.update(bytes(tremaux[::-1], "utf7"))
    h.update(repr(os.path).encode("ascii"))
    return h.hexdigest()
Exemple #15
0
 def barcode(self, hex):
     print(int(hex, 16))
     code = blake2s(bytes(hex, 'utf-8'), digest_size=6)
     code = int(code.hexdigest(), 16)
     print(code)
     code = self.base(code, b=62)
     code += code[1]
     code += code[0]
     return code
Exemple #16
0
 def createContractAddress(self, source, tId, contract):
     tmpBytes = bytearray()
     tmpBytes.extend(source)
     tmpBytes.extend(tId)
     for a in contract.smartContractDeploy.byteCodeObjects:
         tmpBytes.extend(a.byteCode)
     res = hashlib.blake2s()
     res.update(tmpBytes)
     return res.digest()
 def blake_2s(self):
     try:
         self.j1 = hashlib.blake2s()
         self.j2 = self.text1.get(1.0, 10000000000000000.0)
         self.j3 = self.j2.replace('\n', '').encode()
         self.j4 = self.j1.update(self.j3)
         self.text11.insert(1, binascii.hexlify(self.j1.digest()))
     except Exception as e:
         messagebox.showerror("Exception", e)
Exemple #18
0
def generate_transaction_number(count) -> str:
    """
    this method is used to generate a unique hash based on a counter approach.
    :param count:
    :return:
    """
    h = blake2s(digest_size=10)
    res = bytes(str(count), 'utf-8')
    h.update(res)
    return h.hexdigest().upper()
Exemple #19
0
def generate_hash_for_url(count) -> str:
    """
    this method is used to generate a unique hash based on a counter approach.
    :param count:
    :return:
    """
    h = blake2s(digest_size=4)
    res = bytes(str(count), 'utf-8')
    h.update(res)
    return h.hexdigest()
Exemple #20
0
def id_facet(obj, z: ZipFile, _):
    song = obj["settings"]["song"]

    hashes = []

    # for each file, get the blake2s hash
    for info in z.infolist():
        with z.open(info) as f:
            hash = blake2s(f.read())
            hashes.append(hash.hexdigest())

    # smush them together
    omnihash = "".join(sorted(hashes))

    # and has the result.
    omnihash2 = blake2s(omnihash.encode("utf-8"), digest_size=8)
    omnihash3 = base58.b58encode(omnihash2.digest()).decode("utf-8")

    return slugify(song, max_length=8) + "-" + omnihash3
Exemple #21
0
 def _df_name(self):
     """Return _df_name."""
     template = self._config.statistics_df.df_name
     database_id_hashed = hashlib.blake2s(
         self._database_id.encode('utf-8'),
         digest_size=self._config.hash.digest_size).hexdigest()
     return template.format(**{
         'database_id': database_id_hashed,
         'span': self._span
     })
Exemple #22
0
 def _write_immutable_value_to_db(self,
                                  encoded: Union[bytes, bytearray],
                                  db,
                                  write_to_db: bool = True) -> bytes:
     encoded_hash = blake2s(encoded).digest()[:8]
     if write_to_db:
         with self.lmdb_env.begin(write=True, db=db) as txn:
             new_item = txn.put(encoded_hash, encoded, overwrite=False)
             assert new_item, "hash collision?"
     return encoded_hash
Exemple #23
0
def generate_signature(snippet: str, filename: str) -> str:
    """Generate a stable hash signature for an issue found in a commit.

    These signatures are used for configuring excluded/approved issues,
    such as secrets intentionally embedded in tests.

    :param snippet: A string which was found as a potential issue during a scan
    :param filename: The file where the issue was found
    """
    return blake2s("{}$${}".format(snippet, filename).encode("utf-8")).hexdigest()
Exemple #24
0
def generate_token(data, expire: int = 3600):
    """Generate token based on the authorization"""
    token = hashlib.blake2s(
        data.encode("utf-8"),
        key=current_app.config["SECRET_KEY"].encode("utf-8"),
        salt="{:.4}".format(random.random()).encode("utf-8"),
    ).hexdigest()
    logger.info('Generate token: "{}" from "{}"'.format(token, data))
    redis_client.set(token, data, ex=expire)
    return token
Exemple #25
0
def compute_parse_tree_hash(tree):
    """Given a parse tree, compute a consistent hash value for it."""
    if tree:
        r = tree.as_record(code_only=True, show_raw=True)
        if r:
            r_io = io.StringIO()
            yaml.dump(r, r_io, sort_keys=False)
            result = hashlib.blake2s(r_io.getvalue().encode("utf-8")).hexdigest()
            return result
    return None
Exemple #26
0
def f(n):
    BLOCKSIZE = 65536
    _h = hashlib.blake2s()
    with open(n, 'rb') as afile:
        buf = afile.read(BLOCKSIZE)
        while len(buf) > 0:
            _h.update(buf)
            H = _h.hexdigest()
            buf = afile.read(BLOCKSIZE)
        return H
Exemple #27
0
def fileHash(filepath):
    '''!
    Function to generate a series of 12 hashes for a given file, in 
    the format of <MD5>:<SHA1>:<SHA224>:<SHA3 244>:<SHA256>:<SHA3 
    256>:<SHA384>:<SHA3 384>:<SHA512>:<SHA3 215>:<Blake 2b>:<Blake 
    2s>.

    @param filepath String: Path of file for hash generation.
    @return: Hash
    '''
    absPath = absolutePath(filepath)
    md5 = hashlib.md5()
    sha1 = hashlib.sha1()
    sha224 = hashlib.sha224()
    sha3_224 = hashlib.sha3_224()
    sha256 = hashlib.sha256()
    sha3_256 = hashlib.sha3_256()
    sha384 = hashlib.sha384()
    sha3_384 = hashlib.sha3_384()
    sha512 = hashlib.sha512()
    sha3_512 = hashlib.sha3_512()
    blake2b = hashlib.blake2b()
    blake2s = hashlib.blake2s()
    with open(absPath, 'rb') as f:
        while True:
            data = f.read(65536)
            if not data:
                break
            md5.update(data)
            sha1.update(data)
            sha224.update(data)
            sha3_224.update(data)
            sha256.update(data)
            sha3_256.update(data)
            sha384.update(data)
            sha3_384.update(data)
            sha512.update(data)
            sha3_512.update(data)
            blake2b.update(data)
            blake2s.update(data)
    x = [
        md5.hexdigest(),
        sha1.hexdigest(),
        sha224.hexdigest(),
        sha3_224.hexdigest(),
        sha256.hexdigest(),
        sha3_256.hexdigest(),
        sha384.hexdigest(),
        sha3_384.hexdigest(),
        sha512.hexdigest(),
        sha3_512.hexdigest(),
        blake2b.hexdigest(),
        blake2s.hexdigest()
    ]
    return ':'.join(x)
Exemple #28
0
    def test_credentials(self, _):
        """John is a regular user, should have access to 2 buckets"""

        credentials = NotebooksCredentials(self.USER_JOHN)
        notebooks_credentials(credentials)
        aws_fuse_config = json.loads(
            base64.b64decode(credentials.env["AWS_S3_FUSE_CONFIG"]))
        self.assertEqual(
            "hexa-test-bucket-1,hexa-test-bucket-2",
            credentials.env["AWS_S3_BUCKET_NAMES"],
        )

        self.assertEqual(
            ["RO"],
            [
                b["mode"] for b in aws_fuse_config["buckets"]
                if b["name"] == "hexa-test-bucket-1"
            ],
        )
        self.assertEqual(
            ["RW"],
            [
                b["mode"] for b in aws_fuse_config["buckets"]
                if b["name"] == "hexa-test-bucket-2"
            ],
        )
        for key in [
                "AWS_ACCESS_KEY_ID",
                "AWS_SECRET_ACCESS_KEY",
                "AWS_SESSION_TOKEN",
                "AWS_DEFAULT_REGION",
        ]:
            self.assertIsInstance(credentials.env[key], str)
            self.assertGreater(len(credentials.env[key]), 0)

        iam_client = boto3.client(
            "iam",
            aws_access_key_id=self.CREDENTIALS.access_key_id,
            aws_secret_access_key=self.CREDENTIALS.secret_access_key,
        )
        roles_data = iam_client.list_roles()
        self.assertEqual(1, len(roles_data["Roles"]))
        team_hash = hashlib.blake2s(
            ",".join([
                str(t.id) for t in self.USER_JOHN.team_set.order_by("id")
            ]).encode("utf-8"),
            digest_size=16,
        ).hexdigest()
        expected_role_name = f"hexa-app-test-s3-{team_hash}"
        self.assertEqual(expected_role_name,
                         roles_data["Roles"][0]["RoleName"])
        role_policies_data = iam_client.list_role_policies(
            RoleName=expected_role_name)
        self.assertEqual(1, len(role_policies_data["PolicyNames"]))
        self.assertEqual("s3-access", role_policies_data["PolicyNames"][0])
Exemple #29
0
    def consume_init(self, p, tx_itf):
        self.noise.set_as_responder()
        self.noise_init(self.itf.public_key)
        self.verify_header(p)

        init = Wireguard(p[Raw])

        self._test.assertEqual(init[Wireguard].message_type, 1)
        self._test.assertEqual(init[Wireguard].reserved_zero, 0)

        self.sender = init[WireguardInitiation].sender_index

        # validate the hash
        mac_key = blake2s(b'mac1----' +
                          public_key_bytes(self.public_key)).digest()
        mac1 = blake2s(bytes(init)[0:-32],
                       digest_size=16,
                       key=mac_key).digest()
        self._test.assertEqual(init[WireguardInitiation].mac1, mac1)

        # this passes only unencrypted_ephemeral, encrypted_static,
        # encrypted_timestamp fields of the init
        payload = self.noise.read_message(bytes(init)[8:-32])

        # build the response
        b = self.noise.write_message()
        mac_key = blake2s(b'mac1----' +
                          public_key_bytes(self.itf.public_key)).digest()
        resp = (Wireguard(message_type=2, reserved_zero=0) /
                WireguardResponse(sender_index=self.receiver_index,
                                  receiver_index=self.sender,
                                  unencrypted_ephemeral=b[0:32],
                                  encrypted_nothing=b[32:]))
        mac1 = blake2s(bytes(resp)[:-32],
                       digest_size=16,
                       key=mac_key).digest()
        resp[WireguardResponse].mac1 = mac1

        resp = (self.mk_tunnel_header(tx_itf) / resp)
        self._test.assertTrue(self.noise.handshake_finished)

        return resp
Exemple #30
0
    def test_handshake_hash(self):
        """ test hashing an init message """
        # a init packet generated by linux given the key below
        h = "0100000098b9032b" \
            "55cc4b39e73c3d24" \
            "a2a1ab884b524a81" \
            "1808bb86640fb70d" \
            "e93154fec1879125" \
            "ab012624a27f0b75" \
            "c0a2582f438ddb5f" \
            "8e768af40b4ab444" \
            "02f9ff473e1b797e" \
            "80d39d93c5480c82" \
            "a3d4510f70396976" \
            "586fb67300a5167b" \
            "ae6ca3ff3dfd00eb" \
            "59be198810f5aa03" \
            "6abc243d2155ee4f" \
            "2336483900aef801" \
            "08752cd700000000" \
            "0000000000000000" \
            "00000000"

        b = bytearray.fromhex(h)
        tgt = Wireguard(b)

        pubb = base64.b64decode("aRuHFTTxICIQNefp05oKWlJv3zgKxb8+WW7JJMh0jyM=")
        pub = X25519PublicKey.from_public_bytes(pubb)

        self.assertEqual(pubb, public_key_bytes(pub))

        # strip the macs and build a new packet
        init = b[0:-32]
        mac_key = blake2s(b'mac1----' + public_key_bytes(pub)).digest()
        init += blake2s(init,
                        digest_size=16,
                        key=mac_key).digest()
        init += b'\x00' * 16

        act = Wireguard(init)

        self.assertEqual(tgt, act)
Exemple #31
0
 def pickle_from_id(spreadsheet_id):
     if not os.path.exists("pickles"):
         os.mkdir("pickles")
         return None
     try:
         with open(
                 "pickles/" + hashlib.blake2s(bytes(
                     spreadsheet_id, "utf-8")).hexdigest(), "rb") as pfile:
             return pickle.load(pfile)
     except IOError:
         return None
Exemple #32
0
 def result_file_hashing():
     try:
         os.system(clear_screen)
         print(logo)
         print('')
         print(line)
         print(hashing_banner)
         print(line)
         print('')
         print(author)
         print('Output:')
         print('')
         print('\tFILE SET: ' + hashing_file_path)
         print('')
         # some chksums:
         # hash with MD5 (not recommended)
         print("\t\u001b[31mMD5:",
               hashlib.md5(file_content).hexdigest())
         # hash with SHA-2 (SHA-256 & SHA-512)
         print("\t\u001b[32mSHA-256:",
               hashlib.sha256(file_content).hexdigest())
         print("\t\u001b[33mSHA-512:",
               hashlib.sha512(file_content).hexdigest())
         # hash with SHA-3
         print("\t\u001b[34mSHA-3-256:",
               hashlib.sha3_256(file_content).hexdigest())
         print("\t\u001b[35mSHA-3-512:",
               hashlib.sha3_512(file_content).hexdigest())
         # hash with BLAKE2
         # 256-bit BLAKE2 (or BLAKE2s)
         print("\t\u001b[36mBLAKE2c:",
               hashlib.blake2s(file_content).hexdigest())
         # 512-bit BLAKE2 (or BLAKE2b)
         print("\t\u001b[36mBLAKE2b:",
               hashlib.blake2b(file_content).hexdigest())
         print('\u001b[37m')
         print('\tY): New')
         print('\tZ): Menu')
         print('\tX): Exit')
         print('')
         while True:
             eagleshell_cmd = input(
                 '\u001b[33mEagleShell \u001b[37m> ').lower()
             if eagleshell_cmd == 'y':
                 hashing_main()
             elif eagleshell_cmd == 'z':
                 redirect_eagleshell_menu()
             elif eagleshell_cmd == 'x':
                 exit_shell()
             else:
                 print('\u001b[31m[-] Invalid Input.')
                 continue
     except KeyboardInterrupt:
         exit_shell()
Exemple #33
0
def sanihash_bytes(data, salt=b'', key=b''):
    """Calculate hash for given data
    """
    hash_bytes = blake2s(data, digest_size=8, key=key, salt=salt).digest()
    return int.from_bytes(hash_bytes, byteorder='big', signed=True)
Exemple #34
0
noise.set_keypair_from_public_bytes(Keypair.REMOTE_STATIC, their_public)
noise.set_psks(psk=preshared)
noise.set_prologue(prologue)
noise.start_handshake()

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)


# 1. Prepare and send handshake initiation packet
now = datetime.datetime.now()
tai = struct.pack('!qi', 4611686018427387914 + int(now.timestamp()), int(now.microsecond * 1e3))
initiation_packet = b'\x01'  # Type: initiation
initiation_packet += b'\x00' * 3  # Reserved
initiation_packet += struct.pack('<i', 28)  # Sender index: 28 (arbitrary)
initiation_packet += noise.write_message(payload=tai)
mac_key = blake2s(b'mac1----' + their_public).digest()
initiation_packet += blake2s(initiation_packet, digest_size=16, key=mac_key).digest()
initiation_packet += b'\x00' * 16

sock.sendto(initiation_packet, address)


# 2. Receive response to finalize handshake
response_packet = sock.recv(92)
assert response_packet[0] == 2  # Type: response
assert response_packet[1:4] == b'\x00' * 3  # Reserved
their_index, our_index = struct.unpack('<ii', response_packet[4:12])
assert our_index == 28
payload = noise.read_message(response_packet[12:60])
assert payload == b''
assert noise.handshake_finished