Blame view

msteg/steganography/F5.py 14.4 KB
8cfc1a23   Chunk   F5 half-finished.
1
2
"""
<p>This module implements the rather sophisticated F5 algorithm which was
c9fdeb00   Chunk   LSB and F4 added.
3
invented by Andreas Westfeld.</p>
26e2fe9f   Chunk   MPB steganalysis ...
4
5

Unlike its vastly inferior predecessors, namely F3 and F4, it features matrix
c9fdeb00   Chunk   LSB and F4 added.
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
encoding which makes it possible to embed a chunk of k bits within 2^k - 1
bits of the cover data and only change one bit (at most). A bit change is
done by subtracting the absolute value of the corresponding DCT coefficient.
When the embedding process begins, the parameter k is computed based on
the capacity of the cover image and the prospective embedding ratio.
With small amount of hidden data k becomes large which leads to a greater
embedding efficiency (embedded information per bit change).<br />

A permutation (initialized by a user-supplied seed) of the DCT coefficients
helps to scatter each chunk across the entire image.
F5 can be seen as meta-algorithm as it uses a coding scheme to change
as little data as possible and then applies a simpler algorithm (such as F3)
to actually embed data. That is why this module allows the user to specify
which embedding function (one of JSteg, F3, F4) should be used.
"""

import time
import math
import numpy as np
from stegotool.plugins.steganography.F4.F4 import F4
c9fdeb00   Chunk   LSB and F4 added.
26
27
from stegotool.util.JPEGSteg import JPEGSteg
from stegotool.util.plugins import describe_annotate_convert
033d3b0d   Chunk   staged.
28
from stegotool.util.plugins import ident, ImagePath, FilePath, NewFilePath
b69b6985   Chunk   py module refract...
29

033d3b0d   Chunk   staged.
30

c6c61f81   Chunk   staged.
31
class F5(JPEGSteg):
033d3b0d   Chunk   staged.
32
    """ This module has two methods: <i>embed_raw_data</i> to embed data
c9fdeb00   Chunk   LSB and F4 added.
33
34
    with the F5 algorithm and <i>extract_raw_data</i> to extract data
    which was embedded previously. """
033d3b0d   Chunk   staged.
35

c9fdeb00   Chunk   LSB and F4 added.
36
37
38
39
    def __init__(self, ui, core):
        """
        Constructor of the F5 class.
        """
8cfc1a23   Chunk   F5 half-finished.
40
        JPEGSteg.__init__(self, ui, core)
c9fdeb00   Chunk   LSB and F4 added.
41
42
43
        self._embed_hook = self._embed_k
        self._extract_hook = self._extract_k
        self._embed_fun = None
033d3b0d   Chunk   staged.
44
        self.dct_p = None
c9fdeb00   Chunk   LSB and F4 added.
45
        self.seed = None
c9fdeb00   Chunk   LSB and F4 added.
46
        self.default_embedding = True
8cfc1a23   Chunk   F5 half-finished.
47
        self.steg_ind = -1
c9fdeb00   Chunk   LSB and F4 added.
48
        self.excess_bits = None
8cfc1a23   Chunk   F5 half-finished.
49
50
51
52
53
54
55
        # needed because k is embedded separately
        self.cov_ind = -1
        self.k_coeff = -1

    @describe_annotate_convert((None, None, ident),
                               ("cover image", ImagePath, str),
                               ("hidden data", FilePath, str),
c6c61f81   Chunk   staged.
56
                               ("stego image", NewFilePath, str),
8cfc1a23   Chunk   F5 half-finished.
57
58
59
60
61
62
63
64
65
66
                               ("seed", int, int),
                               ("embedding behavior",
                                   ['Default', 'F3', 'JSteg'], str))
    def embed_raw_data(self, src_cover, src_hidden, tgt_stego, seed,
                       embed_fun):
        """<p>This method embeds arbitrary data into a cover image.
        The cover image must be a JPEG.</p>

        <p>Parameters:
        <ol>
c9fdeb00   Chunk   LSB and F4 added.
67
68
69
70
        <li><pre>src_cover</pre>
        A valid pathname to an image file which serves as cover image
        (the image which the secret image is embedded into).</li>

8cfc1a23   Chunk   F5 half-finished.
71
        <li><pre>src_hidden</pre>
c9fdeb00   Chunk   LSB and F4 added.
72
73
        A valid pathname to an arbitrary file that is supposed to be
        embedded into the cover image.</li>
8cfc1a23   Chunk   F5 half-finished.
74

c9fdeb00   Chunk   LSB and F4 added.
75
76
77
        <li><pre>tgt_stego</pre>
        Target pathname of the resulting stego image. You should save to
        a PNG or another lossless format, because many LSBs don't survive
8cfc1a23   Chunk   F5 half-finished.
78
        lossy compression.</li>
c9fdeb00   Chunk   LSB and F4 added.
79
80

        <li><pre>seed</pre>
8cfc1a23   Chunk   F5 half-finished.
81
        A seed for the random number generator that is responsible scattering
c9fdeb00   Chunk   LSB and F4 added.
82
83
84
        the secret data within the cover image.</li>

        <li><pre>param embed_fun</pre>
8cfc1a23   Chunk   F5 half-finished.
85
86
87
88
        Specifies which embedding function should be used. Must be one of
        'Default', 'F3', 'Jsteg'. If 'Default' is selected, the algorithm uses
        the same behavior as Westfeld's implementation, i.e. decrementing
        absolute values for n > 1 (F3) and using F4 in the special case n = 1.
c9fdeb00   Chunk   LSB and F4 added.
89
        Selecting F3 or JSteg results in using that scheme for all n.</li>
8cfc1a23   Chunk   F5 half-finished.
90
        </ol>
c9fdeb00   Chunk   LSB and F4 added.
91
        </p>
8cfc1a23   Chunk   F5 half-finished.
92
93
94
        """
        self.t0 = time.time()
        self.seed = seed
c9fdeb00   Chunk   LSB and F4 added.
95
        if embed_fun == 'F3':
8cfc1a23   Chunk   F5 half-finished.
96
97
            self._embed_fun = self._f3_embed
            self.default_embedding = False
c9fdeb00   Chunk   LSB and F4 added.
98
        elif embed_fun == 'JSteg':
873557f9   Chunk   staged.
99
100
            self._embed_fun = self._jsteg_embed
            self.default_embedding = False
c9fdeb00   Chunk   LSB and F4 added.
101
        elif embed_fun == 'Default':
873557f9   Chunk   staged.
102
103
104
105
106
107
108
            self._embed_fun = self._f3_embed
            self.default_embedding = True

        self.cov_ind = -1
        JPEGSteg._post_embed_actions(self, src_cover, src_hidden, tgt_stego)

    @describe_annotate_convert((None, None, ident),
c9fdeb00   Chunk   LSB and F4 added.
109
                               ("stego image", ImagePath, str),
8cfc1a23   Chunk   F5 half-finished.
110
111
112
113
114
115
116
117
                               ("hidden data", NewFilePath, str),
                               ("seed", int, int),
                               ("embedding behavior", ['Default', 'F3/JSteg'],
                                str))
    def extract_raw_data(self, src_steg, tgt_hidden, seed, embed_fun):
        """<p>This method extracts secret data from a stego image. It is
        (obviously) the inverse operation of embed_raw_data.</p>

c9fdeb00   Chunk   LSB and F4 added.
118
        <p>Parameters:
8cfc1a23   Chunk   F5 half-finished.
119
120
121
122
123
124
        <ol>
        <li><pre>src_stego</pre>
        A valid pathname to an image file which serves as stego image.</li>

        <li><pre>tgt_hidden</pre>
        A pathname denoting where the extracted data should be saved to.</li>
c9fdeb00   Chunk   LSB and F4 added.
125

8cfc1a23   Chunk   F5 half-finished.
126
127
        <li><pre>param seed</pre>
        A seed for the random number generator that is responsible scattering
c9fdeb00   Chunk   LSB and F4 added.
128
129
        the secret data within the cover image.</li>

8cfc1a23   Chunk   F5 half-finished.
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
        <li><pre>param embed_fun</pre>
        Specifies which embedding function should be used. Must be one of
        'Default', 'F3', 'JSteg'. If 'Default' is selected, the algorithm uses
        the same behavior as  Westfeld's implementation, i.e. decrementing
        absolute values for n > 1 (F3) and using F4 in the special case n = 1.
        Selecting F3 or JSteg results in using that scheme for all n.</li>
        </ol></pre>
        """

        self.t0 = time.time()
        self.seed = seed
        self.steg_ind = -1
        if embed_fun == 'F3/JSteg':
            self.default_embedding = False
        elif embed_fun == 'Default':
            self.default_embedding = True

        # excess bits occur when the size of extracted data is not a multiple
        # of k. if excess bits are available, they are prepended to hidden data
        self.excess_bits = None

        JPEGSteg._post_extract_actions(self, src_steg, tgt_hidden)

    def _embed_k(self, cov_data, hid_data):
        np.random.seed(self.seed)
        self.dct_p = np.random.permutation(cov_data.size)
        self.k_coeff = self._find_max_k(cov_data, hid_data)
        self.ui.display_status('setting k = %d' % self.k_coeff)
        k_split = self.lookup_tab.split_byte(self.k_coeff, 1)[-4:]
        # embed k in F3-like style
        for m in k_split:
            success = False
            while not success:
                self.cov_ind += 1
                while cov_data[self.dct_p[self.cov_ind]] == 0 or \
                          self.dct_p[self.cov_ind] % 64 == 0:
                    self.cov_ind += 1
                if m != cov_data[self.dct_p[self.cov_ind]] & 1:
                    cov_data[self.dct_p[self.cov_ind]] -= \
                        math.copysign(1, cov_data[self.dct_p[self.cov_ind]])
                success = cov_data[self.dct_p[self.cov_ind]] != 0
c9fdeb00   Chunk   LSB and F4 added.
171

c9fdeb00   Chunk   LSB and F4 added.
172
173
174
175
176
177
178
179
180
181
182
183
184
    def _extract_k(self, steg_data):
        # initializing the MT is done only once in order to retain the state
        self.dct_p = np.random.seed(self.seed)
        self.dct_p = np.random.permutation(self.steg_data.size)
        k_split = np.zeros(4, np.uint8)
        for i in xrange(k_split.size):
            self.steg_ind += 1
            while self.steg_data[self.dct_p[self.steg_ind]] == 0 or\
                      self.dct_p[self.steg_ind] % 64 == 0:
                self.steg_ind += 1
            k_split[i] = self.steg_data[self.dct_p[self.steg_ind]] & 1
        self.k_coeff = self.lookup_tab.merge_words(tuple([0, 0, 0, 0] +
                                                         list(k_split)), 1)
033d3b0d   Chunk   staged.
185

c9fdeb00   Chunk   LSB and F4 added.
186
187
188
189
190
191
192
193
194
195
196
197
198
    def _find_max_k(self, cov_data, hid_data):
        cnt = 4  # information about k take up 4 bits
        # find number of DCT coefficients
        update_cnt = 10000
        for i, c in enumerate(cov_data):
            if update_cnt == 0:
                self._set_progress(
                        int(30 * (float(i) / float(cov_data.size))))
                update_cnt = 10000
            update_cnt -= 1
            # pessimistic, but accurate estimation of the capacity of the image
            ci = int(c)
            if (not (ci is 0)) and (not ((i % 64) is 0)) \
033d3b0d   Chunk   staged.
199
200
                    and (not (ci is 1)) and (not (ci is -1)):
                cnt += 1
c9fdeb00   Chunk   LSB and F4 added.
201
202
203
204
205
206
207
208
209
210
211
212
        hid_size = hid_data.size
        cov_size = cnt
        if cov_size < hid_size:
            raise Exception("Cannot fit %d bits in %d DCT coefficients. \
                    Cover image is too small." % (hid_size, cov_size))
        self.ui.display_status('DCT embedding ratio = %f' \
                % (float(hid_size) / float(cov_size)))
        k = 1
        while True:
            k += 1
            n = (1 << k) - 1
            num_chunks = cov_size / n
033d3b0d   Chunk   staged.
213
            num_emb_bits = num_chunks * k
c9fdeb00   Chunk   LSB and F4 added.
214
215
216
217
218
219
220
221
222
223
224
225
226
            if num_emb_bits < hid_size:
                return min(k - 1, 15)

    # low level embedding functions
    def _f3_embed(self, cov_data, ind):
        cov_data[ind] -= math.copysign(1, cov_data[ind])

    def _jsteg_embed(self, cov_data, ind):
        m = 1 ^ (cov_data[ind] & 1)
        cov_data[ind] = (cov_data[ind] & 0xffffe) | m

    def _raw_embed(self, cov_data, hid_data, status_begin=0):
        k = self.k_coeff
033d3b0d   Chunk   staged.
227
        n = (1 << k) - 1
c9fdeb00   Chunk   LSB and F4 added.
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
        if n == 1 and self.default_embedding:
            # in case k = n = 1, Westfeld's implementation uses F4 for
            # embedding. Therefore, if 'default' embedding has been selected
            # we will do the same
            f4 = F4(self.ui, self.core)
            f4.seed = self.seed
            f4.dct_p = self.dct_p
            f4.cov_ind = self.cov_ind
            cov_data = f4._raw_embed(cov_data, hid_data, 30)
            return cov_data

        cov_ind = self.cov_ind  # preventing RSI by writing 'self' less often
        hid_ind = 0
        remaining_bits = hid_data.size
        hid_size = float(hid_data.size)
8cfc1a23   Chunk   F5 half-finished.
243
        dct_p = self.dct_p
c9fdeb00   Chunk   LSB and F4 added.
244

8cfc1a23   Chunk   F5 half-finished.
245
        update_cnt = int(hid_size / (70.0 * k))
c9fdeb00   Chunk   LSB and F4 added.
246
247
        while remaining_bits > 0:
            if update_cnt == 0:
8cfc1a23   Chunk   F5 half-finished.
248
                self._set_progress(30 + int(((
c9fdeb00   Chunk   LSB and F4 added.
249
                    hid_size - remaining_bits) / hid_size) * 70))
8cfc1a23   Chunk   F5 half-finished.
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
                update_cnt = int(hid_size / (70.0 * k))
            update_cnt -= 1
            msg_chunk_size = min(remaining_bits, k)
            msg_chunk = np.zeros(k, np.int8)
            cov_chunk = np.zeros(n, np.int32)
            msg_chunk[0:msg_chunk_size] = hid_data[hid_ind:hid_ind +
                                                   msg_chunk_size]
            hid_ind += k

            # get n DCT coefficients
            for i in xrange(n):
                cov_ind += 1
                while cov_data[dct_p[cov_ind]] == 0 \
                        or dct_p[cov_ind] % 64 == 0:
                    cov_ind += 1
                cov_chunk[i] = dct_p[cov_ind]

            success = False
c9fdeb00   Chunk   LSB and F4 added.
268
269
            while not success:  # loop necessary because of shrinkage
                h = 0
8cfc1a23   Chunk   F5 half-finished.
270
                for i in xrange(n):
c9fdeb00   Chunk   LSB and F4 added.
271
272
273
274
275
                    h ^= ((cov_data[cov_chunk[i]] & 1) * (i + 1))
                scalar_x = 0
                for i in xrange(k):
                    scalar_x = (scalar_x << 1) + msg_chunk[i]
                s = scalar_x ^ h
8cfc1a23   Chunk   F5 half-finished.
276
277
                if s != 0:
                    self._embed_fun(cov_data, cov_chunk[s - 1])
c9fdeb00   Chunk   LSB and F4 added.
278
279
280
281
282
283
                else:
                    break

                if cov_data[cov_chunk[s - 1]] == 0:  # test for shrinkage
                    cov_chunk[s - 1:-1] = cov_chunk[s:]  # adjusting
                    cov_ind += 1
8cfc1a23   Chunk   F5 half-finished.
284
285
286
287
                    while cov_data[dct_p[cov_ind]] == 0 or\
                              dct_p[cov_ind] % 64 == 0:
                        cov_ind += 1
                    cov_chunk[n - 1] = dct_p[cov_ind]
c9fdeb00   Chunk   LSB and F4 added.
288
289
290
                else:
                    success = True

8cfc1a23   Chunk   F5 half-finished.
291
            remaining_bits -= k
c9fdeb00   Chunk   LSB and F4 added.
292

8cfc1a23   Chunk   F5 half-finished.
293
        self.k_coeff = -1  # prevent k being read from this instance
c9fdeb00   Chunk   LSB and F4 added.
294
295
        return cov_data

c9fdeb00   Chunk   LSB and F4 added.
296
    def _raw_extract(self, num_bits):
8cfc1a23   Chunk   F5 half-finished.
297
298
299
        k = self.k_coeff
        n = (1 << k) - 1
        if self.is_header == None:
c9fdeb00   Chunk   LSB and F4 added.
300
            self.is_header = True
8cfc1a23   Chunk   F5 half-finished.
301
302
303
        if n == 1 and self.default_embedding:
            f4 = F4(self.ui, self.core)
            f4.seed = self.seed
c9fdeb00   Chunk   LSB and F4 added.
304
            f4.dct_p = self.dct_p
8cfc1a23   Chunk   F5 half-finished.
305
306
307
308
309
310
            f4.steg_data = self.steg_data
            f4.is_header = self.is_header
            f4.steg_ind = self.steg_ind
            hid_data = f4._raw_extract(num_bits)
            self.steg_ind = f4.steg_ind
            self.is_header = False
c9fdeb00   Chunk   LSB and F4 added.
311
312
313
314
315
316
            return hid_data
        remaining_bits = num_bits
        hid_data = np.zeros(num_bits, np.uint8)
        hid_ind = 0

        dct_p = self.dct_p
8cfc1a23   Chunk   F5 half-finished.
317
318

        is_header = False  # signals whether or not extracting header
c9fdeb00   Chunk   LSB and F4 added.
319

8cfc1a23   Chunk   F5 half-finished.
320
321
        if self.excess_bits != None:
            hid_data[hid_ind:hid_ind + self.excess_bits.size] = \
c9fdeb00   Chunk   LSB and F4 added.
322
                    self.excess_bits
8cfc1a23   Chunk   F5 half-finished.
323
            hid_ind += self.excess_bits.size
c9fdeb00   Chunk   LSB and F4 added.
324
            remaining_bits -= self.excess_bits.size
8cfc1a23   Chunk   F5 half-finished.
325

c9fdeb00   Chunk   LSB and F4 added.
326
327
328
        curr_chunk = np.zeros(k, np.uint8)

        update_cnt = int(num_bits / (100.0 * k))