1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 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 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 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
| import torch import torch.nn as nn import torchvision import torchvision.transforms as T from PIL import Image from collections import Counter import numpy as np import math import zlib from reedsolo import RSCodec import re
class ResidualDenseBlock_out(nn.Module): def __init__(self, bias=True): super(ResidualDenseBlock_out, self).__init__() self.channel = 12 self.hidden_size = 32 self.conv1 = nn.Conv2d(self.channel, self.hidden_size, 3, 1, 1, bias=bias) self.conv2 = nn.Conv2d(self.channel + self.hidden_size, self.hidden_size, 3, 1, 1, bias=bias) self.conv3 = nn.Conv2d(self.channel + 2 * self.hidden_size, self.hidden_size, 3, 1, 1, bias=bias) self.conv4 = nn.Conv2d(self.channel + 3 * self.hidden_size, self.hidden_size, 3, 1, 1, bias=bias) self.conv5 = nn.Conv2d(self.channel + 4 * self.hidden_size, self.channel, 3, 1, 1, bias=bias) self.lrelu = nn.LeakyReLU(negative_slope=0.2, inplace=True)
def forward(self, x): x1 = self.lrelu(self.conv1(x)) x2 = self.lrelu(self.conv2(torch.cat((x, x1), 1))) x3 = self.lrelu(self.conv3(torch.cat((x, x1, x2), 1))) x4 = self.lrelu(self.conv4(torch.cat((x, x1, x2, x3), 1))) x5 = self.conv5(torch.cat((x, x1, x2, x3, x4), 1)) return x5
class INV_block(nn.Module): def __init__(self, clamp=2.0): super().__init__() self.split_len1 = 12 self.split_len2 = 12 self.clamp = clamp self.r = ResidualDenseBlock_out() self.y = ResidualDenseBlock_out() self.f = ResidualDenseBlock_out()
def e(self, s): return torch.exp(self.clamp * 2 * (torch.sigmoid(s) - 0.5))
def forward(self, x, rev=False): if rev: return self.inverse(x) return self.direct_forward(x)
def direct_forward(self, x): x1, x2 = (x.narrow(1, 0, self.split_len1), x.narrow(1, self.split_len1, self.split_len2)) t2 = self.f(x2) y1 = x1.clone() + t2 s1, t1 = self.r(y1), self.y(y1) y2 = self.e(s1) * x2 + t1 return torch.cat((y1, y2), 1)
def inverse(self, y_cat): y1, y2 = (y_cat.narrow(1, 0, self.split_len1), y_cat.narrow(1, self.split_len1, self.split_len2)) s1, t1 = self.r(y1), self.y(y1) x2 = (y2 - t1) / self.e(s1) t2 = self.f(x2) x1 = y1.clone() - t2 return torch.cat((x1, x2), 1)
class D3net(nn.Module): def __init__(self): super(D3net, self).__init__() self.inv_blocks = nn.ModuleList() for _ in range(8): self.inv_blocks.append(INV_block())
def forward(self, x, rev=False): if rev: return self.inverse(x) return self.direct_forward(x)
def direct_forward(self, x): out = x for block in self.inv_blocks: out = block.direct_forward(out) return out
def inverse(self, x): out = x for block in reversed(self.inv_blocks): out = block.inverse(out) return out
class Model(nn.Module): def __init__(self, use_cuda=True): super(Model, self).__init__() self.model = D3net() if use_cuda and torch.cuda.is_available(): self.model.cuda()
def forward(self, x, rev=False): return self.model(x, rev=rev)
rs = RSCodec(128)
class DWT(nn.Module): def __init__(self): super(DWT, self).__init__() self.requires_grad = False
def forward(self, x): x01 = x[:, :, 0::2, :] / 2 x02 = x[:, :, 1::2, :] / 2 x1 = x01[:, :, :, 0::2] x2 = x02[:, :, :, 0::2] x3 = x01[:, :, :, 1::2] x4 = x02[:, :, :, 1::2] x_LL = x1 + x2 + x3 + x4 x_HL = -x1 - x2 + x3 + x4 x_LH = -x1 + x2 - x3 + x4 x_HH = x1 - x2 - x3 + x4 return torch.cat((x_LL, x_HL, x_LH, x_HH), 1)
class IWT(nn.Module): def __init__(self): super(IWT, self).__init__() self.requires_grad = False
def forward(self, x): r = 2 in_batch, in_channel, in_height, in_width = x.size() out_batch, out_channel, out_height, out_width = in_batch, int( in_channel / (r ** 2)), r * in_height, r * in_width x1 = x[:, 0:out_channel, :, :] / 2 x2 = x[:, out_channel:out_channel * 2, :, :] / 2 x3 = x[:, out_channel * 2:out_channel * 3, :, :] / 2 x4 = x[:, out_channel * 3:out_channel * 4, :, :] / 2 h = torch.zeros([out_batch, out_channel, out_height, out_width], device=x.device).float() h[:, :, 0::2, 0::2] = x1 - x2 - x3 + x4 h[:, :, 1::2, 0::2] = x1 - x2 + x3 - x4 h[:, :, 0::2, 1::2] = x1 + x2 - x3 - x4 h[:, :, 1::2, 1::2] = x1 + x2 + x3 + x4 return h
def auxiliary_variable(shape, device): return torch.randn(shape, device=device)
def bits_to_bytearray(bits): ints = [] bits_list = np.array(bits).astype(int).tolist() for b in range(len(bits_list) // 8): byte_bits = bits_list[b * 8:(b + 1) * 8] ints.append(int(''.join([str(bit) for bit in byte_bits]), 2)) return bytearray(ints)
def bytearray_to_text(x_bytearray): try: decoded_data_tuple = rs.decode(x_bytearray) data_to_decompress = None if isinstance(decoded_data_tuple, tuple) or isinstance(decoded_data_tuple, list): if decoded_data_tuple: if isinstance(decoded_data_tuple[0], list) and len(decoded_data_tuple[0]) > 0: data_to_decompress = decoded_data_tuple[0][0] else: data_to_decompress = decoded_data_tuple[0] else: data_to_decompress = decoded_data_tuple
if data_to_decompress is None: return False
decompressed_text_bytes = zlib.decompress(data_to_decompress) return decompressed_text_bytes.decode("utf-8") except Exception: return False
transform_stego = T.Compose([ T.CenterCrop((720, 1280)), T.ToTensor(), ])
def load_model_weights(model_wrapper_instance, weight_file_path): print(f"Attempting to load weights from: {weight_file_path}") try: full_state_dict_from_file = torch.load(weight_file_path, map_location=lambda storage, loc: storage, weights_only=False)
if 'net' in full_state_dict_from_file: params_from_file = full_state_dict_from_file['net'] else: params_from_file = full_state_dict_from_file
transformed_state_dict = {} for k_orig, v_param in params_from_file.items(): if 'tmp_var' in k_orig: continue
new_k = k_orig
if k_orig.startswith("model."): key_after_model_prefix = k_orig[len("model."):] match = re.match(r"inv(\d+)\.(.*)", key_after_model_prefix) if match: inv_idx = int(match.group(1)) - 1 rest_of_key = match.group(2) new_k = f"inv_blocks.{inv_idx}.{rest_of_key}" elif k_orig.startswith("inv"): match = re.match(r"inv(\d+)\.(.*)", k_orig) if match: inv_idx = int(match.group(1)) - 1 rest_of_key = match.group(2) new_k = f"inv_blocks.{inv_idx}.{rest_of_key}" if new_k == k_orig and (k_orig.startswith("model.inv") or k_orig.startswith("inv")): print(f"Warning: Key '{k_orig}' was not transformed as expected. Check patterns.")
transformed_state_dict[new_k] = v_param
model_wrapper_instance.model.load_state_dict(transformed_state_dict) print(f"Weights loaded successfully into D3net model.") except FileNotFoundError: print(f"Error: Weight file '{weight_file_path}' not found.") raise except Exception as e: print(f"Error loading or processing weights from '{weight_file_path}': {e}") raise
def stego_transform2tensor(img_path, current_device): img = Image.open(img_path).convert('RGB') transformed_img = transform_stego(img) return transformed_img.unsqueeze(0).to(current_device)
def decrypt_message(stego_image_path, weight_file): print("Initializing...") current_device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") print(f"Using device: {current_device}")
d3net_wrapper = Model(use_cuda=torch.cuda.is_available())
dwt = DWT().to(current_device) iwt = IWT().to(current_device)
load_model_weights(d3net_wrapper, weight_file) d3net_wrapper.eval()
print(f"Loading steganographic image: {stego_image_path}") stego_tensor = stego_transform2tensor(stego_image_path, current_device)
B, C_stego, H_stego, W_stego = stego_tensor.size()
print("Applying DWT to stego image...") Y1_observed_dwt = dwt(stego_tensor)
print("Generating auxiliary variable...") Y2_for_inverse_dwt_shape = Y1_observed_dwt.shape Y2_for_inverse_dwt = auxiliary_variable(Y2_for_inverse_dwt_shape, current_device)
Y_input_for_inverse = torch.cat((Y1_observed_dwt, Y2_for_inverse_dwt), dim=1)
print("Applying inverse D3Net model...") with torch.no_grad(): X_reconstructed_dwt = d3net_wrapper(Y_input_for_inverse, rev=True)
num_channels_per_dwt_stream = Y1_observed_dwt.shape[1] reconstructed_payload_dwt = X_reconstructed_dwt.narrow(1, num_channels_per_dwt_stream, num_channels_per_dwt_stream)
print("Applying IWT to reconstructed payload DWT...") recovered_payload_spatial = iwt(reconstructed_payload_dwt)
print("Binarizing recovered payload...") recovered_bits_flat = (recovered_payload_spatial.contiguous().view(-1) > 0.5).float()
print("Converting bits to text...") candidates = Counter() bits_list = recovered_bits_flat.data.int().cpu().numpy().tolist()
terminator = b'\x00' * (32 // 8) byte_array_data = bits_to_bytearray(bits_list)
potential_message_parts = [] current_part_start_index = 0 search_from_index = 0 while search_from_index < len(byte_array_data): terminator_found_at = -1 try: terminator_found_at = byte_array_data.find(terminator, search_from_index) except TypeError: idx = search_from_index while idx <= len(byte_array_data) - len(terminator): if byte_array_data[idx: idx + len(terminator)] == terminator: terminator_found_at = idx break idx += 1
if terminator_found_at != -1: part = byte_array_data[current_part_start_index: terminator_found_at] if part: potential_message_parts.append(part) current_part_start_index = terminator_found_at + len(terminator) search_from_index = current_part_start_index else: part = byte_array_data[current_part_start_index:] if part: potential_message_parts.append(part) break
if not potential_message_parts and len(byte_array_data) > 0: potential_message_parts.append(byte_array_data)
for candidate_bytes in potential_message_parts: if not candidate_bytes: continue candidate_text = bytearray_to_text(candidate_bytes) if candidate_text: candidates[candidate_text] += 1
if not candidates: print("\nFailed to find any candidate message after decoding.") return None
most_common_candidate, count = candidates.most_common(1)[0] print(f"\n--- Recovered Message (most common, appeared {count} times) ---") print(most_common_candidate) print("--- End of Message ---") return most_common_candidate
if __name__ == '__main__': stego_image_file = 'mysterious_invitation.png' model_weights_file = 'magic.potions'
import os
if not os.path.exists(stego_image_file): print(f"Error: Stego image '{stego_image_file}' not found. Please place it in the current directory.") elif not os.path.exists(model_weights_file): print(f"Error: Model weights file '{model_weights_file}' not found. Please place it in the current directory.") else: decrypt_message(stego_image_file, model_weights_file)
|