Exemple #1
0
 def __init__(self, known_hash, data=b''):
     self.known_hash = known_hash
     if known_hash == Known_Hashes.blake2b:
         from pyblake2 import blake2b
         self.implem = blake2b()
     elif known_hash == Known_Hashes.blake2s:
         from pyblake2 import blake2s
         self.implem = blake2s()
     elif known_hash == Known_Hashes.sha3:
         self.implem = hashlib.new('sha3_256')
     else:
         self.implem = hashlib.new(known_hash.name, data)
Exemple #2
0
 def from_id(cls, id):
     """
     This decodes an ID to a public key and verifies the checksum byte. ID
     structure in miniLock is the base58 encoded form of the public key
     appended with a single-byte digest from blake2s of the public key, as a
     simple check-sum.
     """
     decoded = cls.ensure_bytes(base58.b58decode(id))
     assert_type_and_length('id', decoded, bytes, L=33)
     pk = nacl.public.PublicKey(decoded[:-1])
     cs = decoded[-1:]
     if cs != pyblake2.blake2s(pk.encode(), 1).digest():
         raise ValueError("Public Key does not match its attached checksum byte: id='{}', decoded='{}', given checksum='{}', calculated checksum={}".format(id, decoded, cs, pyblake2.blake2s(pk.encode(), 1).digest()))
     return cls(pk)
Exemple #3
0
 def encode(self, hash_name, payload, expected_code):
     multihasher = multihash.new(hash_name)
     if hash_name == "blake2s":
         reference_hasher = pyblake2.blake2s()
     elif hash_name == "blake2b":
         reference_hasher = pyblake2.blake2b()
     elif hash_name == "sha3":
         reference_hasher = hashlib.new("sha3_256")
     else:
         reference_hasher = hashlib.new(hash_name)
     multihasher.update(payload.encode("utf8"))
     reference_hasher.update(payload.encode("utf8"))
     self.assertTrue(multihasher.hexdigest().endswith(reference_hasher.hexdigest()))
     self.assertEqual(multihasher.digest()[0], expected_code)
     self.assertEqual(multihasher.digest()[1], len(reference_hasher.digest()))
Exemple #4
0
 def from_passphrase(cls, email, passphrase):
     """
     This performs key derivation from an email address and passphrase according
     to the miniLock specification.
     
     Specifically, the passphrase is digested with a standard blake2s 32-bit digest,
     then it is passed through scrypt with the email address as salt value using
     N = 217, r = 8, p = 1, L = 32.
     
     The 32-byte digest from scrypt is then used as the Private Key from which
     the public key is derived.
     """
     pp_blake = pyblake2.blake2s(cls.ensure_bytes(passphrase)).digest()
     #pp_scrypt = scrypt.hash(pp_blake, cls.ensure_bytes(email), 2**17, 8, 1, 32)
     pp_scrypt = pylibscrypt.scrypt(pp_blake, cls.ensure_bytes(email), 2**17, 8, 1, 32)
     key = nacl.public.PrivateKey(pp_scrypt)
     return cls(key.public_key, key)
Exemple #5
0
    def firmware_update(self, fp):
        if self.features.bootloader_mode is False:
            raise RuntimeError("Device must be in bootloader mode")

        data = fp.read()

        resp = self.call(proto.FirmwareErase(length=len(data)))
        if isinstance(resp, proto.Failure
                      ) and resp.code == proto.FailureType.FirmwareError:
            return False

        # TREZORv1 method
        if isinstance(resp, proto.Success):
            fingerprint = hashlib.sha256(data[256:]).hexdigest()
            LOG.debug("Firmware fingerprint: " + fingerprint)
            resp = self.call(proto.FirmwareUpload(payload=data))
            if isinstance(resp, proto.Success):
                return True
            elif isinstance(resp, proto.Failure
                            ) and resp.code == proto.FailureType.FirmwareError:
                return False
            raise RuntimeError("Unexpected result %s" % resp)

        # TREZORv2 method
        if isinstance(resp, proto.FirmwareRequest):
            import pyblake2
            while True:
                payload = data[resp.offset:resp.offset + resp.length]
                digest = pyblake2.blake2s(payload).digest()
                resp = self.call(
                    proto.FirmwareUpload(payload=payload, hash=digest))
                if isinstance(resp, proto.FirmwareRequest):
                    continue
                elif isinstance(resp, proto.Success):
                    return True
                elif isinstance(
                        resp, proto.Failure
                ) and resp.code == proto.FailureType.FirmwareError:
                    return False
                raise RuntimeError("Unexpected result %s" % resp)

        raise RuntimeError("Unexpected message %s" % resp)
Exemple #6
0
 def new(cls, file_name, file_or_contents, sender, recipients):
     """
     Constructs (that is, encrypts) a new miniLock file from sender to recipients.
     """
     assert_type_and_length('recipients', recipients, list, minL=1)
     assert_type_and_length('sender', sender, UserLock)
     for R in recipients:
         assert_type_and_length('recipient', R, (str, UserLock))   
     recipients = list(set(recipients))
     # Encrypt file with secret key using file_contents and file_name
     file_key   = os.urandom(32)
     file_nonce = os.urandom(16)
     file_cipher = SymmetricMiniLock.from_key(file_key)
     ciphertext = b''.join(file_cipher.encrypt(file_or_contents, file_name, file_nonce))
     file_info = {
         'fileKey'   : b64encode(file_key),
         'fileNonce' : b64encode(file_nonce),
         'fileHash'  : b64encode(pyblake2.blake2s(ciphertext).digest())
     }
     header = MiniLockHeader.new(file_info, sender, recipients)
     b_header = header.to_bytes()
     encrypted_file = b'miniLock' + len(b_header).to_bytes(4, 'little') + b_header + ciphertext
     return cls(encrypted_file)
Exemple #7
0
 def decrypt(self, recipient_key):
     """
     recipient_key: UserLock with a private key part.
     returns: filename, decrypted file contents
     """
     if recipient_key.private_key is None:
         raise ValueError("Cannot decrypt with this key; no private key part found.")
     header = MiniLockHeader(self.header)
     # Create ephemeral public key for authenticated decryption of metadata.
     # TODO: Future-proof this by making it try to decrypt a b58 ephem ID if available?
     decryptInfo = header.decrypt(recipient_key)
     file_info = decryptInfo['fileInfo']
     file_hash = file_info['fileHash']
     if not b64decode(file_hash) == pyblake2.blake2s(self.chunks_block).digest():
         raise ValueError("ciphertext does not match given hash!")
     symbox = SymmetricMiniLock.from_key(b64decode(file_info['fileKey']))
     filename, *filechunks = symbox.decrypt(self.chunks_block, b64decode(file_info['fileNonce']))
     try:
         filename = filename.decode('utf8')
     except Exception as E:
         raise ValueError("Cannot decode filename to UTF8 string: '{}'".format(filename))
     sender = decryptInfo['senderID']
     return filename, sender, b''.join(filechunks)
Exemple #8
0
def validate_firmware(filename):
    with open(filename, "rb") as f:
        data = f.read()
    if data[:6] == b"54525a":
        data = bytes.fromhex(data.decode())

    try:
        fw = Firmware.parse(data)
    except Exception as e:
        raise ValueError("Invalid firmware image format") from e

    vendor = fw.vendor_header
    header = fw.firmware_header

    print("Vendor header from {}, version {}.{}".format(
        vendor.vendor_string, vendor.version.major, vendor.version.minor))
    print("Firmware version {v.major}.{v.minor}.{v.patch} build {v.build}".
          format(v=header.version))

    # rebuild header without signatures
    stripped_header = header.copy()
    stripped_header.sigmask = 0
    stripped_header.signature = b"\0" * 64
    header_bytes = FirmwareHeader.build(stripped_header)
    digest = pyblake2.blake2s(header_bytes).digest()

    print("Fingerprint: {}".format(digest.hex()))

    global_pk = cosi.combine_keys(vendor.pubkeys[i] for i in range(8)
                                  if header.sigmask & (1 << i))

    try:
        cosi.verify(header.signature, digest, global_pk)
        print("Signature OK")
    except Exception:
        print("Signature FAILED")
        raise
Exemple #9
0
def update(client, data):
    if client.features.bootloader_mode is False:
        raise RuntimeError("Device must be in bootloader mode")

    resp = client.call(messages.FirmwareErase(length=len(data)))

    # TREZORv1 method
    if isinstance(resp, messages.Success):
        resp = client.call(messages.FirmwareUpload(payload=data))
        if isinstance(resp, messages.Success):
            return
        else:
            raise RuntimeError("Unexpected result %s" % resp)

    # TREZORv2 method
    while isinstance(resp, messages.FirmwareRequest):
        payload = data[resp.offset : resp.offset + resp.length]
        digest = pyblake2.blake2s(payload).digest()
        resp = client.call(messages.FirmwareUpload(payload=payload, hash=digest))

    if isinstance(resp, messages.Success):
        return
    else:
        raise RuntimeError("Unexpected message %s" % resp)
Exemple #10
0
def update(client, data):
    if client.features.bootloader_mode is False:
        raise RuntimeError("Device must be in bootloader mode")

    resp = client.call(messages.FirmwareErase(length=len(data)))

    # TREZORv1 method
    if isinstance(resp, messages.Success):
        resp = client.call(messages.FirmwareUpload(payload=data))
        if isinstance(resp, messages.Success):
            return
        else:
            raise RuntimeError("Unexpected result %s" % resp)

    # TREZORv2 method
    while isinstance(resp, messages.FirmwareRequest):
        payload = data[resp.offset : resp.offset + resp.length]
        digest = pyblake2.blake2s(payload).digest()
        resp = client.call(messages.FirmwareUpload(payload=payload, hash=digest))

    if isinstance(resp, messages.Success):
        return
    else:
        raise RuntimeError("Unexpected message %s" % resp)
Exemple #11
0
class Multihash(object):
    """
    Superclass for all kinds of hashes, this is for convenience in passing things around between some places that want binary, or
    multihash or hex.

    core storage is as a multihash_binary i.e. [ code, length, digest...]

    Each instance:
    code = SHA1, SHA256 etc (uses integer conventions from multihash
    """

    # Constants
    # 0x01..0x0F are app specific (unused)
    SHA1 = 0x11
    SHA2_256 = 0x12
    SHA2_512 = 0x13
    SHA3 = 0x14
    BLAKE2B = 0x40
    BLAKE2S = 0x41

    FUNCS = {
        SHA1: hashlib.sha1,
        SHA2_256: hashlib.sha256,
        # Alternative use nacl.hash.sha256(data, encoder=nacl.encoding.RawEncoder) which has different footprint
        SHA2_512: hashlib.sha512,
        SHA3: lambda: hashlib.new('sha3_512'),
        BLAKE2B: lambda: pyblake2.blake2b(),
        BLAKE2S: lambda: pyblake2.blake2s(),
    }
    LENGTHS = {
        SHA1: 20,
        SHA2_256: 32,
        SHA2_512: 64,
        SHA3: 64,
        BLAKE2B: 64,
        BLAKE2S: 32,
    }

    def assertions(self, code=None):
        if code and code != self.code:
            raise MultihashError(
                message="Expecting code {}, got {}".format(code, self.code))
        if self.code not in self.FUNCS:
            raise MultihashError(
                message="Unsupported Hash type {}".format(self.code))
        if (self.digestlength != len(self.digest)) or (
                self.digestlength != self.LENGTHS[self.code]):
            raise MultihashError(
                message="Invalid lengths: expect {}, byte {}, len {}".format(
                    self.LENGTHS[self.code], self.digestlength, len(
                        self.digest)))

    def __init__(self,
                 multihash58=None,
                 sha1hex=None,
                 data=None,
                 code=None,
                 url=None):
        """
        Accept variety of parameters,

        :param multihash_58:
        """
        digest = None

        if url:  # Assume its of the form somescheme:/somescheme/Q...
            logging.debug("url={} {}".format(url.__class__.__name__, url))
            if isinstance(url, str) and "/" in url:  # https://.../Q...
                url = urlparse(url)
            if not isinstance(url, str):
                multihash58 = url.path.split('/')[-1]
            else:
                multihash58 = url
            if multihash58[0] not in (
                    '5', 'Q'):  # Simplistic check that it looks ok-ish
                raise MultihashError(message="Invalid hash portion of URL {}".
                                     format(multihash58))
        if multihash58:
            self._multihash_binary = base58.b58decode(multihash58)
        if sha1hex:
            if python_version.startswith('2'):
                digest = sha1hex.decode('hex')  # Python2
            else:
                digest = bytes.fromhex(sha1hex)  # Python3
            code = self.SHA1
        if data and code:
            digest = self._hash(code, data)
        if digest and code:
            self._multihash_binary = bytearray([code, len(digest)])
            self._multihash_binary.extend(digest)
        self.assertions()  # Check consistency

    def _hash(self, code, data):
        if not code in self.FUNCS:
            raise MultihashError(
                message="Cant encode hash code={}".format(code))
        hashfn = self.FUNCS.get(code)(
        )  # Note it calls the function in that strange way hashes work!
        if isinstance(data, bytes):
            hashfn.update(data)
        elif isinstance(data, str):
            # In Python 3 this is ok, would be better if we were sure it was utf8
            # raise MultihashError(message="Should be passing bytes, not strings as could encode multiple ways")  # TODO can remove this if really need to handle UTF8 strings, but better to push conversion upstream
            hashfn.update(data.encode('utf-8'))
        return hashfn.digest()

    def check(self, data):
        assert self.digest == self._hash(self.code,
                                         data), "Hash doesnt match expected"

    @property
    def code(self):
        return self._multihash_binary[0]

    @property
    def digestlength(self):
        return self._multihash_binary[1]

    @property
    def digest(self):
        """
        :return: bytes, the digest part of any multihash
        """
        return self._multihash_binary[2:]

    @property
    def sha1hex(self):
        """
        :return: The hex of the sha1 (as used in DOI sqlite tables)
        """
        self.assertions(self.SHA1)
        return binascii.hexlify(self.digest).decode(
            'utf-8')  # The decode is turn bytes b'a1b2' to str 'a1b2'

    @property
    def multihash58(self):
        foo = base58.b58encode(
            bytes(self._multihash_binary)
        )  # Documentation says returns bytes, Mac returns string, want string
        if isinstance(foo, bytes):
            return foo.decode('ascii')
        else:
            return foo
Exemple #12
0
def main(hashmes, s, v, c):
    """
    If there is a file at hashme, read and omnihash that file.
    Elif hashme is a string, omnihash that.
    """

    # Print version and quit
    if v:
        import pkg_resources
        version = pkg_resources.require("omnihash")[0].version
        click.echo(version)
        return

    for hashme in hashmes:
        # URL
        if not s and validators.url(hashme):
            click.echo("Hashing content of URL '%s'.." % hashme)
            try:
                response = requests.get(hashme)
            except requests.exceptions.ConnectionError as e:
                print ("Not a valid URL. :(")
                continue
            except Exception as e:
                print ("Not a valid URL. %s" % e)
                continue                
            if response.status_code != 200:
                click.echo("Response returned %s. :(" % response.status_code)
                continue
            hashme_data = response.content
        # File
        elif os.path.exists(hashme) and not s:
            click.echo("Hashing file %s.." % hashme)
            with open(hashme, mode='rb') as f:
                hashme_data = f.read()
                hashme_data = hashme_data.encode('utf-8')
        # String
        else:
            click.echo("Hashing string '%s'.." % hashme)
            hashme_data = hashme.encode('utf-8')

        # Default Algos
        done = []
        for algo in sorted(hashlib.algorithms_available):

            # algorithms_available can have duplicates
            if algo.upper() in done:
                continue
                
            h = hashlib.new(algo)
            h.update(hashme_data)
            echo(algo, h.hexdigest())
            done.append(algo)

        # SHA3 Family
        sha = sha3.SHA3224()
        sha.update(hashme_data)
        echo('SHA3_224', sha.hexdigest().decode("utf-8"))

        sha = sha3.SHA3256()
        sha.update(hashme_data)
        echo('SHA3_256', sha.hexdigest().decode("utf-8"))

        sha = sha3.SHA3384()
        sha.update(hashme_data)
        echo('SHA3_384', sha.hexdigest().decode("utf-8"))

        sha = sha3.SHA3512()
        sha.update(hashme_data)
        echo('SHA3_512', sha.hexdigest().decode("utf-8"))

        # BLAKE
        blake = blake2s()
        blake.update(hashme_data)
        echo('BLAKE2s', blake.hexdigest())
        
        blake = blake2b()
        blake.update(hashme_data)
        echo('BLAKE2b', blake.hexdigest())

        # CRC
        if c:
            for name in sorted(crcmod.predefined._crc_definitions_by_name):
                crc_name = crcmod.predefined._crc_definitions_by_name[name]['name']
                crc_func = crcmod.predefined.mkCrcFun(crc_name)
                echo(crc_name.upper(), hex(crc_func(hashme_data)))
    'blake2b': 64,
    'blake2s': 32,
}

FUNCS = {
    SHA1: hashlib.sha1,
    SHA2_256: hashlib.sha256,
    SHA2_512: hashlib.sha512,
}

if sha3:
    FUNCS[SHA3] = lambda: hashlib.new('sha3_512')

if pyblake2:
    FUNCS[BLAKE2B] = lambda: pyblake2.blake2b()
    FUNCS[BLAKE2S] = lambda: pyblake2.blake2s()


def _hashfn(hashfn):
    """Return an initialised hash object, by function, name or integer id

    >>> _hashfn(SHA1) # doctest: +ELLIPSIS
    <sha1 HASH object @ 0x...>

    >>> _hashfn('sha2-256') # doctest: +ELLIPSIS
    <sha256 HASH object @ 0x...>
    >>> _hashfn('18') # doctest: +ELLIPSIS
    <sha256 HASH object @ 0x...>

    >>> _hashfn('md5')
    Traceback (most recent call last):
Exemple #14
0
# rebuild zcash main net genesis block
### Assertions
genesisSerEq = x(
    '040000000000000000000000000000000000000000000000000000000000000000000000db4d7a85b768123f1dff1d4c4cece70083b2d27e117b4ac2e31d087988a5eac4000000000000000000000000000000000000000000000000000000000000000090041358ffff071f'
)
hashMerkleRoot = lx(
    'c4eaa58879081de3c24a7b117ed2b28300e7ec4c4c1dff1d3f1268b7857a4ddb')
hashGenesis = lx(
    '00040fe8ec8471911baa1db1266ea15dd06b4a8a5c453883c000b031973dce08')
##############
genesisSol = x(
    '000a889f00854b8665cd555f4656f68179d31ccadc1b1f7fb0952726313b16941da348284d67add4686121d4e3d930160c1348d8191c25f12b267a6a9c131b5031cbf8af1f79c9d513076a216ec87ed045fa966e01214ed83ca02dc1797270a454720d3206ac7d931a0a680c5c5e099057592570ca9bdf6058343958b31901fce1a15a4f38fd347750912e14004c73dfe588b903b6c03166582eeaf30529b14072a7b3079e3a684601b9b3024054201f7440b0ee9eb1a7120ff43f713735494aa27b1f8bab60d7f398bca14f6abb2adbf29b04099121438a7974b078a11635b594e9170f1086140b4173822dd697894483e1c6b4e8b8dcd5cb12ca4903bc61e108871d4d915a9093c18ac9b02b6716ce1013ca2c1174e319c1a570215bc9ab5f7564765f7be20524dc3fdf8aa356fd94d445e05ab165ad8bb4a0db096c097618c81098f91443c719416d39837af6de85015dca0de89462b1d8386758b2cf8a99e00953b308032ae44c35e05eb71842922eb69797f68813b59caf266cb6c213569ae3280505421a7e3a0a37fdf8e2ea354fc5422816655394a9454bac542a9298f176e211020d63dee6852c40de02267e2fc9d5e1ff2ad9309506f02a1a71a0501b16d0d36f70cdfd8de78116c0c506ee0b8ddfdeb561acadf31746b5a9dd32c21930884397fb1682164cb565cc14e089d66635a32618f7eb05fe05082b8a3fae620571660a6b89886eac53dec109d7cbb6930ca698a168f301a950be152da1be2b9e07516995e20baceebecb5579d7cdbc16d09f3a50cb3c7dffe33f26686d4ff3f8946ee6475e98cf7b3cf9062b6966e838f865ff3de5fb064a37a21da7bb8dfd2501a29e184f207caaba364f36f2329a77515dcb710e29ffbf73e2bbd773fab1f9a6b005567affff605c132e4e4dd69f36bd201005458cfbd2c658701eb2a700251cefd886b1e674ae816d3f719bac64be649c172ba27a4fd55947d95d53ba4cbc73de97b8af5ed4840b659370c556e7376457f51e5ebb66018849923db82c1c9a819f173cccdb8f3324b239609a300018d0fb094adf5bd7cbb3834c69e6d0b3798065c525b20f040e965e1a161af78ff7561cd874f5f1b75aa0bc77f720589e1b810f831eac5073e6dd46d00a2793f70f7427f0f798f2f53a67e615e65d356e66fe40609a958a05edb4c175bcc383ea0530e67ddbe479a898943c6e3074c6fcc252d6014de3a3d292b03f0d88d312fe221be7be7e3c59d07fa0f2f4029e364f1f355c5d01fa53770d0cd76d82bf7e60f6903bc1beb772e6fde4a70be51d9c7e03c8d6d8dfb361a234ba47c470fe630820bbd920715621b9fbedb49fcee165ead0875e6c2b1af16f50b5d6140cc981122fcbcf7c5a4e3772b3661b628e08380abc545957e59f634705b1bbde2f0b4e055a5ec5676d859be77e20962b645e051a880fddb0180b4555789e1f9344a436a84dc5579e2553f1e5fb0a599c137be36cabbed0319831fea3fddf94ddc7971e4bcf02cdc93294a9aab3e3b13e3b058235b4f4ec06ba4ceaa49d675b4ba80716f3bc6976b1fbf9c8bf1f3e3a4dc1cd83ef9cf816667fb94f1e923ff63fef072e6a19321e4812f96cb0ffa864da50ad74deb76917a336f31dce03ed5f0303aad5e6a83634f9fcc371096f8288b8f02ddded5ff1bb9d49331e4a84dbe1543164438fde9ad71dab024779dcdde0b6602b5ae0a6265c14b94edd83b37403f4b78fcd2ed555b596402c28ee81d87a909c4e8722b30c71ecdd861b05f61f8b1231795c76adba2fdefa451b283a5d527955b9f3de1b9828e7b2e74123dd47062ddcc09b05e7fa13cb2212a6fdbc65d7e852cec463ec6fd929f5b8483cf3052113b13dac91b69f49d1b7d1aec01c4a68e41ce157'
)

pszTimestamp = 'Zcash' + blake2s(
    b'The Economist 2016-10-29 Known unknown: Another crypto-currency is born. BTC#436254 0000000000000000044f321997f336d2908cf8c8d6893e88dbf067e2d949487d ETH#2521903 483039a6b6bd8bd05f0584f9a078d075e454925eb71c1f13eaff59b405a721bb DJIA close on 27 Oct 2016: 18,169.68'
).hexdigest()

pk = x(
    '04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f'
)
bits = 0x1f07ffff
scriptSig = CScript() + bits + b'\x04' + pszTimestamp.encode('UTF-8')
txin = CMutableTxIn(scriptSig=scriptSig)

scriptPubKey = CScript() + pk + OP_CHECKSIG
txout = CMutableTxOut(nValue=0, scriptPubKey=scriptPubKey)
tx = CMutableTransaction(vin=[txin], vout=[txout])

assert tx.GetTxid() == hashMerkleRoot
Exemple #15
0
#!/usr/bin/env python3
import glob
import pyblake2

ALIGNED_SIZE = 128 * 1024

files = glob.glob("bootloader*.bin")

for fn in sorted(files):
    data = open(fn, "rb").read()
    if len(data) > ALIGNED_SIZE:
        raise ValueError(fn, "too big")
    data_00 = data + b"\x00" * (ALIGNED_SIZE - len(data))
    data_ff = data + b"\xff" * (ALIGNED_SIZE - len(data))
    h_00 = pyblake2.blake2s(data=data_00).digest()
    h_ff = pyblake2.blake2s(data=data_ff).digest()
    h_00 = "".join(["\\x%02x" % i for i in h_00])
    h_ff = "".join(["\\x%02x" % i for i in h_ff])
    print(
        "    // %s (padded with 0x00)\n    if (0 == memcmp(hash, \"%s\", 32)) return sectrue;"
        % (fn, h_00))
    print(
        "    // %s (padded with 0xff)\n    if (0 == memcmp(hash, \"%s\", 32)) return sectrue;"
        % (fn, h_ff))
Exemple #16
0
def plugin_pyblake2_digesters(include_CRCs=False):
    import pyblake2  # @UnresolvedImport

    known_digesters['BLAKE2s'] = (pyblake2.blake2s(), lambda d: d.hexdigest())
    known_digesters['BLAKE2b'] = (pyblake2.blake2b(), lambda d: d.hexdigest())
Exemple #17
0
def batch(verify): # batching the database
	if verify != "OK": # if the user does not enter OK they are not going to run the script.
		print("Use the same command with 'OK' to verify you have enough storage.")
		raise argparse.ArgumentTypeError('')
		exit(1)

	c.execute("""SELECT DISTINCT ASCII FROM hashlist WHERE CALC='0'""") # select only one version of the term in case of duplication
	rows = c.fetchall() # get the output of the SQLite query
	count = 0 # set a counter.
	for ASCII in tqdm(rows, desc="Batching", smoothing=0.1, unit=" w"): # create a loop with a progress bar
		ASCII 		= ASCII[0] # the tupule is now a string.
		BASE32		= base64.b32encode(ASCII) # encode the string in Base32
		BASE64		= base64.b64encode(ASCII) # encode the string in Base64
		MD5 		= hashlib.md5(ASCII).hexdigest() # encode the string in MD5
		SHA1 		= hashlib.sha1(ASCII).hexdigest() # ...
		SHA224 		= hashlib.sha224(ASCII).hexdigest()
		SHA256 		= hashlib.sha256(ASCII).hexdigest()
		SHA384 		= hashlib.sha384(ASCII).hexdigest()
		SHA512 		= hashlib.sha512(ASCII).hexdigest()
		NTLM 		= hashlib.new('md4', ASCII.encode('utf-16le')).hexdigest() # encode the string in NTLM
		BLAKE2B 	= pyblake2.blake2b(ASCII.encode('utf-8')).hexdigest()
		BLAKE2S 	= pyblake2.blake2s(ASCII.encode('utf-8')).hexdigest()
		HMAC		= hmac.new(ASCII.encode('utf-8')).hexdigest()
		base32qry 	= "UPDATE hashlist SET BASE32 = ? WHERE ASCII = ?" # make a query to update the current string to have its alternative forms as an entry.
		base64qry 	= "UPDATE hashlist SET BASE64 = ? WHERE ASCII = ?" # ...
		md5qry 		= "UPDATE hashlist SET MD5 = ? WHERE ASCII = ? "
		sha1qry 	= "UPDATE hashlist SET SHA1 = ? WHERE ASCII = ? "
		sha224qry 	= "UPDATE hashlist SET SHA224 = ? WHERE ASCII = ?"
		sha256qry 	= "UPDATE hashlist SET SHA256 = ? WHERE ASCII = ?"
		sha384qry 	= "UPDATE hashlist SET SHA384 = ? WHERE ASCII = ?"
		sha512qry 	= "UPDATE hashlist SET SHA512 = ? WHERE ASCII = ?"
		NTLMqry 	= "UPDATE hashlist SET NTLM = ? WHERE ASCII = ?"
		BLAKE2Bqry 	= "UPDATE hashlist SET BLAKE2B = ? WHERE ASCII = ?"
		BLAKE2Sqry 	= "UPDATE hashlist SET BLAKE2S = ? WHERE ASCII = ?"
		HMACqry 	= "UPDATE hashlist SET HMAC = ? WHERE ASCII = ?"
		base32data      = (BASE32, ASCII) # the command that will combine both to apply the change of the entry.
		base64data      = (BASE64, ASCII) # ...
		md5data 	= (MD5, ASCII)
		sha1data 	= (SHA1, ASCII)
		sha224data 	= (SHA224, ASCII)
		sha256data 	= (SHA256, ASCII)
		sha384data 	= (SHA384, ASCII)
		sha512data 	= (SHA512, ASCII)
		ntlmdata 	= (NTLM, ASCII)
		blake2bdata = (BLAKE2B, ASCII)
		blake2sdata = (BLAKE2S, ASCII)
		hmacdata   	= (HMAC, ASCII)
		c.execute(base32qry, base32data) # execute the query.
		c.execute(base64qry, base64data) # ...
		c.execute(md5qry, md5data)
		c.execute(sha1qry, sha1data)
		c.execute(sha224qry, sha224data)
		c.execute(sha256qry, sha256data)
		c.execute(sha384qry, sha384data)
		c.execute(sha512qry, sha512data)
		c.execute(NTLMqry, ntlmdata)
		c.execute(BLAKE2Bqry, blake2bdata)
		c.execute(BLAKE2Sqry, blake2sdata)
		c.execute(HMACqry, hmacdata)
		update  = "UPDATE hashlist SET CALC=? WHERE ASCII = ? " # set the row CALC to 1 as it doesn't need to be hashed again.
		updatedata = ("1", ASCII)
		c.execute(update, updatedata)
		count +=1
		if count == 1000: # automatically commit every 1000 reps.
			conn.commit() # commit the changes.
			count= 0
	print("Indexing database ...")
	c.execute('''CREATE UNIQUE INDEX "HASHED" ON "hashlist" ("BASE32","BASE64","MD5","SHA1","SHA224","SHA256","SHA384","SHA512", "NTLM", "BLAKE2B", "BLAKE2S", "HMAC");''') # index the changes as it will make searching MUCH faster.
	conn.commit() # commit changes
	print("Done.")
Exemple #18
0
def py_blake2s():
    s = blake2s(digest_size=32)
    s.update(b'Hello World')
    return s.hexdigest()
Exemple #19
0
def test_blake2bs_32():
    h = blake2s(digest_size=32)
    h.update(b'Hello World')
    assert len(h.digest()) == 32
    assert h.hexdigest(
    ) == '7706af019148849e516f95ba630307a2018bb7bf03803eca5ed7ed2c3c013513'
Exemple #20
0
def hash(data):
    return blake2s(data, digest_size=BLAKE2S_256_SIZE).digest()
Exemple #21
0
def blake2s(outputformat, importx, inputformat, raw, infilepath, outfilepath):

    if importx == 'file':

        f = open(infilepath, 'r')
        raw = f.read()
        f.close()

    elif importx == 'print':

        raw = raw

    else:

        print('\033[1;31m[-]\033[0m Unknown error.')
        return False

    inp = raw

    if inputformat == 'base64':

        iput = base64.b64decode(inp)

    elif inputformat == 'raw':

        iput = inp

    elif inputformat == 'base32':

        iput = base64.b32decode(inp)

    elif inputformat == 'base16':

        iput = base64.b16decode(inp)

    elif inputformat == 'base58':

        iput = base58.b58decode(inp)

    elif inputformat == 'base85':

        print('\033[1;31m[-]\033[0m Option not available yet')

    elif inputformat == 'hex':

        iput = inp.decode('hex')

    elif inputformat == 'dec':

        print('\033[1;31m[-]\033[0m Option not available yet')

    elif inputformat == 'octal':

        print('\033[1;31m[-]\033[0m Option not available yet')

    elif inputformat == 'binary':

        iput = text_from_bits(inp)

    else:

        print('\033[1;31m[-]\033[0m Unknown error.')
        return False

    m = pyblake2.blake2s()
    m.update(iput)
    out = m.digest()

    if outputformat == 'base64':

        output = base64.b64encode(out)

    elif outputformat == 'raw':

        output = out

    elif outputformat == 'base32':

        output = base64.b32encode(out)

    elif outputformat == 'base16':

        output = base64.b16encode(out)

    elif outputformat == 'base58':

        output = base58.b58encode(out)

    elif outputformat == 'base85':

        print('\033[1;31m[-]\033[0m Option not available yet')

    elif outputformat == 'hex':

        output = out.encode('hex')

    elif outputformat == 'dec':

        print('\033[1;31m[-]\033[0m Option not available yet')

    elif outputformat == 'octal':

        print('\033[1;31m[-]\033[0m Option not available yet')

    elif outputformat == 'binary':

        output = text_to_bits(out)

    else:

        print('\033[1;31m[-]\033[0m Unknown error.')
        return False

    return output
Exemple #22
0
def crh_ivk(ak, nk):
    digest = blake2s(person=b'Zcashivk')
    digest.update(ak)
    digest.update(nk)
    ivk = digest.digest()
    return leos2ip(ivk) % 2**251
def prf_nf_sapling(nk_star, rho_star):
    digest = blake2s(person=b'Zcash_nf')
    digest.update(nk_star)
    digest.update(rho_star)
    return digest.digest()
Exemple #24
0
 def userID(self):
     return base58.b58encode(   self.public_key.encode() + 
                         pyblake2.blake2s(self.public_key.encode(), 1).digest() )
Exemple #25
0
    'blake2b': 64,
    'blake2s': 32,
}

FUNCS = {
    SHA1: hashlib.sha1,
    SHA2_256: hashlib.sha256,
    SHA2_512: hashlib.sha512,
}

if sha3:
    FUNCS[SHA3] = lambda: hashlib.new('sha3_512')

if pyblake2:
    FUNCS[BLAKE2B] = lambda: pyblake2.blake2b()
    FUNCS[BLAKE2S] = lambda: pyblake2.blake2s()


def _hashfn(hashfn):
    if six.callable(hashfn):
        return hashfn()

    elif isinstance(hashfn, six.integer_types):
        return FUNCS[hashfn]()

    elif isinstance(hashfn, six.string_types):
        if hashfn in NAMES:
            return FUNCS[NAMES[hashfn]]()

        elif hashfn.isdigit():
            return _hashfn(int(hashfn))
Exemple #26
0
def blake2s_hmac(packet):
    # h = hmac.new(KEY2, digestmod=hashlib.blake2s)
    h = pyblake2.blake2s(digest_size=DIG_SIZE2, key=KEY2)
    h.update(packet)
    # print("Digest Size: " + str(h.digest_size) )
    return h.digest()
Exemple #27
0
def mixhash(hash, data):
    return blake2s(hash + data, digest_size=BLAKE2S_256_SIZE).digest()
def hashing(get_input):
    #encoding code for hexadecimal conversion
    encoded_input = get_input.encode()
    print("-" * 80)
    '''
    #md2
    m=MD2.new()
    m.update(get_input)
    print(G+"{+}The MD2 Hash Value Of Your Input Is {+}: "+m.hexdigest())
    '''

    #md4
    m = hashlib.new("md4")
    m.update(get_input)
    md4_hash = m.hexdigest()
    print(G + "{+}The MD4 Hash Value Of Your Input Is {+}: " + Y + md4_hash)

    #md5
    md5_hash = hashlib.md5(encoded_input)
    print(G + "{+}The MD5 Hash Value Of Your Input Is {+}: " + Y +
          md5_hash.hexdigest())

    #md5 crypt
    from passlib.hash import md5_crypt as mc
    md5_crypt = mc.encrypt(get_input)
    print(G + "{+}The MD5 Crypt Hash Value Of Your Input Is {+}: " + Y +
          md5_crypt)

    #sun md5 crypt
    from passlib.hash import sun_md5_crypt as mc
    sunmd5_crypt = mc.encrypt(get_input)
    print(G + "{+}The Sun MD5 Crypt Hash Value Of Your Input Is {+}: " + Y +
          sunmd5_crypt)

    #apache's md5 crypt
    from passlib.hash import apr_md5_crypt as mc
    apachemd5_crypt = mc.encrypt(get_input)
    print(G + "{+}The Apache MD5 Crypt Hash Value Of Your Input Is {+}: " + Y +
          apachemd5_crypt)

    #sha1
    sha1_hash = hashlib.sha1(encoded_input)
    print(G + "{+}The SHA1 Hash Value Of Your Input Is {+}: " + Y +
          sha1_hash.hexdigest())

    #sha224
    sha224_hash = hashlib.sha224(encoded_input)
    print(G + "{+}The SHA224 Hash Value Of Your Input Is {+}: " + Y +
          sha224_hash.hexdigest())

    #sha256
    sha256_hash = hashlib.sha256(encoded_input)
    print(G + "{+}The SHA256 Hash Value Of Your Input Is {+}: " + Y +
          sha256_hash.hexdigest())

    #sha384
    sha384_hash = hashlib.sha384(encoded_input)
    print(G + "{+}The SHA384 Hash Value Of Your Input Is {+}: " + Y +
          sha384_hash.hexdigest())

    #sha512
    sha512_hash = hashlib.sha512(encoded_input)
    print(G + "{+}The SHA512 Hash Value Of Your Input Is {+}: " + Y +
          sha512_hash.hexdigest())

    #sha1 Crypt
    from passlib.hash import sha1_crypt as mc
    sha1 = mc.encrypt(get_input)
    print(G + "{+}The SHA1 Crypt Hash Value Of Your Input Is {+}: " + Y + sha1)

    #sha256 Crypt
    from passlib.hash import sha256_crypt as mc
    sha256_crypt = mc.encrypt(get_input)
    print(G + "{+}The SHA256 Crypt Hash Value Of Your Input Is {+}: " + Y +
          sha256_crypt)

    # Sha512 crypt
    from passlib.hash import sha512_crypt as mc
    sha512_crypt = mc.encrypt(get_input)
    print(G + "{+}The SHA512 Crypt Hash Value Of Your Input Is {+}: " + Y +
          sha512_crypt)

    #django sha1
    from passlib.hash import django_pbkdf2_sha1 as m25
    django_sha1 = m25.encrypt(get_input)
    print(G + "{+}The Django HMAC SHA1 Hash Value Of Your Input Is {+}: " + Y +
          django_sha1)

    #django sha256
    from passlib.hash import django_pbkdf2_sha256 as m25
    django_sha256 = m25.encrypt(get_input)
    print(G + "{+}The Django HMAC SHA256 Hash Value Of Your Input Is {+}: " +
          Y + django_sha256)
    '''
    #ntlm
    ntlm_hash=hashlib.new('md4', "password".encode('utf-16le')).digest()
    print(G+"{+}The NTLM Hash Value Of Your Input Is {+}: "+ntlm_hash)
    '''

    #blake2b
    from pyblake2 import blake2b
    h = blake2b()
    h.update(get_input)
    blake2b_hash = h.hexdigest()
    print(G + "{+}The Blake2b Hash Value Of Your Input Is {+}: " + Y +
          blake2b_hash)

    #blake2s
    from pyblake2 import blake2s
    h = blake2s()
    h.update(get_input)
    blake2s_hash = h.hexdigest()
    print(G + "{+}The Blake2s Hash Value Of Your Input Is {+}: " + Y +
          blake2s_hash)

    #whirlpool
    m = hashlib.new("whirlpool")
    m.update(get_input)
    whirlpool_hash = m.hexdigest()
    print(G + "{+}The Whirlpool Hash Value Of Your Input Is {+}: " + Y +
          whirlpool_hash)

    #ripemd160
    m = hashlib.new("ripemd160")
    m.update(get_input)
    ripemd160_hash = m.hexdigest()
    print(G + "{+}The Ripemd160 Hash Value Of Your Input Is {+}: " + Y +
          ripemd160_hash)

    #crc32
    crc32_value = zlib.crc32(get_input)
    crc32 = '%08X' % (crc32_value & 0xffffffff, )
    print(G + "{+}The CRC32 Hash Value Of Your Input Is {+}: " + Y +
          crc32.lower())

    #adler32
    adler32_value = zlib.adler32(get_input)
    adler32 = '%08X' % (adler32_value & 0xffffffff, )
    print(G + "{+}The Adler32 Hash Value Of Your Input Is {+}: " + Y +
          adler32.lower())

    #des
    from passlib.hash import des_crypt
    des_hash = des_crypt.encrypt(get_input)
    print(G + "{+}The DES Hash Value Of Your Input Is {+}: " + Y + des_hash)

    #bsdicrypt
    from passlib.hash import bsdi_crypt
    bsdi_hash = bsdi_crypt.encrypt(get_input)
    print(G + "{+}The BSDI Hash Value Of Your Input Is {+}: " + Y + bsdi_hash)

    #bigcrypt
    from passlib.hash import bigcrypt
    big_hash = bigcrypt.encrypt(get_input)
    print(G + "{+}The BigCrypt Hash Value Of Your Input Is {+}: " + Y +
          big_hash)

    #crypt16
    from passlib.hash import crypt16
    crypt16_hash = crypt16.encrypt(get_input)
    print(G + "{+}The Crypt16 Hash Value Of Your Input Is {+}: " + Y +
          crypt16_hash)

    #phppass
    from passlib.hash import phpass as mc
    phpass = mc.encrypt(get_input)
    print(G + "{+}The PHPass Hash Value Of Your Input Is {+}: " + Y + phpass)

    #Cryptacular's PBDF2
    from passlib.hash import cta_pbkdf2_sha1 as mc
    cryp_pbkdf2_sha1 = mc.encrypt(get_input)
    print(G + "{+}The Cryptacular's PBDF2 Hash Value Of Your Input Is {+}: " +
          Y + cryp_pbkdf2_sha1)

    #dwayne PBDF2
    from passlib.hash import dlitz_pbkdf2_sha1 as mc
    dwayne_pbkdf2_sha1 = mc.encrypt(get_input)
    print(G + "{+}The Dwayne PBDF2 Hash Value Of Your Input Is {+}: " + Y +
          dwayne_pbkdf2_sha1)

    #Atlassian's PBKDF2 Hash
    from passlib.hash import cta_pbkdf2_sha1 as mc
    atl_pbkdf2_sha1 = mc.encrypt(get_input)
    print(G +
          "{+}The Atlassin's PBKDF2 SHA1 Hash Value Of Your Input Is {+}: " +
          Y + atl_pbkdf2_sha1)

    #grub pbkdf2
    from passlib.hash import grub_pbkdf2_sha512 as m25
    grub_pbkdf2_sha512 = m25.encrypt(get_input)
    print(G + "{+}The Grub PBKDF2 SHA512 Hash Value Of Your Input Is {+}: " +
          Y + grub_pbkdf2_sha512)

    #scram
    from passlib.hash import scram as mc
    scram = mc.encrypt(get_input)
    print(G + "{+}The Scram Hash Value Of Your Input Is {+}: " + Y + scram)

    #freebsd nthash
    from passlib.hash import bsd_nthash as mc
    bsd_nthash = mc.encrypt(get_input)
    print(G + "{+}The BSD1 NTHash Value Of Your Input Is {+}: " + Y +
          bsd_nthash)

    #oracle11
    from passlib.hash import oracle11 as m25
    oracle11 = m25.encrypt(get_input)
    print(G + "{+}The Oracle11G Hash Value Of Your Input Is {+}: " + Y +
          oracle11)

    #lanManager
    from passlib.hash import lmhash as m25
    lmhash = m25.encrypt(get_input)
    print(G + "{+}The LMHash Hash Value Of Your Input Is {+}: " + Y + lmhash)

    #nthash
    from passlib.hash import nthash as m25
    nthash = m25.encrypt(get_input)
    print(G + "{+}The Windows-Nthash Hash Value Of Your Input Is {+}: " + Y +
          nthash)

    #cisco type 7
    from passlib.hash import cisco_type7 as m25
    cisco = m25.encrypt(get_input)
    print(G + "{+}The CISCO Type-7 Hash Value Of Your Input Is {+}: " + Y +
          cisco)

    #fshp
    from passlib.hash import fshp as m25
    fshp = m25.encrypt(get_input)
    print(
        G +
        "{+}The FSHP-Fairly Secured Hashed Password Hash Value Of Your Input Is {+}: "
        + Y + fshp)

    #mysql323
    from passlib.hash import mysql323
    mysql323hash = mysql323.encrypt(get_input)
    print(G + "{+}The MySQL 3.2.3 Hash Value Of Your Input Is {+}: " + Y +
          mysql323hash)

    #mysql41
    from passlib.hash import mysql41
    mysql141hash = mysql41.encrypt(get_input)
    print(G + "{+}The MySQL 4.1 Hash Value Of Your Input Is {+}: " + Y +
          mysql141hash)

    #mssql2000
    from passlib.hash import mssql2000 as m20
    mssql2000hash = m20.encrypt(get_input)
    print(G + "{+}The MS-SQL 2000 Hash Value Of Your Input Is {+}: " + Y +
          mssql2000hash)

    #mssql2005
    from passlib.hash import mssql2005 as m25
    mssql2005hash = m25.encrypt(get_input)
    print(G + "{+}The MS-SQL 2005 Hash Value Of Your Input Is {+}: " + Y +
          mssql2005hash)
def _header_digest(header: c.Container, header_type: c.Construct) -> bytes:
    stripped_header = header.copy()
    stripped_header.sigmask = 0
    stripped_header.signature = b"\0" * 64
    header_bytes = header_type.build(stripped_header)
    return pyblake2.blake2s(header_bytes).digest()
Exemple #30
0
    def datagramReceived(self, data, src):
        # Supports only the Initiation message of WireGuard protocol
        #
        # All other message types and non-conforming data are dropped
        #
        if len(data) != MSG_INITIATION_LEN or not data.startswith(
                MSG_INITIATION_PREFIX):
            return

        # MAC offsets at the end of message
        smac2 = len(data) - BLAKE2S_128_SIZE
        smac1 = smac2 - BLAKE2S_128_SIZE

        device = None
        for deviceCandidate in self.devices:
            mac1 = blake2s(data[:smac1],
                           digest_size=BLAKE2S_128_SIZE,
                           key=deviceCandidate.mac1_key).digest()
            if (mac1 == data[smac1:smac2]):
                device = deviceCandidate
                break

        if not device:
            print("Could not find matching public key for message")
            return

        mtype, sessionIndex, ephemeral, static, timestamp, mac1, mac2 = struct.unpack(
            MSG_INITIATION_FMT, data)

        hash = mixhash(INITIAL_HASH, device.privateKey.public_key.encode())
        hash = mixhash(hash, ephemeral)
        chainKey = mixKey(INITIAL_CHAIN_KEY, ephemeral)
        ss = sharedSecret(device.privateKey.encode(), ephemeral)
        chainKey, key = KDF2(chainKey, ss)
        peerPK = AEAD(key, ZERO_NONCE, static, hash)

        hash = mixhash(hash, static)
        chainKey, key = KDF2(chainKey,
                             sharedSecret(device.privateKey.encode(), peerPK))
        tai64nTimestamp = AEAD(key, ZERO_NONCE, timestamp, hash)
        if not tai64nTimestamp:
            log.debug(
                "Timestamp not valid; Handshake not provably sent by peer key")
            return

        unix_seconds, nano = struct.unpack("!QI", tai64nTimestamp)
        unix_seconds -= TAI64N_BASE
        time_diff = abs(int(time.time()) - unix_seconds)
        if time_diff > MSG_INITIATION_MAX_TIME_DIFF:
            log.debug("Handshake timestamp too new or too old")
            return

        public_key = base64.b64encode(peerPK)
        canarytoken = queries.wireguard_keymap_get(public_key)
        if not canarytoken:
            log.debug(
                "No matching token for valid handshake with client key {} from {}. Expected when Canarytoken is deleted, but WG client config still in use."
                .format(public_key, src))
            return

        event = {
            'src_ip': src[0],
            'src_data': {
                'src_port':
                src[1],
                'server_public_key':
                device.privateKey.public_key.encode(
                    encoder=nacl.encoding.Base64Encoder),
                'client_public_key':
                public_key,
                'session_index':
                sessionIndex
            }
        }
        print(event)
        self.channel.dispatch(canarytoken=canarytoken, **event)