def verify(self, received_mac_tag):
        """Validate the *binary* authentication tag (MAC).

        The receiver invokes this method at the very end, to
        check if the associated data (if any) and the decrypted
        messages are valid.

        :param bytes/bytearray/memoryview received_mac_tag:
            This is the 16-byte *binary* MAC, as received from the sender.
        :Raises ValueError:
            if the MAC does not match. The message has been tampered with
            or the key is incorrect.
        """

        if self.verify not in self._next:
            raise TypeError("verify() cannot be called"
                            " when encrypting a message")
        self._next = (self.verify,)

        secret = get_random_bytes(16)

        self._compute_mac()

        mac1 = BLAKE2s.new(digest_bits=160, key=secret,
                           data=self._mac_tag)
        mac2 = BLAKE2s.new(digest_bits=160, key=secret,
                           data=received_mac_tag)

        if mac1.digest() != mac2.digest():
            raise ValueError("MAC check failed")
Exemple #2
0
    def verify(self, received_mac_tag):
        """Validate the *binary* MAC tag.

        The caller invokes this function at the very end.

        This method checks if the decrypted message is indeed valid
        (that is, if the key is correct) and it has not been
        tampered with while in transit.

        :Parameters:
          received_mac_tag : byte string
            This is the *binary* MAC, as received from the sender.
        :Raises MacMismatchError:
            if the MAC does not match. The message has been tampered with
            or the key is incorrect.
        """

        if self.verify not in self._next:
            raise TypeError("verify() cannot be called"
                                " when encrypting a message")
        self._next = [self.verify]

        if not self._mac_tag:
            tag = bchr(0) * self.block_size
            for i in range(3):
                tag = strxor(tag, self._omac[i].digest())
            self._mac_tag = tag[:self._mac_len]

        secret = get_random_bytes(16)

        mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=self._mac_tag)
        mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=received_mac_tag)

        if mac1.digest() != mac2.digest():
            raise ValueError("MAC check failed")
Exemple #3
0
    def verify(self, received_mac_tag):
        """Validate the *binary* MAC tag.

        The caller invokes this function at the very end.

        This method checks if the decrypted message is indeed valid
        (that is, if the key is correct) and it has not been
        tampered with while in transit.

        :Parameters:
          received_mac_tag : bytes/bytearray/memoryview
            This is the *binary* MAC, as received from the sender.
        :Raises ValueError:
            if the MAC does not match. The message has been tampered with
            or the key is incorrect.
        """

        if self.verify not in self._next:
            raise TypeError("verify() cannot be called"
                            " when encrypting a message")
        self._next = [self.verify]

        if self._mac_tag is None:
            self._mac_tag = self._kdf.derive()

        secret = get_random_bytes(16)

        mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=self._mac_tag)
        mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=received_mac_tag)

        if mac1.digest() != mac2.digest():
            raise ValueError("MAC check failed")
    def verify(self, received_mac_tag):
        """Validate the *binary* MAC tag.

        Call this method after the final `decrypt` (the one with no arguments)
        to check if the message is authentic and valid.

        :Parameters:
          received_mac_tag : byte string
            This is the *binary* MAC, as received from the sender.
        :Raises ValueError:
            if the MAC does not match. The message has been tampered with
            or the key is incorrect.
        """

        if self.verify not in self._next:
            raise TypeError("verify() cannot be called now for this cipher")

        assert(len(self._cache_P) == 0)

        self._next = [self.verify]

        if self._mac_tag is None:
            self._compute_mac_tag()

        secret = get_random_bytes(16)
        mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=self._mac_tag)
        mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=received_mac_tag)

        if mac1.digest() != mac2.digest():
            raise ValueError("MAC check failed")
        def testSignVerify(self):
            rng = Random.new().read
            key = RSA.generate(1024, rng)

            for hashmod in (MD2, MD5, SHA1, SHA224, SHA256, SHA384, SHA512, RIPEMD160):
                hobj = hashmod.new()
                hobj.update(b('blah blah blah'))

                signer = PKCS.new(key)
                signature = signer.sign(hobj)
                signer.verify(hobj, signature)

            # Blake2b has variable digest size
            for digest_bits in (160, 256, 384, 512):
                hobj = BLAKE2b.new(digest_bits=digest_bits)
                hobj.update(b("BLAKE2b supports several digest sizes"))

                signer = PKCS.new(key)
                signature = signer.sign(hobj)
                signer.verify(hobj, signature)

            # Blake2s too
            for digest_bits in (128, 160, 224, 256):
                hobj = BLAKE2s.new(digest_bits=digest_bits)
                hobj.update(b("BLAKE2s supports several digest sizes"))

                signer = PKCS.new(key)
                signature = signer.sign(hobj)
                signer.verify(hobj, signature)
Exemple #6
0
    def verify(self, received_mac_tag):
        """Validate the *binary* MAC tag.

        The caller invokes this function at the very end.

        This method checks if the decrypted message is indeed valid
        (that is, if the key is correct) and it has not been
        tampered with while in transit.

        :Parameters:
          received_mac_tag : byte string
            This is the *binary* MAC, as received from the sender.
        :Raises ValueError:
            if the MAC does not match. The message has been tampered with
            or the key is incorrect.
        """

        if self.verify not in self._next:
            raise TypeError("verify() cannot be called"
                                " when encrypting a message")
        self._next = [self.verify]

        if not self._mac_tag:

            if self._assoc_len is None:
                self._start_ccm(assoc_len=self._signer.data_signed_so_far())
            if self._msg_len is None:
                self._start_ccm(msg_len=0)

            # Both associated data and payload are concatenated with the least
            # number of zero bytes (possibly none) that align it to the
            # 16 byte boundary (A.2.2 and A.2.3)
            self._signer.zero_pad()

            # Step 8 in 6.1 (T xor MSB_Tlen(S_0))
            self._mac_tag = strxor(self._signer.digest(),
                                   self._s_0)[:self._mac_len]

        secret = get_random_bytes(16)

        mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=self._mac_tag)
        mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=received_mac_tag)

        if mac1.digest() != mac2.digest():
            raise ValueError("MAC check failed")
Exemple #7
0
    def verify(self, mac_tag):
        """Verify that a given **binary** MAC (computed by another party) is valid.

        :Parameters:
          mac_tag : byte string
            The expected MAC of the message.
        :Raises ValueError:
            if the MAC does not match. It means that the message
            has been tampered with or that the MAC key is incorrect.
        """

        secret = get_random_bytes(16)

        mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=mac_tag)
        mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=self.digest())

        if mac1.digest() != mac2.digest():
            raise ValueError("MAC check failed")
    def runTest(self):

        key = RSA.generate(1024)
        signer = pkcs1_15.new(key)
        hash_names = ("MD2", "MD4", "MD5", "RIPEMD160", "SHA1",
                      "SHA224", "SHA256", "SHA384", "SHA512",
                      "SHA3_224", "SHA3_256", "SHA3_384", "SHA3_512")

        for name in hash_names:
            hashed = load_hash_by_name(name).new(b("Test"))
            signer.sign(hashed)

        from Crypto.Hash import BLAKE2b, BLAKE2s
        for hash_size in (20, 32, 48, 64):
            hashed_b = BLAKE2b.new(digest_bytes=hash_size, data=b("Test"))
            signer.sign(hashed_b)
        for hash_size in (16, 20, 28, 32):
            hashed_s = BLAKE2s.new(digest_bytes=hash_size, data=b("Test"))
            signer.sign(hashed_s)
    def runTest(self):

        key = RSA.generate(1024)
        signer = pkcs1_15.new(key)
        hash_names = ("MD2", "MD4", "MD5", "RIPEMD160", "SHA1",
                      "SHA224", "SHA256", "SHA384", "SHA512",
                      "SHA3_224", "SHA3_256", "SHA3_384", "SHA3_512")

        for name in hash_names:
            hashed = load_hash_by_name(name).new(b("Test"))
            signer.sign(hashed)

        from Crypto.Hash import BLAKE2b, BLAKE2s
        for hash_size in (20, 32, 48, 64):
            hashed_b = BLAKE2b.new(digest_bytes=hash_size, data=b("Test"))
            signer.sign(hashed_b)
        for hash_size in (16, 20, 28, 32):
            hashed_s = BLAKE2s.new(digest_bytes=hash_size, data=b("Test"))
            signer.sign(hashed_s)
Exemple #10
0
    def blake_2s(self, bits: int = 256, key: bytes = ""):
        """Get Blake-2s hash
        
        Performs BLAKE2s hashing on the input. BLAKE2s is a flavour of 
        the BLAKE cryptographic hash function that is optimized for 8- to 
        32-bit platforms and produces digests of any size between 1 and 32 bytes. 
        Supports the use of an optional key.
        
        Args:
            bits (int, optional): Number of digest bits, by default 256
            key (bytes, optional): Encryption secret key, by default ''
        
        Returns:
            Chepy: The Chepy object. 

        Examples:
            >>> Chepy("A").blake_2s(bits=128, key="key").output
            "4e33cc702e9d08c28a5e9691f23bc66a"
        """
        assert bits in [256, 160, 128], "Valid bits are 256, 160, 128"
        h = BLAKE2s.new(digest_bits=bits, key=key.encode())
        h.update(self._convert_to_bytes())
        self.state = h.hexdigest()
        return self
############################

# Method 1: Using SHA 256 to Hash the file:
from Crypto.Hash import SHA256
hash_M1 = SHA256.new(data=content)
print(hash_M1.digest())
# b'\xf6\xddpY\xae\xb4R\xe6Hl\xc0W]Y]V?@y\x1fBL\xf3GS\xb6\xbc\x0e\xacax2'
print(hash_M1.hexdigest())
# f6dd7059aeb452e6486cc0575d595d563f40791f424cf34753b6bc0eac617832

# source: https://pycryptodome.readthedocs.io/en/latest/src/hash/sha256.html
# source: https://nitratine.net/blog/post/how-to-hash-files-in-python/

# Method 2: Using BLAKE2S to Hash the file:
from Crypto.Hash import BLAKE2s
hash_M2 = BLAKE2s.new(digest_bits=256)
hash_M2.update(content)
print(hash_M2.digest())
# b'\xa6\xd4\xd9c\x80mP\xd1\x88\xbd[\xbcm\xebYr{\xb9\x1fU\x0b\xdf\x9bc\xaf\x05\x80\xef8\x92\xa1\x81'
print(hash_M2.hexdigest())
# a6d4d963806d50d188bd5bbc6deb59727bb91f550bdf9b63af0580ef3892a181

# source: https://pycryptodome.readthedocs.io/en/latest/src/hash/blake2s.html
# source: https://nitratine.net/blog/post/how-to-hash-files-in-python/

################################
### PART 2 - DATA ENCRYPTION ###
################################

# Method 1: Encrypting using AES (CBC):
from Crypto.Cipher import AES
Exemple #12
0
 def __init__(self):
     self.hasher = BLAKE2s.new(digest_bits=256)
Exemple #13
0
 def new(data=None):
     return BLAKE2s.new(digest_bits=256, data=data)
        def testSignVerify(self):
                        h = SHA1.new()
                        h.update(b('blah blah blah'))

                        class RNG(object):
                            def __init__(self):
                                self.asked = 0
                            def __call__(self, N):
                                self.asked += N
                                return Random.get_random_bytes(N)

                        key = RSA.generate(1024)

                        # Helper function to monitor what's request from MGF
                        global mgfcalls
                        def newMGF(seed,maskLen):
                            global mgfcalls
                            mgfcalls += 1
                            return bchr(0x00)*maskLen

                        # Verify that PSS is friendly to all hashes
                        for hashmod in (MD2,MD5,SHA1,SHA224,SHA256,SHA384,RIPEMD160):
                            h = hashmod.new()
                            h.update(b('blah blah blah'))

                            # Verify that sign() asks for as many random bytes
                            # as the hash output size
                            rng = RNG()
                            signer = PKCS.new(key, randfunc=rng)
                            s = signer.sign(h)
                            signer.verify(h, s)
                            self.assertEqual(rng.asked, h.digest_size)

                        # Blake2b has variable digest size
                        for digest_bits in (160, 256, 384):  # 512 is too long
                            hobj = BLAKE2b.new(digest_bits=digest_bits)
                            hobj.update(b("BLAKE2b supports several digest sizes"))

                            signer = PKCS.new(key)
                            signature = signer.sign(hobj)
                            signer.verify(hobj, signature)

                        # Blake2s too
                        for digest_bits in (128, 160, 224, 256):
                            hobj = BLAKE2s.new(digest_bits=digest_bits)
                            hobj.update(b("BLAKE2s supports several digest sizes"))

                            signer = PKCS.new(key)
                            signature = signer.sign(hobj)
                            signer.verify(hobj, signature)


                        h = SHA1.new()
                        h.update(b('blah blah blah'))

                        # Verify that sign() uses a different salt length
                        for sLen in (0,3,21):
                            rng = RNG()
                            signer = PKCS.new(key, saltLen=sLen, randfunc=rng)
                            s = signer.sign(h)
                            self.assertEqual(rng.asked, sLen)
                            signer.verify(h, s)

                        # Verify that sign() uses the custom MGF
                        mgfcalls = 0
                        signer = PKCS.new(key, newMGF)
                        s = signer.sign(h)
                        self.assertEqual(mgfcalls, 1)
                        signer.verify(h, s)

                        # Verify that sign() does not call the RNG
                        # when salt length is 0, even when a new MGF is provided
                        key.asked = 0
                        mgfcalls = 0
                        signer = PKCS.new(key, newMGF, 0)
                        s = signer.sign(h)
                        self.assertEqual(key.asked,0)
                        self.assertEqual(mgfcalls, 1)
                        signer.verify(h, s)
Exemple #15
0
    def testSignVerify(self):
        h = SHA1.new()
        h.update(b('blah blah blah'))

        class RNG(object):
            def __init__(self):
                self.asked = 0

            def __call__(self, N):
                self.asked += N
                return Random.get_random_bytes(N)

        key = RSA.generate(1024)

        # Helper function to monitor what's request from MGF
        global mgfcalls

        def newMGF(seed, maskLen):
            global mgfcalls
            mgfcalls += 1
            return bchr(0x00) * maskLen

        # Verify that PSS is friendly to all hashes
        for hashmod in (MD2, MD5, SHA1, SHA224, SHA256, SHA384, RIPEMD160):
            h = hashmod.new()
            h.update(b('blah blah blah'))

            # Verify that sign() asks for as many random bytes
            # as the hash output size
            rng = RNG()
            signer = PKCS.new(key, randfunc=rng)
            s = signer.sign(h)
            signer.verify(h, s)
            self.assertEqual(rng.asked, h.digest_size)

        # Blake2b has variable digest size
        for digest_bits in (160, 256, 384):  # 512 is too long
            hobj = BLAKE2b.new(digest_bits=digest_bits)
            hobj.update(b("BLAKE2b supports several digest sizes"))

            signer = PKCS.new(key)
            signature = signer.sign(hobj)
            signer.verify(hobj, signature)

        # Blake2s too
        for digest_bits in (128, 160, 224, 256):
            hobj = BLAKE2s.new(digest_bits=digest_bits)
            hobj.update(b("BLAKE2s supports several digest sizes"))

            signer = PKCS.new(key)
            signature = signer.sign(hobj)
            signer.verify(hobj, signature)

        h = SHA1.new()
        h.update(b('blah blah blah'))

        # Verify that sign() uses a different salt length
        for sLen in (0, 3, 21):
            rng = RNG()
            signer = PKCS.new(key, saltLen=sLen, randfunc=rng)
            s = signer.sign(h)
            self.assertEqual(rng.asked, sLen)
            signer.verify(h, s)

        # Verify that sign() uses the custom MGF
        mgfcalls = 0
        signer = PKCS.new(key, newMGF)
        s = signer.sign(h)
        self.assertEqual(mgfcalls, 1)
        signer.verify(h, s)

        # Verify that sign() does not call the RNG
        # when salt length is 0, even when a new MGF is provided
        key.asked = 0
        mgfcalls = 0
        signer = PKCS.new(key, newMGF, 0)
        s = signer.sign(h)
        self.assertEqual(key.asked, 0)
        self.assertEqual(mgfcalls, 1)
        signer.verify(h, s)
Exemple #16
0
 def new(data=None):
     return BLAKE2s.new(digest_bits=256, data=data)
Exemple #17
0
def _generate_cipher(secret: str):
    # Generate initial vector from hash of ENCRYPT_SECRET_KEY.
    iv = BLAKE2s.new(digest_bits=128).update(secret).digest()

    return AES.new(secret, AES.MODE_CBC, iv)