コード例 #1
0
    def verify(self, msgAndDigest, associatedData=b''):
        """
        Verifies whether the MAC digest from input ciphertext and digest matches the computed one over ciphertext and associated data.

        Parameters
        ----------
        msgAndDigest : dict
            Dictionary composed of the MAC algorithm, the MACed message (or ciphertext), and the digest computed by MACing HMAC_algorithm + associatedData + msg.
            It is the format generated by the mac() function within this class.
        associatedData : str or byte str, optional
            Associated data that will be MACed together with the ciphertext and algorithm; the associated data will not be encrypted.

        Returns
        -------
        bool
            True if the digests match, False otherwise.

        Raises
        ------
        ValueError
            If the HMAC algorithm is not supported.
        """
        if msgAndDigest['alg'] != self._algorithm:
            raise ValueError(
                "Currently only HMAC_SHA2 is supported as an algorithm")
        expected = bytes(
            self.mac(msgAndDigest['msg'],
                     associatedData=associatedData)['digest'], 'utf-8')
        received = bytes(msgAndDigest['digest'], 'utf-8')
        # we compare the hash instead of the direct value to avoid a timing attack
        return sha2(expected).digest() == sha2(received).digest()
コード例 #2
0
    def read_user_id(self, u_id):
        if u_id is None or u_id == '':
            return ''

        algorithm = sha2()
        algorithm.update(u_id.encode())
        return algorithm.hexdigest().upper()
コード例 #3
0
    def do_test_sha2_inserts(self, m, k, num_key):
        """ Test CountingBloom2 for specific parameters. """
        keys = []
        # set up distinct keys, each the hash of a unique value
        for i in range(num_key):
            sha = sha2()
            stuff = RNG.some_bytes(32)  # 32 quasi-random bytes
            stuff[0] = i  # guarantee uniqueness
            sha.update(stuff)
            keys.append(stuff)

        fltr = CountingBloom(m, k, key_bytes=32)
        # DEBUG
        # print("test_sha2_inserts: len of new filter is %d" % len(fltr))
        # END
        for i in range(num_key):
            # DEBUG
            if i != len(fltr):
                print("  before %d-th insert length of filter is %d" %
                      (i, len(fltr)))
            # END
            self.assertEqual(i, len(fltr))
            keysel = KeySelector(keys[i], fltr)
            self.assertFalse(fltr.is_member(keysel),
                             "key %d not yet in set, but found!" % i)
            fltr.insert(keysel)  # add key to fltr

        for i in range(num_key):
            keysel = KeySelector(keys[i], fltr)
            self.assertTrue(fltr.is_member(keysel),
                            "key %d has been added but not found in set" % i)
コード例 #4
0
def test_register_device():
    url = base_url + register_endpoint
    
    alg = sha2()
    alg.update(TEST_EMAIL.encode())
    headers = {'User-Id': alg.hexdigest().upper(),
               'Install-Id': TEST_INSTALL_ID}
    response = requests.post(url, data={'push_id': TEST_PUSH_ID}, headers=headers)
    return response.text
コード例 #5
0
def test_upload_sensor_readings():
    url = base_url + upload_sensor_readings_endpoint
    
    alg = sha2()
    alg.update(TEST_EMAIL.encode())
    headers = {'User-Id': alg.hexdigest().upper()}
    sensor_readings = generate_sensor_readings(0)
    
    response = requests.post(url, json=sensor_readings, headers=headers)
    return response.text
コード例 #6
0
def sha2_parse(filename):
    """Open file, compute sha2 hash and return as ascii hex string"""
    try:
        f = open(filename, 'rb')
        content = f.read()
        sha2hash = hashlib.sha2(content).hexdigest()
        return sha2hash
    except ValueError:
        return 'No hash'
    finally:
        f.close()
コード例 #7
0
def test_get_medicine_data():
    url = base_url + get_med_data_endpoint
    
    alg = sha2()
    alg.update(TEST_EMAIL.encode())
    headers = {'User-Id': alg.hexdigest().upper(), 'Install-Id': TEST_INSTALL_ID}
    
    response = requests.get(url, headers=headers)
    response = response.json()
    
    MED_IDS.append(response['medicines'][0]['id'])
    MED_IDS.append(response['medicines'][0]['id'])
    MED_IDS.append(response['medicines'][1]['id'])
    MED_IDS.append(response['medicines'][1]['id'])
    MED_IDS.append(response['medicines'][1]['id'])
    return response
コード例 #8
0
    def decrypt(self, cipherText, associatedData=''):
        """
        Decrypts a ciphertext in AEAD mode (Authenticated Encryption with Associated Data) using the superclass symmetric encryption parameters.
        The MAC is computed with both the ciphertext and associated data (and other cryptosystem parameters), but the associated data is not encrypted, nor
        available within the ciphertext structure.

        Parameters
        ----------
        ciphertext : str or byte str
            The message to be decrypted.
        associatedData : str or byte str, optional
            Associated data that will be MACed together with the ciphertext and algorithm. This associated text must be in plaintext.

        Returns
        -------
        byte str
            The decrypted plaintext, if the ciphertext was successfuly authenticated. Raise exception otherwise.

        Raises
        ------
        ValueError
            If the MAC is invalid.

        Notes
        -----
        The IV is included in the computation of the MAC. In fact, all cipher parameters are included: the encryption function returns a JSON object from
        a dictionary composed of the cipher parameters (e.g., algorithm, mode, IV), and the ciphertext. The MAC function uses the whole JSON object/string
        to compute the MAC, prepended with the HMAC algorithm + associatedData.

        The MAC key is computed as sha2(b'Poor Mans Key Extractor" + key).
        """
        # warning only valid in the random oracle
        mac_key = sha2(b'Poor Mans Key Extractor' + self._key).digest()
        mac = MessageAuthenticator(mac_key)
        if not mac.verify(cipherText, associatedData=associatedData):
            raise ValueError(
                "Invalid mac. Your data was tampered with or your key is wrong"
            )
        else:
            return super(AuthenticatedCryptoAbstraction,
                         self).decrypt(cipherText['msg'])
コード例 #9
0
    def encrypt(self, msg, associatedData=''):
        """
        Encrypts a message in AEAD mode (Authenticated Encryption with Associated Data) using the superclass symmetric encryption parameters.
        The MAC is computed with both the ciphertext and associated data (and other cryptosystem parameters), but the associated data is not encrypted, nor
        saved within the ciphertext structure.

        Parameters
        ----------
        msg : str or byte str
            The message to be encrypted.
        associatedData : str or byte str, optional
            Associated data that will be MACed together with the ciphertext and algorithm; the associated data will not be encrypted.

        Returns
        -------
        dict
            Dictionary structure containing:
                msg: {'ALG': symmetric cryptosystem.
                      'MODE': symmetric encryption mode.
                      'IV': the IV for the encryption algorithm.
                      'CipherText': the padded ciphertext (padding according to PKCS 7).
                     }
                "alg": The HMAC algorithm.
                "digest": The MAC computed as MAC = HMAC(key, alg + associatedData + msg)

        Notes
        -----
        The IV is included in the computation of the MAC. In fact, all cipher parameters are included: the encryption function returns a JSON object from
        a dictionary composed of the cipher parameters (e.g., algorithm, mode, IV), and the ciphertext. The MAC function uses the whole JSON object/string
        to compute the MAC, prepended with the HMAC algorithm + associatedData.

        The MAC key is computed as sha2(b'Poor Mans Key Extractor" + key).
        """
        # warning only valid in the random oracle
        mac_key = sha2(b'Poor Mans Key Extractor' + self._key).digest()
        mac = MessageAuthenticator(mac_key)
        enc = super(AuthenticatedCryptoAbstraction, self).encrypt(msg)
        return mac.mac(enc, associatedData=associatedData)
コード例 #10
0
ファイル: test_bloom_sha.py プロジェクト: jddixon/xlcrypto_py
    def do_test_sha2_inserts(self, m, k, num_key):
        """ Test BloomSHA2 for specific parameters. """
        keys = []
        # set up distinct keys, each the hash of a unique value
        for i in range(num_key):
            sha = sha2()
            stuff = RNG.some_bytes(32)  # 32 quasi-random bytes
            stuff[0] = i  # guarantee uniqueness
            sha.update(stuff)
            keys.append(stuff)

        fltr = BloomSHA(m, k, key_bytes=32)
        for i in range(num_key):
            self.assertEqual(i, len(fltr))
            keysel = KeySelector(keys[i], fltr)
            self.assertFalse(fltr.is_member(keysel),
                             "key %d not yet in set, but found!" % i)
            fltr.insert(keysel)  # add key to fltr

        for i in range(num_key):
            keysel = KeySelector(keys[i], fltr)
            self.assertTrue(fltr.is_member(keysel),
                            "key %d has been added but not found in set" % i)