-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathimage_embedder.go
518 lines (434 loc) · 13.6 KB
/
image_embedder.go
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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
package stegano
import (
"bufio"
"bytes"
"errors"
"fmt"
"image"
"os"
"path/filepath"
"runtime"
"sync"
c "github.com/scott-mescudi/stegano/compression"
u "github.com/scott-mescudi/stegano/pkg"
)
// EncodeAndSave embeds the provided data into the given image and saves the modified image to a new file.
// The data is embedded using the specified bit depth. If `defaultCompression` is true, the data is compressed before embedding.
// Returns an error if the data exceeds the embedding capacity of the image or if the saving process fails.
// Parameters:
// - coverImage: The original image where data will be embedded.
// - data: The data to embed into the image.
// - bitDepth: The number of bits per channel used for embedding (0-7).
// - outputFilename: The name of the file where the modified image will be saved.
// - defaultCompression: A flag indicating whether the data should be compressed before embedding.
func (m *EmbedHandler) Encode(coverImage image.Image, data []byte, bitDepth uint8, outputFilename string, defaultCompression bool) error {
// Validate coverImage dimensions
if coverImage == nil {
return ErrInvalidCoverImage
}
height := coverImage.Bounds().Dy()
width := coverImage.Bounds().Dx()
if height <= 0 || width <= 0 {
return ErrInvalidCoverImage
}
// Validate bit depth
if bitDepth < 0 || bitDepth > 7 {
return ErrDepthOutOfRange
}
// Validate data
if len(data) == 0 {
return ErrInvalidData
}
if m.concurrency <= 0 {
m.concurrency = 1
}
// Extract RGB channels
RGBchannels := u.ExtractRGBChannelsFromImageWithConCurrency(coverImage, m.concurrency)
if RGBchannels == nil {
return ErrFailedToExtractRGB
}
maxCapacity := (len(RGBchannels) * 3 * (int(bitDepth) + 1)) / 8
if (len(data)*8)+32 > maxCapacity {
return ErrDataTooLarge
}
// Compress data if required
var indata []byte = data
if defaultCompression {
compressedData, err := c.CompressZSTD(data)
if err != nil {
return ErrFailedToCompressData
}
indata = compressedData
}
// Embed data
embeddedRGBChannels, err := u.EmbedIntoRGBchannelsWithDepth(RGBchannels, indata, bitDepth)
if err != nil {
return fmt.Errorf("failed to embed data into RGB channels: %w", err)
}
// Generate image from embedded RGB channels
imgdata, err := u.SaveImage(embeddedRGBChannels, height, width)
if err != nil {
return ErrFailedToSaveImage
}
// Use default filename if none provided
if outputFilename == "" {
outputFilename = DefaultOutputFile
}
return SaveImage(outputFilename, imgdata)
}
// Decode extracts data embedded in an image using the specified bit depth.
// If the embedded data was compressed, it will be decompressed when `isDefaultCompressed` is true.
// Returns the extracted data or an error if the extraction or decompression fails.
//
// Parameters:
// - coverImage: The image containing embedded data to be extracted.
// - bitDepth: The bit depth used during the embedding process.
// - isDefaultCompressed: A flag indicating whether the embedded data was compressed.
func (m *ExtractHandler) Decode(coverImage image.Image, bitDepth uint8, isDefaultCompressed bool) ([]byte, error) {
// Validate coverImage dimensions
if coverImage == nil {
return nil, ErrInvalidCoverImage
}
if bitDepth < 0 || bitDepth > 7 {
return nil, ErrDepthOutOfRange
}
if m.concurrency <= 0 {
m.concurrency = 1
}
// Extract RGB channels
RGBchannels := u.ExtractRGBChannelsFromImageWithConCurrency(coverImage, m.concurrency)
if RGBchannels == nil {
return nil, ErrFailedToExtractRGB
}
// Extract data
data, err := u.ExtractDataFromRGBchannelsWithDepth(RGBchannels, bitDepth)
if err != nil {
return nil, ErrFailedToExtractData
}
// Validate extracted data length
lenData, err := u.GetlenOfData(data)
if err != nil {
return nil, fmt.Errorf("failed to get length of extracted data: %w", err)
}
if lenData == 0 {
return nil, ErrInvalidDataLength
}
var moddedData = make([]byte, 0, lenData)
defer func() {
if r := recover(); r != nil {
moddedData = nil
err = fmt.Errorf("fatal error: %v", r)
}
}()
for i := 4; i < lenData+4; i++ {
if i >= len(data) {
return nil, fmt.Errorf("index out of range while accessing data: %d", i)
}
moddedData = append(moddedData, data[i])
}
// Decompress data if required
if isDefaultCompressed {
outdata, err := c.DecompressZSTD(moddedData)
if err != nil {
return nil, fmt.Errorf("failed to decompress extracted data: %w", err)
}
return outdata, nil
}
return moddedData, nil
}
// Encode embeds data into a cover image using a specified bit depth, encrypts and compresses the data, and saves the resulting image to the specified output file.
// Secure uses reed solomon codes for persistency
// Parameters:
// - coverImage: The image to embed data into.
// - data: The data to embed in the image.
// - bitDepth: The bit depth used for embedding (valid range: 0-7).
// - outputFilename: The file name to save the resulting image. Defaults to a pre-defined name if empty.
// - password: The password used to encrypt the data.
// Returns:
// - error: An error if any part of the embedding process fails.
func (m *SecureEmbedHandler) Encode(coverImage image.Image, data []byte, bitDepth uint8, outputFilename string, password string) error {
// Validate coverImage dimensions
if coverImage == nil {
return ErrInvalidCoverImage
}
height := coverImage.Bounds().Dy()
width := coverImage.Bounds().Dx()
if height <= 0 || width <= 0 {
return ErrInvalidCoverImage
}
// Validate bit depth
if bitDepth < 0 || bitDepth > 7 {
return ErrDepthOutOfRange
}
// Validate data
if len(data) == 0 {
return ErrInvalidData
}
if m.concurrency <= 0 {
m.concurrency = 1
}
// Extract RGB channels
RGBchannels := u.ExtractRGBChannelsFromImageWithConCurrency(coverImage, m.concurrency)
if RGBchannels == nil {
return ErrFailedToExtractRGB
}
maxCapacity := (len(RGBchannels) * 3 * (int(bitDepth) + 1)) / 8
if (((len(data)*8)+32)*5)+8 > maxCapacity {
return ErrDataTooLarge
}
cipher, err := EncryptData(data, password)
if err != nil {
return err
}
compressedData, err := c.CompressZSTD(cipher)
if err != nil {
return ErrFailedToCompressData
}
RsData, err := u.RsEncode(compressedData, 4)
if err != nil {
return err
}
// Embed data
embeddedRGBChannels, err := u.EmbedIntoRGBchannelsWithDepth(RGBchannels, RsData, bitDepth)
if err != nil {
return fmt.Errorf("failed to embed data into RGB channels: %w", err)
}
// Generate image from embedded RGB channels
imgdata, err := u.SaveImage(embeddedRGBChannels, height, width)
if err != nil {
return ErrFailedToSaveImage
}
// Use default filename if none provided
if outputFilename == "" {
outputFilename = DefaultOutputFile
}
return SaveImage(outputFilename, imgdata)
}
// Decode extracts embedded data from a cover image using a specified bit depth, decrypts and decompresses it, and returns the original data.
// Secure uses reed solomon codes for persistency
// Parameters:
// - coverImage: The image containing the embedded data.
// - bitDepth: The bit depth used for extracting data (valid range: 0-7).
// - password: The password used to decrypt the embedded data.
// Returns:
// - []byte: The extracted original data.
// - error: An error if the extraction process fails.
func (m *SecureExtractHandler) Decode(coverImage image.Image, bitDepth uint8, password string) ([]byte, error) {
// Validate coverImage dimensions
if coverImage == nil {
return nil, ErrInvalidCoverImage
}
if bitDepth < 0 || bitDepth > 7 {
return nil, ErrDepthOutOfRange
}
if m.concurrency <= 0 {
m.concurrency = 1
}
// Extract RGB channels
RGBchannels := u.ExtractRGBChannelsFromImageWithConCurrency(coverImage, m.concurrency)
if RGBchannels == nil {
return nil, ErrFailedToExtractRGB
}
// Extract data
data, err := u.ExtractDataFromRGBchannelsWithDepth(RGBchannels, bitDepth)
if err != nil {
return nil, ErrFailedToExtractData
}
// Validate extracted data length
lenData, err := u.GetlenOfData(data)
if err != nil {
return nil, fmt.Errorf("failed to get length of extracted data: %w", err)
}
if lenData == 0 {
return nil, errors.New("extracted data length is zero")
}
var moddedData = make([]byte, 0, lenData)
defer func() {
if r := recover(); r != nil {
moddedData = nil
err = fmt.Errorf("fatal error: %v", r)
}
}()
for i := 4; i < lenData+4; i++ {
if i >= len(data) {
return nil, fmt.Errorf("index out of range while accessing data: %d", i)
}
moddedData = append(moddedData, data[i])
}
RsUnpacked, err := u.RsDecode(moddedData, 1, 4)
if err != nil {
return nil, err
}
outdata, err := c.DecompressZSTD(RsUnpacked)
if err != nil {
return nil, fmt.Errorf("failed to decompress extracted data: %w", err)
}
return DecryptData(outdata, password)
}
func openFiles(coverImagePath, dataFilePath string) (coverImage image.Image, dataFile []byte, err error) {
cimg, err := Decodeimage(coverImagePath)
if err != nil {
return nil, nil, err
}
df, err := os.ReadFile(dataFilePath)
if err != nil {
return nil, nil, err
}
return cimg, df, nil
}
// EmbedFile embeds data from a file into an image using a default bit depth of 1 (the last two bits in a byte).
// The data is first compressed and encrypted with the provided password before embedding into the image.
// Returns an error if the process fails at any stage.
//
// Parameters:
// - coverImagePath: The file path of the image to embed data into.
// - dataFilePath: The file path of the data to embed.
// - outputFilePath: The file path to save the resulting image with embedded data.
// - password: A password used to encrypt the data before embedding.
// ExtractFile extracts embedded data from an image using a default bit depth of 1 (the last two bits in a byte).
// The embedded data is decrypted and decompressed using the provided password.
// The extracted file is saved using its original name (stored within the embedded data).
// Returns an error if the process fails at any stage.
//
// Parameters:
// - coverImagePath: The file path of the image containing embedded data.
// - password: A password used to decrypt the embedded data after extraction.
func EmbedFile(coverImagePath, dataFilePath, outputFilePath, password string, bitDepth uint8) error {
if coverImagePath == "" {
return errors.New("invalid coverImagePath")
}
if dataFilePath == "" {
return errors.New("invalid dataFilePath")
}
if outputFilePath == "" {
return errors.New("invalid outputFilePath")
}
if password == "" {
return errors.New("invalid password")
}
if bitDepth > 7 {
return ErrDepthOutOfRange
}
if ext := filepath.Ext(outputFilePath); ext != ".png" {
return fmt.Errorf("output file must have a .png extension, got '%s'", ext)
}
fp := filepath.Base(dataFilePath)
ext := fmt.Sprintf("/-%s-/\n", fp)
cf, df, err := openFiles(coverImagePath, dataFilePath)
if err != nil {
return err
}
df = append([]byte(ext), df...)
var (
wg sync.WaitGroup
erchan = make(chan error)
channels []u.RgbChannel
)
wg.Add(2)
go func() {
defer wg.Done()
channels = u.ExtractRGBChannelsFromImageWithConCurrency(cf, runtime.NumCPU())
if (len(df)*8)+32 > len(channels)*3*(int(bitDepth)+1) {
erchan <- fmt.Errorf("error: Data too large to embed into the image")
return
}
}()
go func() {
defer wg.Done()
df, err = c.CompressZSTD(df)
if err != nil {
erchan <- err
return
}
df, err = u.Encrypt(password, df)
if err != nil {
erchan <- err
return
}
}()
select {
case <-erchan:
return err
default:
}
wg.Wait()
channels, err = u.EmbedIntoRGBchannelsWithDepth(channels, df, bitDepth)
if err != nil {
return err
}
newImage, err := u.SaveImage(channels, cf.Bounds().Max.Y, cf.Bounds().Max.X)
if err != nil {
return nil
}
return SaveImage(outputFilePath, newImage)
}
// ExtractFile extracts embedded data from an image using a default bit depth of 1 (the last two bits in a byte).
// The embedded data is decrypted and decompressed using the provided password.
// The extracted file is saved using its original name (stored within the embedded data).
// Returns an error if the process fails at any stage.
//
// Parameters:
// - coverImagePath: The file path of the image containing embedded data.
// - password: A password used to decrypt the embedded data after extraction.
func ExtractFile(coverImagePath, password string, bitDepth uint8) error {
if coverImagePath == "" {
return errors.New("invalid coverImagePath")
}
if password == "" {
return errors.New("invalid password")
}
if bitDepth > 7 {
return ErrDepthOutOfRange
}
cf, err := Decodeimage(coverImagePath)
if err != nil {
return err
}
channels := u.ExtractRGBChannelsFromImageWithConCurrency(cf, runtime.NumCPU())
embeddedData, err := u.ExtractDataFromRGBchannelsWithDepth(channels, bitDepth)
if err != nil {
return err
}
lenData, err := u.GetlenOfData(embeddedData)
if err != nil {
return err
}
var cipherText = make([]byte, 0, lenData)
defer func() {
if r := recover(); r != nil {
cipherText = nil
err = fmt.Errorf("fatal error: %v", r)
}
}()
for i := 4; i < lenData+4; i++ {
if i >= len(embeddedData) {
return fmt.Errorf("index out of range while accessing data: %d", i)
}
cipherText = append(cipherText, embeddedData[i])
}
plaintext, err := u.Decrypt(password, cipherText)
if err != nil {
return err
}
plaintext, err = c.DecompressZSTD(plaintext)
if err != nil {
return err
}
scanner := bufio.NewScanner(bytes.NewReader(plaintext))
var filename string
var size int
if scanner.Scan() {
filename = scanner.Text()
size = len(scanner.Bytes())
}
ff, err := os.Create(filename[2 : len(filename)-2])
if err != nil {
return err
}
defer ff.Close()
_, err = ff.Write(plaintext[size+1:])
if err != nil {
return err
}
return nil
}