def check_medv(input_dir, wav_files):
    results = []

    for i, f in enumerate(wav_files):
        print(f)
        samples, samplerate = sf.read(input_dir + '/' + f, dtype=np.int16)
        samples = samples[:, 0]

        # Choose seed pseudo-randomly
        seed = int((max_seed - min_seed) * np.random.random_sample() +
                   min_seed)

        # Generate random mark
        wmk = []
        for c in range(wmk_len):
            wmk.append(round(np.random.sample()))

        # Construct watermarking system
        wm_sys = XsWMSystem(la=la,
                            num_bins=num_bins,
                            threshold=bin_threshold,
                            step=step)

        # Embed mark
        marked_samples, bp = wm_sys.embed_watermark(samples, wmk, key=seed)

        # Encrypt the signal
        ciphered_samples, padding_length = catmap_encryption.encrypt(
            marked_samples, a, b, n)

        # Decrypt signal
        decrypted_samples = catmap_encryption.decrypt(ciphered_samples,
                                                      padding_length, a, b, n)

        # Verify the mark
        w_2 = wm_sys.extract_watermark(decrypted_samples,
                                       key=bp,
                                       delta=0.0,
                                       syn=wmk[:4])
        print(wmk)
        print(w_2)
        print('BER: ', watermarking_utils.calc_bit_error_rate(wmk, w_2))
        results.append(watermarking_utils.calc_bit_error_rate(wmk, w_2))

    return results
Exemplo n.º 2
0
    def emb(self, o, m, embedding_key, **kwargs):
        """Implements the emb()-method of the proposed protocol.
        Embeds a watermark m into an media-object - in this case an audio
        file -  via the combined method (Xiang+Schmitz) and stores all for
        the verification process necessary information in the Prover-object,
        on which it was called. The seed serves as embedding key.

        :param o: the media object to mark - a list of samples
        :param m: the watermark - a list of bits
        :param embedding_key: a scalar, which serves as seed and therefore
        as the
        embedding key
        :param kwargs: the initialization parameters for the watermarking
        system. See XsWMSystem.__init__(..)
        :return:
        """
        if len(m) != self._graph_size:
            raise ValueError('Length of WMK has to match length of public key')

        # store params
        self._mark = m
        self._obj = o
        self._seed = embedding_key

        # Initialize watermarking system
        wm_sys = XsWMSystem(**kwargs)

        # Mark the cover work
        self._obj_marked, self._detection_key = wm_sys.embed_watermark(
            self._obj, self._mark, key=self._seed)
        self._wm_params = wm_sys.get_params()

        # create scrambled watermark and scrambled watermark key
        self._wm_key_scrambled = utils.permute_list(self._detection_key,
                                                    self._tau)
        self._mark_scrambled = utils.permute_list(self._mark, self._tau)
        self._is_init = True
    files = files[1:]  # exclude .ds_store on mac

for i, f in enumerate(files):
    samples, samplerate = sf.read(input_dir + '/' + f, dtype=np.int16)
    samples = samples[:, 0]

    # Choose seed pseudo-randomly
    seed = int((max_seed - min_seed) * np.random.random_sample() + min_seed)

    # Generate random mark
    wmk = []
    for c in range(wmk_len):
        wmk.append(round(np.random.sample()))

    # Construct watermarking system
    wm_sys = XsWMSystem(la=la, num_bins=num_bins, threshold=bin_threshold,
                        step=step)

    # Embed mark
    marked_samples, bp = wm_sys.embed_watermark(samples, wmk, key=seed)
    # Get all parameters
    iv = wm_sys.get_params()

    # Store results
    sf.write(output_dir + '/' + f[:-4] + '_' + str(
        len(wmk)) + '_bits' + '.wav', marked_samples, samplerate)
    watermarking_utils.dump_params(output_dir,
                                   f[:-4] + '_' + str(len(wmk)) + '_bits',
                                   key=bp, iv=iv, mark=wmk)


Exemplo n.º 4
0
from core.audio_cwe.xs_wm_scheme import XsWMSystem
from core.audio_cwe import watermarking_utils
from experimental_testing.robustness_eval import tsm_utils

# Define file names
input_file = '../../res/testing/original_test_files/SQAM/58.wav'
output_dir = '../../res/demo'
filename = input_file.split('/')[-1].split('.')[0]
suffix = '_24_bits_xs'

# Load sound file
samples, fs = sf.read(input_file, dtype=np.int16)

# Construct the watermarking system
wm_sys_xs = XsWMSystem(num_bins=224, la=2.5, threshold=50, delta=0.05, step=5)

# Form the watermark w, each list element is embedded in one channel
w = watermarking_utils.construct_watermark(['HdM', 'Stg'])

# Mark the samples
marked_samples, key = wm_sys_xs.embed_watermark(samples, w, key=[1234, 5678])

# Write result to disk
out_file = path.join(output_dir, filename + suffix + '.wav')
sf.write(out_file, marked_samples, fs)

# Write the IV to disk for later detection
params = wm_sys_xs.get_params()
watermarking_utils.dump_params(output_dir,
                               filename + suffix,
Exemplo n.º 5
0
results = np.ones(
    (len(wav_files),
     len([
         f for f in listdir(attacked_filedirs[0])
         if isfile(join(attacked_filedirs[0], f)) and f.endswith('.wav')
     ])),
    dtype=np.float)
for i, f in enumerate(wav_files):
    print(f)
    print(iv_files[i])
    print(keys[i])
    print(marks[i])

    # Init WM system
    wm_sys = XsWMSystem.from_file(join(input_dir, iv_files[i]))

    # Read key
    bin_pairs = watermarking_utils.read_keyfile(input_dir + "/" + keys[i])
    # Read embedded WMK
    wmk = np.loadtxt(input_dir + "/" + marks[i], dtype=np.int)

    attacked_files = [
        f for f in listdir(attacked_filedirs[i])
        if isfile(join(attacked_filedirs[i], f)) and f.endswith('.wav')
    ]
    attacked_files = sorted(attacked_files,
                            key=lambda x: float(x[:-4].split('_')[-1]))

    for j, af in enumerate(attacked_files):
        print(af)
Exemplo n.º 6
0
n = 5

samples, padding_length = catmap_encryption.encrypt(samples[:, 0], a, b, n)
output_file = path.join(out_dir,
                        input_file[0:len(input_file) - 4] + '_encrypted.wav')
sf.write(output_file, samples, samplerate)

# Reads encrypted audio file and marks it
samples, samplerate = sf.read(output_file, dtype=np.int16)

# Form mark and syn code
w = watermarking_utils.construct_watermark('CWE')
syn = w[:4]

# Construct watermarking system
wm_system = XsWMSystem()  # init with default values

# Mark the samples
marked_samples, bin_pairs = wm_system.embed_watermark(samples, w, key=1234)
output_file = output_file[0:len(input_file) - 4] + '_marked.wav'
sf.write(output_file, marked_samples, samplerate)

# Read marked and encrypted audio file and decrypt it
samples, samplerate = sf.read(output_file, dtype=np.int16)
samples = catmap_encryption.decrypt(samples, padding_length, a, b, n)
output_file = path.join(
    out_dir, input_file[0:len(input_file) - 4] + '_decrypted' + '_marked.wav')
sf.write(output_file, samples, samplerate)

# Read decrypted and marked audio file and verify the mark
samples, samplerate = sf.read(output_file, dtype=np.int16)
Exemplo n.º 7
0
import os.path
import platform

import soundfile as sf
import numpy as np

from core.audio_cwe import watermarking_utils
from core.audio_cwe.xs_wm_scheme import XsWMSystem

# retrieve marked test files
input_dir = '../../../res/testing/transparency_eval/56_bits_step_5_t_50/odg' \
            '/wave/test'
output_dir = '../../../res/testing/transparency_eval/56_bits_step_5_t_50/odg' \
             '/wave/test'

# retrieve files
files = [
    f for f in listdir(input_dir)
    if isfile(join(input_dir, f)) and f.endswith('_iv')
]
for i, f in enumerate(files):

    iv = np.loadtxt(input_dir + "/" + files[i], dtype=np.float64)
    wm_sys = XsWMSystem(la=iv[1],
                        num_bins=iv[0],
                        threshold=iv[2],
                        orig_mean=iv[-1],
                        step=5,
                        delta=0.05)
    new_iv = wm_sys.get_params()
    watermarking_utils.dump_params(output_dir, f[:-3], iv=new_iv)
Exemplo n.º 8
0
    def start_verification(self):
        """Performs the actual verification by calling ver() of the prover
        iteratively. In each round the OwnershipTicket, which contains the
        encrypted permutations \rho & \simga and the hash of g_i is received.
        A coin flip decides which commitment should be opened. In case(i)
        the presence of the scrambled watermark is verified and in case(ii)
        the prover's knowledge of \tau is validated. If the verifiers is
        cheaten once, he quits the protocol run.

        :return: success: a boolean which specifies, whether the
        verification process was successfull.
        """
        print('------------------------------------------------------')
        print('Verification process starts')
        print('------------------------------------------------------')

        # Receive public data
        o, g, scrambled_g, scrambled_mark, scrambled_wmk_key, wm_params = \
            self.prover.setup_verification()

        # WM parameters
        print('Watermarking parameters:\n', wm_params)

        has_cheated = False
        i = self._rounds

        while i > 0 and not has_cheated:
            # Get OwnershipTicket
            print('------------------------------------------------------')
            print('Iteration #', self._rounds - i)
            print('------------------------------------------------------')
            nonce = self._prng.randint(np.iinfo('i').max)
            ot = self.prover.ver(nonce)

            if self._flip_coin() is 1:
                print('------------------------------------------------------')
                print("Case (i)")
                print('------------------------------------------------------')
                c1_params = self.prover.reveal(Prover.CHOICES[0])
                sigma_permutation = self._aes_decrypt_array(ot.c1, *c1_params)

                # Check random number at the end of commitment
                if nonce != sigma_permutation[-1]:
                    raise ProtocolError('Commitment seems to be manipulated!')

                # Strip it off
                sigma_permutation = sigma_permutation[:-1]

                inv_sigma_permutation = utils.invert(sigma_permutation)

                # Calculate o_i and g_i
                g_i = utils.permute_graph(scrambled_g, inv_sigma_permutation)

                # Check hash bits
                hash_g_i = SHA512.new(g_i.toarray().tostring()).hexdigest()

                if hash_g_i != ot.hash_g_i:
                    has_cheated = True
                    print("Hash of G_i doesn't match")
                else:
                    print("Hash of G_i matches")

                # Calculate mark_i and wmk_key__i
                mark_i = utils.permute_list(scrambled_mark,
                                            inv_sigma_permutation)
                wmk_key_i = utils.permute_list(scrambled_wmk_key,
                                               inv_sigma_permutation)

                # Extract wmk
                wm_sys = XsWMSystem(**wm_params)
                extracted_msg = wm_sys.extract_watermark(
                    o, syn=mark_i[0:len(mark_i) // 3], key=wmk_key_i)

                print("Extracted mark:\n", np.array(extracted_msg))
                print("Mark_i:\n", mark_i)

                if np.array_equal(extracted_msg, mark_i):
                    print("Extracted mark matches")
                else:
                    has_cheated = True
                    print("Marks are not equal")

            else:
                print('------------------------------------------------------')
                print("Case (ii)")
                print('------------------------------------------------------')
                c2_params = self.prover.reveal(Prover.CHOICES[1])
                rho_permutation = self._aes_decrypt_array(ot.c2, *c2_params)
                # Check random number at the end of decrypted commitment
                if nonce != rho_permutation[-1]:
                    raise ProtocolError('Commitment seems to be manipulated!')
                rho_permutation = rho_permutation[:-1]

                # Calculate g_i
                g_i = utils.permute_graph(g, rho_permutation)

                # Check hash bits
                hash_g_i = SHA512.new(g_i.toarray().tostring()).hexdigest()

                if hash_g_i != ot.hash_g_i:
                    has_cheated = True
                    print("Hash of G_i doesn't match")
                else:
                    print("Hash of G_i matches")

            i -= 1

        self.success = not has_cheated

        return self.success