Exemple #1
0
    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 : 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 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 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")
    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")
Exemple #4
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")
Exemple #5
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")
    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]

        secret = get_random_bytes(16)

        mac1 = BLAKE2s.new(digest_bits=160, key=secret,
                           data=self._compute_mac())
        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* 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")
    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 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 = b'\x00' * 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 #9
0
def bcrypt_check(password, bcrypt_hash):
    """Verify if the provided password matches the given bcrypt hash.

    Args:
      password (byte string or string):
        The secret password or pass phrase to test.
        It must be at most 72 bytes long.
        It must not contain the zero byte.
        Unicode strings will be encoded as UTF-8.
      bcrypt_hash (byte string, bytearray):
        The reference bcrypt hash the password needs to be checked against.

    Raises:
        ValueError: if the password does not match

    Note:
        If you want to hash passwords with no restrictions on their length, it
        is common practice to apply a cryptographic hash and then BASE64-encode
        the result. For instance::

            from base64 import b64encode
            from Crypto.Hash import SHA256
            from Crypto.Protocol.KDF import bcrypt

            password_to_test = b"test"
            try:
                b64pwd = b64encode(SHA256.new(password).digest())
                bcrypt_check(b64pwd, bcrypt_hash)
            except ValueError:
                print("Incorrect password")
    """

    bcrypt_hash = tobytes(bcrypt_hash)

    if len(bcrypt_hash) != 60:
        raise ValueError("Incorrect length of the bcrypt hash: %d bytes instead of 60" % len(bcrypt_hash))

    if bcrypt_hash[:4] != b'$2a$':
        raise ValueError("Unsupported prefix")

    p = re.compile(b'\$2a\$([0-9][0-9])\$([A-Za-z0-9./]{22,22})([A-Za-z0-9./]{31,31})')
    r = p.match(bcrypt_hash)
    if not r:
        raise ValueError("Incorrect bcrypt hash format")

    cost = int(r.group(1))
    if not (4 <= cost <= 31):
        raise ValueError("Incorrect cost")

    salt = _bcrypt_decode(r.group(2))

    bcrypt_hash2  = bcrypt(password, cost, salt)

    secret = get_random_bytes(16)

    mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=bcrypt_hash).digest()
    mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=bcrypt_hash2).digest()
    if mac1 != mac2:
        raise ValueError("Incorrect bcrypt hash")
Exemple #10
0
    def verify(self, mac_tag):

        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 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 #12
0
    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 #13
0
def bcrypt_check(password, bcrypt_hash):
    """Verify if the provided password matches the given bcrypt hash.

    Args:
      password (byte string or string):
        The secret password or pass phrase to test.
        It must be at most 72 bytes long.
        It must not contain the zero byte.
        Unicode strings will be encoded as UTF-8.
      bcrypt_hash (byte string, bytearray):
        The reference bcrypt hash the password needs to be checked against.

    Raises:
        ValueError: if the password does not match
    """

    bcrypt_hash = tobytes(bcrypt_hash)

    if len(bcrypt_hash) != 60:
        raise ValueError(
            "Incorrect length of the bcrypt hash: %d bytes instead of 60" %
            len(bcrypt_hash))

    if bcrypt_hash[:4] != b'$2a$':
        raise ValueError("Unsupported prefix")

    p = re.compile(
        br'\$2a\$([0-9][0-9])\$([A-Za-z0-9./]{22,22})([A-Za-z0-9./]{31,31})')
    r = p.match(bcrypt_hash)
    if not r:
        raise ValueError("Incorrect bcrypt hash format")

    cost = int(r.group(1))
    if not (4 <= cost <= 31):
        raise ValueError("Incorrect cost")

    salt = _bcrypt_decode(r.group(2))

    bcrypt_hash2 = bcrypt(password, cost, salt)

    secret = get_random_bytes(16)

    mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=bcrypt_hash).digest()
    mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=bcrypt_hash2).digest()
    if mac1 != mac2:
        raise ValueError("Incorrect bcrypt hash")
Exemple #14
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")
    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 #16
0
 def setPassCode(self):
     self.passCode = self.passCode.get().strip()
     self.key = BLAKE2s.new(digest_bits=64, )
     self.key.update(bytes(self.passCode, encoding='utf-8'))
     self.eKey = self.key.digest()
     self.cipher = DES.new(self.eKey, DES.MODE_OFB)
     self.mode = DES.MODE_OFB
     # place holder for key, take passcode parameter and generate key here or in main.
     self.encrypted = 1
Exemple #17
0
def _generate_cipher():
    """
    암호화 객체를 생성.
    """
    secret = current_app.config['ENCRYPT_SECRET_KEY']
    # 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)
 def get_blake2s_as_mac(self, secret="secret"):
     # TODO: udsotępnić userowi dopisanie sekretnego klucza
     """
     Ewentulanie BLAKE2s może być użyty jak kryptograficzny MAC jeśli się zainicjalizuje go dodatkową  sekretną wartością
     :return:
     """
     mac = BLAKE2s.new(digest_bits=128, key=str.encode(secret))
     mac.update(self.value)
     return mac.digest(), mac.hexdigest()
Exemple #19
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 get_blake2s_256_bits(self):
     """
     Weilkość digest_bits od 8 do 256
     The algorithm uses 32 bit words, and it therefore works best on 32-bit platforms. The digest size ranges from 8 to 256 bits:
     """
     hash_obj = BLAKE2s.new(digest_bits=256)
     hash_obj.update(self.value)
     return {
         "digest": hash_obj.digest(),
         "hexdigets": hash_obj.hexdigest()
     }
    def runTest(self):

        key = RSA.generate(1280)
        signer = pss.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 #23
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
Exemple #24
0
 def __init__(self):
     self.hasher = BLAKE2s.new(digest_bits=256)
Exemple #25
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)
############################

# 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 #27
0
 def new(data=None):
     return BLAKE2s.new(digest_bits=256, data=data)
Exemple #28
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 #29
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)