Blame view

msteg/__init__.py 5.83 KB
1d19f0e7   Chunk   staged.
1
2
3
4
__author__ = 'chunk'

import numpy as np

ca73c96f   Chunk   Transformed into ...
5
6
from ..mjpeg import Jpeg
from ..common import *
1d19f0e7   Chunk   staged.
7
8
9

__all__ = ['StegBase', 'sample_key']

95f76ce8   Chunk   theis finished.论文...
10
11
sample_key = [46812L, 20559L, 31360L, 16681L, 27536L, 39553L, 5427L, 63029L, 56572L, 36476L, 25695L,
              61908L, 63014L,
1d19f0e7   Chunk   staged.
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
              5908L, 59816L, 56765L]


class StegBase(object):
    """
    This is the base class for some of the JPEG-algorithms that behave
    similarly such as JSteg, OutGuess and F3.
    """

    def __init__(self, key=sample_key):
        """
        Constructor of the JPEGSteg class.
        """
        self.t0 = None
        self.cov_jpeg = None
        self.cov_data = None
        self.hid_data = None
        self.key = key

    def _get_cov_data(self, img_path):
        """
        Returns DCT coefficients of the cover image.
        """
ca73c96f   Chunk   Transformed into ...
35
        self.cov_jpeg = Jpeg(img_path)
1d19f0e7   Chunk   staged.
36
        self.key = self.cov_jpeg.getkey()
9ff70cf4   Chunk   capacity engeneer...
37
38
39
        self.cov_data = self.cov_jpeg.getCoefBlocks('Y')
        # self.capacity = self.cov_jpeg.getCapacity('Y')
        self.capacity = np.sum(self.cov_data != 0) - np.size(self.cov_data) / 64
1d19f0e7   Chunk   staged.
40
41
        return self.cov_data

9ff70cf4   Chunk   capacity engeneer...
42
    def _get_hid_data(self, src_hidden, frommem=False):
1d19f0e7   Chunk   staged.
43
44
45
        """
        Returnsthe secret data as byte sequence.
        """
9ff70cf4   Chunk   capacity engeneer...
46
47
48
49
50
        if not frommem:
            raw = [0, 0, 0, 0] + np.fromfile(src_hidden, np.uint8).tolist()
        else:
            raw = [0, 0, 0, 0] + np.fromstring(src_hidden, dtype=np.uint8).tolist()

1d19f0e7   Chunk   staged.
51
52
53
54
55
56
        raw_size = len(raw)
        for i in xrange(4):
            raw[i] = raw_size % 256
            raw_size /= 256
        self.hid_data = np.array(raw, dtype=np.uint8)

9ff70cf4   Chunk   capacity engeneer...
57
        if np.size(self.hid_data) * 8 > self.capacity:
95f76ce8   Chunk   theis finished.论文...
58
59
60
            raise Exception(
                "Cover image is too small to embed data.Cannot fit %d bits in %d NZ-DCT coefficients" % (
                    np.size(self.hid_data) * 8, self.capacity))
1d19f0e7   Chunk   staged.
61
62
        return self.hid_data

95f76ce8   Chunk   theis finished.论文...
63
    def _post_embed_actions(self, src_cover, src_hidden, tgt_stego, frommem=False):
1d19f0e7   Chunk   staged.
64
65
66
67
68
69
        """
        This function isn't named very accurately. It actually calls the
        _raw_embed function in inherited classes.
        """
        try:
            cov_data = self._get_cov_data(src_cover)
95f76ce8   Chunk   theis finished.论文...
70
71
            # hid_data = self._get_hid_data(src_hidden)
            hid_data = self._get_hid_data(src_hidden, frommem)
1d19f0e7   Chunk   staged.
72
73
74
75
76
77
78
79
80
81
            # print hid_data.dtype,type(hid_data),hid_data.tolist()
            cov_data, bits_cnt = self._raw_embed(cov_data, hid_data)

            if bits_cnt != np.size(hid_data) * 8:
                raise Exception("Expected embedded size is %db but actually %db." % (
                    np.size(hid_data) * 8, bits_cnt))

            self.cov_jpeg.setCoefBlocks(cov_data)
            self.cov_jpeg.Jwrite(tgt_stego)

9ff70cf4   Chunk   capacity engeneer...
82
            self._display_rate('embed', self.capacity, bits_cnt)
1d19f0e7   Chunk   staged.
83

080c30c2   Chunk   F5 lib updated. I...
84
85
86
87
88
            # # size_cov = os.path.getsize(tgt_stego)
            # size_cov = np.size(cov_data) / 8
            # size_embedded = np.size(hid_data)
            # self._display_stats("embedded", size_cov, size_embedded,
            # time.time() - self.t0)
1d19f0e7   Chunk   staged.
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133

        except TypeError as e:
            raise e
        except Exception as expt:
            print "Exception when embedding!"
            raise

    def _post_extract_actions(self, src_steg, tgt_hidden):
        """
        This function isn't named very accurately. It actually calls the
        _raw_extract function in inherited classes.
        """
        try:
            steg_data = self._get_cov_data(src_steg)
            # emb_size = os.path.getsize(src_steg)
            emb_size = np.size(steg_data) / 8


            # recovering file size
            header_size = 4 * 8
            size_data, bits_cnt = self._raw_extract(steg_data, header_size)
            if bits_cnt < header_size:
                raise Exception("Expected embedded size is %db but actually %db." % (
                    header_size, bits_cnt))

            size_data = bits2bytes(size_data)
            size_hd = 0
            for i in xrange(4):
                size_hd += size_data[i] * 256 ** i

            raw_size = size_hd * 8

            if raw_size > np.size(steg_data):
                raise Exception("Supposed secret data too large for stego image.")

            hid_data, bits_cnt = self._raw_extract(steg_data, raw_size)

            if bits_cnt != raw_size:
                raise Exception("Expected embedded size is %db but actually %db." % (
                    raw_size, bits_cnt))

            hid_data = bits2bytes(hid_data)
            # print hid_data.dtype,type(hid_data),hid_data.tolist()
            hid_data[4:].tofile(tgt_hidden)

9ff70cf4   Chunk   capacity engeneer...
134
135
136
137
138
            self._display_rate('extract', self.capacity, bits_cnt)

            # self._display_stats("extracted", emb_size,
            # np.size(hid_data),
            #                     time.time() - self.t0)
1d19f0e7   Chunk   staged.
139
140
141
142
        except Exception as expt:
            print "Exception when extracting!"
            raise

1d19f0e7   Chunk   staged.
143
144
145
146
147
148
149
150
151
152
153
154
155
    def _looks_like_jpeg(self, path):
        try:
            with open(path, 'r') as f:
                return f.read(2) == '\xff\xd8'
        except IOError:
            return False

    def _display_stats(self, verb, cov_size, emb_size, duration):
        print(
            "%dB %s in %.2fs (%.2f kBps), embedding ratio: %.4f" %
            (emb_size, verb, duration, (emb_size / duration) / 1000.,
             float(emb_size) / cov_size))

9ff70cf4   Chunk   capacity engeneer...
156
157
    def _display_rate(self, verb, cov_bits, emb_bits):
        print "%s: %d bits\trate: %.4f bpc" % (verb, emb_bits, float(emb_bits) / cov_bits)
080c30c2   Chunk   F5 lib updated. I...
158

1d19f0e7   Chunk   staged.
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
    # set & get
    def set_key(self, key):
        assert key != None
        self.key = key

    def get_key(self):
        return self.key

    # dummy functions to please pylint
    def _raw_embed(self, cov_data, hid_data):
        pass

    def _raw_extract(self, steg_data, num_bits):
        pass

    def _dummy_embed_hook(self, cov_data, hid_data):
        pass

    def _dummy_extract_hook(self, steg_data, num_bits):
        pass