/
AS4PGC.py
3117 lines (2911 loc) · 172 KB
/
AS4PGC.py
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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
AS4PGC.py
~~~~~~~~~
This module contains functions for hiding and recovering files
using compressed audio files of types supported by ffmpeg (e.g. mp3, flac, ogg) but also uncompressed .wav is supported.
:copyright: (c) 2021 by Clark Fieseln.
:license: MIT License, see LICENSE.md for more details.
"""
"""
Notes
~~~~~
Warning! Hiding files inside "big audio files" may take several minutes.
Formats tested so far: MP3, FLAC, OGG, WAV
#####################################################################################
The target of this steganographic technique is hiding information in compressed audio files instead of using the classical
LSB-steganography on .WAV files. But also uncompressed .WAV files may be used as carrier.
This results in a lower capacity, but an audio format is used, which is much more wide spread and therefore less
suspicious.
The main reason it is not possible to directly manipulate "single" samples as in .WAV format
is because of changes resulting from conversion e.g. in .MP3 format which distort signal manipulations.
Modifications on single bits of the samples are just too small to survive audio compression reliably.
Instead, the audio signal is partitioned in small chunks and then the FFT of each chunk is calculated.
The FFT-series obtained as a result, is manipulated by increasing or decreasing the amplitude of the FFT at specific
coding-frequencies.
Coding is done on alternating chunks, using unmodified chunks as reference points.
A linear interpolation between these reference points determines the threshold between ones and zeros.
It is important that the FFT-series has consecutive samples that are highly correlated.
"""
# Module description:
#####################
# first lines of code: definitions, load/create config.ini
# print_progress(..): print progress bar
# write(): hide message in carrier and output result in stego file
# read(): extract hidden message from stego file
# main(): call write() if -w option or read() if -r option
# psnr(): calculate Peak Signal To Noise Ratio
# snr(): calulate Signal To Noise Ratio
# nextpow2(): helper function for freq_shift()
# freq_shift(): frequency shift a signal using SSB modulation
# imports
#########
import copy
import traceback
import soundfile as sf
import matplotlib.pyplot as plt
import shlex, subprocess
import simpleaudio as sa
import numpy as np
import scipy.io.wavfile as wf
from scipy.fft import rfft, irfft
import math
from inspect import currentframe, getframeinfo
import random
from bitarray import bitarray
from timeit import default_timer as timer
from datetime import timedelta
import logging
import argparse
from getpass import getpass
import os
from dataclasses import dataclass
import configparser
from tinytag import TinyTag
import base64
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
import zlib
from shutil import copy2
from scipy import signal
from sys import exit
# version
#########
# TODO: import from setup.py or from __init__.py?
# if we import it from setup.py the help shows "strange default parameters"...
# import setup
# from setup import __version__
__version__ = "1.1.6"
# current frame
###############
cf = currentframe()
# header
########
# Note: HEADER_PAYLOAD_SIZE_BYTES as bytes() will result in encrypted data of size HEADER_SIZE_BYTES
# Header = compression_on encryption_on , file_name , size # padding
# max. size in bytes 1 1 1 36 1 6 1 (HEADER_PAYLOAD_SIZE_BYTES -
# (len(file_name) + len(size) + 5))
#####################################################################################################################
HEADER_SIZE_BYTES = 140
HEADER_PAYLOAD_SIZE_BYTES = 47
MAX_LEN_MSG_FILE_NAME = 36
# Note: LEVEL_OF_COMPRESSION: 9 highest but slow, 6 default compromise, 1 fast but low compression
LEVEL_OF_COMPRESSION = 9
# argument parser
#################
parser = argparse.ArgumentParser(prog='as4pgc',
usage='%(prog)s -w <message_file> <carrier_file> [options]\n or\n %(prog)s -r <stego_file> [options]',
description='Hide message_file (e.g. type txt or zip) inside carrier_file (e.g. type mp3, ogg, flac, wav)\nor\nExtract message_file from stego_file.')
group = parser.add_mutually_exclusive_group()
group.add_argument('-w', "--write", action='store', type=str, nargs=2, help='<path and name of file with secret message (any type)> <path and name of file used as a carrier to embed \
the secret message file (mono or stereo)>', metavar='')
parser.add_argument('-f', "--output_file", action='store', type=str, help='(-w) path and name of stego output file of same type as carrier or (-r) name of message output file', metavar='')
parser.add_argument('-n', "--no_encryption", action='store_true', help='do NOT encrypt the secret message before hiding it')
group.add_argument('-r', "--read", action='store', type=str, help='<path and name of stego file with hidden secret message (e.g. type .mp3 mono)>', metavar='')
parser.add_argument('-v', "--verbose", action='store_true', help='display details during program execution')
parser.add_argument('-l', "--verbose_level", action='store', type=str, choices={"info","warning","error","critical","debug"}, help=': info, warning, error, critical, debug', metavar='')
parser.add_argument('-p', "--plot", action='store_true', help='show plots')
parser.add_argument('-s', "--sound", action='store_true', help='play stego output file')
parser.add_argument('-a', "--hide", action='store_true', help='hide output file using attrib')
group.add_argument('-d', "--defaultconfig", action='store_true', help='create default config.ini and exit (file can be edited to customize) - when used together with -m config.ini is \
messed-up with the password')
parser.add_argument('-m', "--messupconfig", action='store_true', help='mess up configuration as derived from password (needs to be used in both write and read calls)')
parser.add_argument('-V', "--version", action='version', version="%(prog)s " + __version__, help='show version and exit')
# parse arguments
# with options -h or -V the program exits after next code-line
##############################################################
args = parser.parse_args()
# arguments?
############
if args.defaultconfig == False\
and\
isinstance(args.write, type(None))\
and\
isinstance(args.read, type(None)):
print("You need to provide some option, for help type: as4pgc -h")
exit(cf.f_lineno)
# write(=hide) or read(=recover) files
######################################
message_file = ""
carrier_file = ""
stego_file = ""
WRITE = False
if not isinstance(args.write, type(None)):
message_file = args.write[0]
carrier_file = args.write[1]
WRITE = True
elif not isinstance(args.read, type(None)):
stego_file = args.read
# logging
#########
# LOGGING_LEVEL specifies the lowest-severity log message a logger will handle, where debug is the lowest built-in severity level and critical is the highest built-in severity.
# For example, if the severity level is INFO, the logger will handle only INFO, WARNING, ERROR, and CRITICAL messages and will ignore DEBUG messages.
DO_LOG = args.verbose
if args.verbose == False:
# set DO_LOG to true anyways...logging level will be set to ERROR in this case
DO_LOG = True
if not isinstance(args.verbose_level, type(None)):
LOGGING_LEVEL = args.verbose_level
LOGGING_LEVEL = "logging." + LOGGING_LEVEL.upper()
else:
if args.verbose == False:
LOGGING_LEVEL = "logging.ERROR"
else:
# -v provided but no level specified, take INFO as default in that case
LOGGING_LEVEL = "logging.INFO"
logging_level = logging.ERROR # logging.INFO
if LOGGING_LEVEL == "logging.DEBUG":
logging_level = logging.DEBUG
elif LOGGING_LEVEL == "logging.INFO":
logging_level = logging.INFO
elif LOGGING_LEVEL == "logging.WARNING":
logging_level = logging.WARNING
elif LOGGING_LEVEL == "logging.ERROR":
logging_level = logging.ERROR
elif LOGGING_LEVEL == "logging.CRITICAL":
logging_level = logging.CRITICAL
if args.verbose == False:
# we activate it anyways with default logging.ERROR but, in this case we dont want to make it
# look like a log, so we remove the timestamp
logging.basicConfig(format='%(message)s', datefmt='%H:%M:%S', level=logging_level)
else:
logging.basicConfig(format='%(asctime)s.%(msecs)03d %(message)s', datefmt='%H:%M:%S', level=logging_level)
logger = logging.getLogger()
logger.disabled = not DO_LOG
logging.info(args)
logging.info("DO_LOG = " + str(DO_LOG))
logging.info("LOGGING_LEVEL = " + str(LOGGING_LEVEL))
# module variable containing
# - hardcoded default configuration
# - configuration read from config.ini
# - configuration partially derived from password
#####################################################
@dataclass
class Configuration:
# normal configuration:
#######################
CHUNK_LEN_SAMPLES: int
MAX_VOLUME: float
SEED_IGNORE: int
SEED_IGNORE_CODE_DECEPTION: int
SEED_THRESHOLD: int # TODO: implement code using this..
IGNORE_THRESHOLD: float
DO_IGNORE_SOME: bool
DO_DECEPTION: bool
BSF_MIN_ATTENUATION_DB: int
SKIP_CODING_IF_MIN_EXCEEDED_DEFAULT: float
SKIP_CODING_IF_MAX_EXCEEDED_DEFAULT: float
INTERLEAVED_CHUNKS: int
INTERLEAVED_FC: int
SAMPLING_FREQUENCY: int
NORMALIZE_SETTINGS: bool
MAX_NR_OF_ITERATIONS: int
# advanced configuration:
#########################
CODE_FREQUENCY_START_BIN: int
CODE_FREQUENCY_END_BIN: int
CHECK_IMAG_TOO: bool
KEEP_TEMP_FILES: bool
BITRATE: int
INTERPOLATE_AND_DUMMY_CODE_ALL: bool
AVG_INTERPOLATION: bool
INTERPOLATE_WITH_MEAN: bool
CODE_WITH_MAGNITUDE: bool
RECODE_FACTOR_PLUS: float
CODE_FACTOR_PERCENT: float
CODE_FACTOR_PERCENT_DETECTION_THRESHOLD: float
FFMPEG_VERSION: str
# Note: these default values will be used in case we can't read or there is no config.ini
#########################################################################################
configuration = Configuration(
# basic configuration:
######################
480, # 960, # 480, # CHUNK_LEN_SAMPLES
0.75, # MAX_VOLUME
77, # SEED_IGNORE
78, # SEED_IGNORE_CODE_DECEPTION
79, # SEED_THRESHOLD
0.99, # IGNORE_THRESHOLD - 0.99 will result in approx. 1% of bits being NOT coded
True, # DO_IGNORE_SOME
True, # DO_DECEPTION
85, # BSF_MIN_ATTENUATION_DB
0.0083, # SKIP_CODING_IF_MIN_EXCEEDED_DEFAULT - depends on NORMALIZE_SETTINGS
9999.9, # 0.1000, # SKIP_CODING_IF_MAX_EXCEEDED_DEFAULT - depends on NORMALIZE_SETTINGS
2, # INTERLEAVED_CHUNKS
2, # INTERLEAVED_FC
48000, # SAMPLING_FREQUENCY
True, # NORMALIZE_SETTINGS
250, # MAX_NR_OF_ITERATIONS
# advanced configuration:
#########################
120, # 240, # 120, # CODE_FREQUENCY_START_BIN
179, # 239 # 359 # 399, # 199, # CODE_FREQUENCY_END_BIN
True, # CHECK_IMAG_TOO
False, # KEEP_TEMP_FILES
320000, # BITRATE
False, # INTERPOLATE_AND_DUMMY_CODE_ALL
False, # AVG_INTERPOLATION
True, # INTERPOLATE_WITH_MEAN
True, # CODE_WITH_MAGNITUDE
1.15, # RECODE_FACTOR_PLUS
70.0, # CODE_FACTOR_PERCENT
40.0, # CODE_FACTOR_PERCENT_DETECTION_THRESHOLD
"4.4-full_build-www.gyan.dev") # FFMPEG_VERSION
# configparser
##############
config = configparser.ConfigParser(allow_no_value=True)
config_filename = "config.ini"
# if option -d provided, then force creation of default config.ini
# by renaming the current config.ini and storing a backup as old.config.ini
###########################################################################
if args.defaultconfig == True:
if os.path.isfile(config_filename):
if os.path.isfile('old.' + config_filename):
os.remove('old.' + config_filename)
logging.info("Deleted old." + config_filename)
os.rename(config_filename, 'old.'+config_filename)
logging.info("Created backup of "+config_filename+" as old."+config_filename)
else:
logging.info("Reading " + config_filename + "...")
# Load the configuration file
#############################
if os.path.isfile(config_filename):
try:
config.read(config_filename)
logging.info(" Sections: " + config.sections().__str__())
if "myConfig" in config:
logging.info(" Keys in section myConfig:")
if "CHUNK_LEN_SAMPLES" in config["myConfig"]:
configuration.CHUNK_LEN_SAMPLES = int(config['myConfig']['CHUNK_LEN_SAMPLES'])
logging.info(" configuration.CHUNK_LEN_SAMPLES = " + configuration.CHUNK_LEN_SAMPLES.__str__())
if "MAX_VOLUME" in config["myConfig"]:
configuration.MAX_VOLUME = float(config['myConfig']['MAX_VOLUME'])
logging.info(" configuration.MAX_VOLUME = " + configuration.MAX_VOLUME.__str__())
if "SEED_IGNORE" in config["myConfig"]:
configuration.SEED_IGNORE = int(config['myConfig']['SEED_IGNORE'])
logging.info(" configuration.SEED_IGNORE = " + configuration.SEED_IGNORE.__str__())
if "SEED_IGNORE_CODE_DECEPTION" in config["myConfig"]:
configuration.SEED_IGNORE_CODE_DECEPTION = int(config['myConfig']['SEED_IGNORE_CODE_DECEPTION'])
logging.info(" configuration.SEED_IGNORE_CODE_DECEPTION = " + configuration.SEED_IGNORE_CODE_DECEPTION.__str__())
if "SEED_THRESHOLD" in config["myConfig"]:
configuration.SEED_THRESHOLD = int(config['myConfig']['SEED_THRESHOLD'])
logging.info(" configuration.SEED_THRESHOLD = " + configuration.SEED_THRESHOLD.__str__())
if "IGNORE_THRESHOLD" in config["myConfig"]:
configuration.IGNORE_THRESHOLD = float(config['myConfig']['IGNORE_THRESHOLD'])
logging.info(" configuration.IGNORE_THRESHOLD = " + configuration.IGNORE_THRESHOLD.__str__())
if "DO_IGNORE_SOME" in config["myConfig"]:
configuration.DO_IGNORE_SOME = config.getboolean('myConfig','DO_IGNORE_SOME')
logging.info(" configuration.DO_IGNORE_SOME = " + configuration.DO_IGNORE_SOME.__str__())
if "DO_DECEPTION" in config["myConfig"]:
configuration.DO_DECEPTION = config.getboolean('myConfig','DO_DECEPTION')
logging.info(" configuration.DO_DECEPTION = " + configuration.DO_DECEPTION.__str__())
if "BSF_MIN_ATTENUATION_DB" in config["myConfig"]:
configuration.BSF_MIN_ATTENUATION_DB = int(config['myConfig']['BSF_MIN_ATTENUATION_DB'])
logging.info(" configuration.BSF_MIN_ATTENUATION_DB = " + configuration.BSF_MIN_ATTENUATION_DB.__str__())
if "SKIP_CODING_IF_MIN_EXCEEDED_DEFAULT" in config["myConfig"]:
configuration.SKIP_CODING_IF_MIN_EXCEEDED_DEFAULT = float(config['myConfig']['SKIP_CODING_IF_MIN_EXCEEDED_DEFAULT'])
logging.info(" configuration.SKIP_CODING_IF_MIN_EXCEEDED_DEFAULT = " + configuration.SKIP_CODING_IF_MIN_EXCEEDED_DEFAULT.__str__())
if "SKIP_CODING_IF_MAX_EXCEEDED_DEFAULT" in config["myConfig"]:
configuration.SKIP_CODING_IF_MAX_EXCEEDED_DEFAULT = float(config['myConfig']['SKIP_CODING_IF_MAX_EXCEEDED_DEFAULT'])
logging.info(" configuration.SKIP_CODING_IF_MAX_EXCEEDED_DEFAULT = " + configuration.SKIP_CODING_IF_MAX_EXCEEDED_DEFAULT.__str__())
if "INTERLEAVED_CHUNKS" in config["myConfig"]:
configuration.INTERLEAVED_CHUNKS = int(config['myConfig']['INTERLEAVED_CHUNKS'])
logging.info(" configuration.INTERLEAVED_CHUNKS = " + configuration.INTERLEAVED_CHUNKS.__str__())
if "INTERLEAVED_FC" in config["myConfig"]:
configuration.INTERLEAVED_FC = int(config['myConfig']['INTERLEAVED_FC'])
logging.info(" configuration.INTERLEAVED_FC = " + configuration.INTERLEAVED_FC.__str__())
if "SAMPLING_FREQUENCY" in config["myConfig"]:
configuration.SAMPLING_FREQUENCY = int(config['myConfig']['SAMPLING_FREQUENCY'])
logging.info(" configuration.SAMPLING_FREQUENCY = " + configuration.SAMPLING_FREQUENCY.__str__())
if "NORMALIZE_SETTINGS" in config["myConfig"]:
configuration.NORMALIZE_SETTINGS = config.getboolean('myConfig', 'NORMALIZE_SETTINGS')
logging.info(" configuration.NORMALIZE_SETTINGS = " + configuration.NORMALIZE_SETTINGS.__str__())
if "MAX_NR_OF_ITERATIONS" in config["myConfig"]:
configuration.MAX_NR_OF_ITERATIONS = int(config['myConfig']['MAX_NR_OF_ITERATIONS'])
logging.info(" configuration.MAX_NR_OF_ITERATIONS = " + configuration.MAX_NR_OF_ITERATIONS.__str__())
if "myAdvancedConfig" in config:
logging.info(" Keys in section myAdvancedConfig:")
if "CODE_FREQUENCY_START_BIN" in config["myAdvancedConfig"]:
configuration.CODE_FREQUENCY_START_BIN = int(config['myAdvancedConfig']['CODE_FREQUENCY_START_BIN'])
logging.info(" configuration.CODE_FREQUENCY_START_BIN = " + configuration.CODE_FREQUENCY_START_BIN.__str__())
if "CODE_FREQUENCY_END_BIN" in config["myAdvancedConfig"]:
configuration.CODE_FREQUENCY_END_BIN = int(config['myAdvancedConfig']['CODE_FREQUENCY_END_BIN'])
logging.info(" configuration.CODE_FREQUENCY_END_BIN = " + configuration.CODE_FREQUENCY_END_BIN.__str__())
if "CHECK_IMAG_TOO" in config["myAdvancedConfig"]:
configuration.CHECK_IMAG_TOO = config.getboolean('myAdvancedConfig', 'CHECK_IMAG_TOO')
logging.info(" configuration.CHECK_IMAG_TOO = " + configuration.CHECK_IMAG_TOO.__str__())
if "KEEP_TEMP_FILES" in config["myAdvancedConfig"]:
configuration.KEEP_TEMP_FILES = config.getboolean('myAdvancedConfig', 'KEEP_TEMP_FILES')
logging.info(" configuration.KEEP_TEMP_FILES = " + configuration.KEEP_TEMP_FILES.__str__())
if "BITRATE" in config["myAdvancedConfig"]:
configuration.BITRATE = int(config['myAdvancedConfig']['BITRATE'])
logging.info(" configuration.BITRATE = " + configuration.BITRATE.__str__())
if "INTERPOLATE_AND_DUMMY_CODE_ALL" in config["myAdvancedConfig"]:
configuration.INTERPOLATE_AND_DUMMY_CODE_ALL = config.getboolean('myAdvancedConfig', 'INTERPOLATE_AND_DUMMY_CODE_ALL')
logging.info(" configuration.INTERPOLATE_AND_DUMMY_CODE_ALL = " + configuration.INTERPOLATE_AND_DUMMY_CODE_ALL.__str__())
if "AVG_INTERPOLATION" in config["myAdvancedConfig"]:
configuration.AVG_INTERPOLATION = config.getboolean('myAdvancedConfig', 'AVG_INTERPOLATION')
logging.info(" configuration.AVG_INTERPOLATION = " + configuration.AVG_INTERPOLATION.__str__())
if "INTERPOLATE_WITH_MEAN" in config["myAdvancedConfig"]:
configuration.INTERPOLATE_WITH_MEAN = config.getboolean('myAdvancedConfig', 'INTERPOLATE_WITH_MEAN')
logging.info(" configuration.INTERPOLATE_WITH_MEAN = " + configuration.INTERPOLATE_WITH_MEAN.__str__())
if "CODE_WITH_MAGNITUDE" in config["myAdvancedConfig"]:
configuration.CODE_WITH_MAGNITUDE = config.getboolean('myAdvancedConfig', 'CODE_WITH_MAGNITUDE')
logging.info(" configuration.CODE_WITH_MAGNITUDE = " + configuration.CODE_WITH_MAGNITUDE.__str__())
if "RECODE_FACTOR_PLUS" in config["myAdvancedConfig"]:
configuration.RECODE_FACTOR_PLUS = float(config['myAdvancedConfig']['RECODE_FACTOR_PLUS'])
logging.info(" configuration.RECODE_FACTOR_PLUS = " + configuration.RECODE_FACTOR_PLUS.__str__())
if "CODE_FACTOR_PERCENT" in config["myAdvancedConfig"]:
configuration.CODE_FACTOR_PERCENT = float(config['myAdvancedConfig']['CODE_FACTOR_PERCENT'])
logging.info(" configuration.CODE_FACTOR_PERCENT = " + configuration.CODE_FACTOR_PERCENT.__str__())
if "CODE_FACTOR_PERCENT_DETECTION_THRESHOLD" in config["myAdvancedConfig"]:
configuration.CODE_FACTOR_PERCENT_DETECTION_THRESHOLD = float(config['myAdvancedConfig']['CODE_FACTOR_PERCENT_DETECTION_THRESHOLD'])
logging.info(" configuration.CODE_FACTOR_PERCENT_DETECTION_THRESHOLD = " + configuration.CODE_FACTOR_PERCENT_DETECTION_THRESHOLD.__str__())
if "FFMPEG_VERSION" in config["myAdvancedConfig"]:
configuration.FFMPEG_VERSION = str(config['myAdvancedConfig']['FFMPEG_VERSION'])
logging.info(" configuration.FFMPEG_VERSION = " + configuration.FFMPEG_VERSION.__str__())
except (configparser.NoSectionError, configparser.MissingSectionHeaderError):
logging.info("Error: Exception raised in AS4PGC.py trying to load config file!")
logging.info(" Default values will be used.\n")
pass
except Exception:
traceback.print_exc()
exit(cf.f_lineno)
else:
logging.info("No config.ini found. Default values will be used.")
# plausibility checks
#####################
if configuration.CODE_FREQUENCY_END_BIN <= configuration.CODE_FREQUENCY_START_BIN:
logging.error("Error: CODE_FREQUENCY_END_BIN <= CODE_FREQUENCY_START_BIN")
exit(cf.f_lineno)
# ffmpeg version
################
FFMPEG_VERSION = configuration.FFMPEG_VERSION
command = "ffmpeg -version"
p1 = subprocess.Popen(shlex.split(command), shell=False, stdout=subprocess.PIPE)
out, err = p1.communicate()
if p1.returncode == 0:
ffmpeg_ver_idx_start = out.__str__().find("ffmpeg version")
if ffmpeg_ver_idx_start >= 0:
ffmpeg_ver_idx_start = ffmpeg_ver_idx_start + len("ffmpeg version") + 1
ffmpeg_ver_idx_end = ffmpeg_ver_idx_start + out.__str__()[ffmpeg_ver_idx_start:].find(" ")
FFMPEG_VERSION = out.__str__()[ffmpeg_ver_idx_start:ffmpeg_ver_idx_end]
# FFMPEG_VERSION ok?
####################
if configuration.FFMPEG_VERSION != FFMPEG_VERSION:
logging.warning("Warning: configuration.FFMPEG_VERSION = " + str(configuration.FFMPEG_VERSION))
logging.warning(" But the current ffmpeg has version = "+FFMPEG_VERSION)
logging.warning(" Remember you need to use the same codec when extracting the hidden message!")
configuration.FFMPEG_VERSION = FFMPEG_VERSION
if os.path.isfile(config_filename):
input1 = input("{} (y/n): ".format("Shall FFMPEG_VERSION be set to " + configuration.FFMPEG_VERSION + " in config.ini?", "n"))
if "y" == input1.lower() or "yes" == input1.lower():
# update FFMPEG_VERSION in config.ini
#####################################
config['myAdvancedConfig']['FFMPEG_VERSION'] = str(configuration.FFMPEG_VERSION)
with open(config_filename, 'w') as configfile:
config.write(configfile)
logging.warning("Updated FFMPEG_VERSION in config.ini")
else:
logging.warning(" Consider using option -d")
else:
logging.error("Error: could not get ffmpeg version!")
exit(cf.f_lineno)
p1.terminate()
p1.kill()
logging.info("FFMPEG_VERSION = "+FFMPEG_VERSION+"(used only for plausibility check)")
# ffmpeg formats
################
FFMPEG_FORMATS = " wav , mp3 , ogg , flac "
# TODO: find out why we see the output of the ffmpeg -version command and hide it..
'''
command = "ffmpeg -formats"
p1 = subprocess.Popen(shlex.split(command), shell=False, stdout=subprocess.PIPE)
out, err = p1.communicate()
FFMPEG_FORMATS = str(out)
if p1.returncode != 0:
logging.error("Error: could not get ffmpeg formats!")
exit(cf.f_lineno)
p1.terminate()
p1.kill()
logging.info("FFMPEG_FORMATS = "+FFMPEG_FORMATS)
# '''
# mess-up config?
# NOTE: if no pwd is provided but -m was passed
# then we use empty pwd as password.
###############################################
MESS_UP_CONFIG = args.messupconfig
logging.info("MESS_UP_CONFIG = " + str(MESS_UP_CONFIG))
# password
# used for:
# encryption of the message file (if option -n NOT provided)
# setting random seeds (if not empty)
# encryption of the header
# messing-up configuration (if option -m provided)
##################################################################
try_count = 3
while (True):
PASSWORD = getpass("pwd: ")
if WRITE:
# Note: consider https://github.com/microsoft/ptvsd/issues/1723
# The following warning is displayed while debugging, but it's ok:
# Warning: Password input may be echoed.
pwd_conf = getpass("confirm pwd: ")
else:
pwd_conf = PASSWORD
if PASSWORD == pwd_conf:
# Note: if we use a random number here we must make sure that it is equal when reading,
# this is not posssible with urandom() so we hardcode it
##############################################################
salt = bytes(b'salt') # os.urandom(16)
kdf = PBKDF2HMAC(algorithm = hashes.SHA256(),length = 32,salt = salt,iterations = 100000,)
KEY_FROM_PASSWORD = base64.urlsafe_b64encode(kdf.derive(bytearray(PASSWORD,"utf-8")))
fernet = Fernet(KEY_FROM_PASSWORD)
# derive new seeds from key
# use first and second part of key to generate 2 different integers
# NOTE: with this, correct decoding does NOT only depend on config.ini but also on password
###########################################################################################
if PASSWORD != "":
configuration.SEED_IGNORE = int.from_bytes(KEY_FROM_PASSWORD[:len(KEY_FROM_PASSWORD)//2], byteorder='little', signed=False)
configuration.SEED_IGNORE_CODE_DECEPTION = int.from_bytes(KEY_FROM_PASSWORD[len(KEY_FROM_PASSWORD)//2:], byteorder='little', signed=False)
logging.info("configuration.SEED_IGNORE derived from password = " + str(configuration.SEED_IGNORE))
logging.info("configuration.SEED_IGNORE_CODE_DECEPTION derived from password = " + str(configuration.SEED_IGNORE_CODE_DECEPTION))
elif MESS_UP_CONFIG == False:
# Note: no password and no argument -m provided
# the unmodified seeds may be the hardcoded-default-values or may come from config.ini
# We still have some randomness derived from deception[] and ignore[] which will generate different compressed audio files
# in each iteration, resulting in small variations during normalization/scaling of the audio signal.
logging.warning("Warning: no pwd provided, unmodified seeds will be used.")
# this seed is always derived from password
configuration.SEED_F_SHUFFLE = int.from_bytes(KEY_FROM_PASSWORD[len(KEY_FROM_PASSWORD) // 2:len(KEY_FROM_PASSWORD) // 2 + len(KEY_FROM_PASSWORD) // 4], byteorder='little',signed=False)
logging.info("configuration.SEED_F_SHUFFLE derived from password = " + str(configuration.SEED_F_SHUFFLE))
if WRITE == True:
print("You'll need this password to recover the embedded message, keep it safe!")
break
else:
try_count = try_count - 1
if try_count == 0:
logging.error("Error: incorrect password confirmation. Max. nr. of retries exceeded.")
exit(cf.f_lineno)
else:
logging.error("Error: incorrect password confirmation, try again.")
# mess up configuration
#######################
if MESS_UP_CONFIG == True:
idx_key = 0
len_key = len(KEY_FROM_PASSWORD)
logging.info("Start messing up with configuration based on password..")
configuration.CHUNK_LEN_SAMPLES = configuration.CHUNK_LEN_SAMPLES + int(KEY_FROM_PASSWORD[idx_key])
logging.info("Messed configuration.CHUNK_LEN_SAMPLES = "+str(configuration.CHUNK_LEN_SAMPLES))
##### MAX_VOLUME
idx_key = (idx_key + 1)%len_key
configuration.SEED_IGNORE = int.from_bytes(KEY_FROM_PASSWORD[:len(KEY_FROM_PASSWORD) // 2], byteorder='little',signed=False)
logging.info("Messed up configuration.SEED_IGNORE = " + str(configuration.SEED_IGNORE))
configuration.SEED_IGNORE_CODE_DECEPTION = int.from_bytes(KEY_FROM_PASSWORD[len(KEY_FROM_PASSWORD) // 2:],byteorder='little', signed=False)
logging.info("Messed up configuration.SEED_IGNORE_CODE_DECEPTION = " + str(configuration.SEED_IGNORE_CODE_DECEPTION))
configuration.SEED_THRESHOLD = int(KEY_FROM_PASSWORD[idx_key])
logging.info("Messed up configuration.SEED_THRESHOLD = " + str(configuration.SEED_THRESHOLD))
idx_key = (idx_key + 1) % len_key
configuration.IGNORE_THRESHOLD = 0.99 + (float(KEY_FROM_PASSWORD[idx_key])/255.0)/100.0
logging.info("Messed up configuration.IGNORE_THRESHOLD = " + str(configuration.IGNORE_THRESHOLD))
idx_key = (idx_key + 1) % len_key
##### DO_IGNORE_SOME: bool
##### DO_DECEPTION: bool
##### BSF_MIN_ATTENUATION_DB: int
##### SKIP_CODING_IF_MIN_EXCEEDED_DEFAULT: float
##### SKIP_CODING_IF_MAX_EXCEEDED_DEFAULT: float
##### INTERLEAVED_CHUNKS: int
##### INTERLEAVED_FC: int
##### SAMPLING_FREQUENCY: int
##### NORMALIZE_SETTINGS: bool
##### MAX_NR_OF_ITERATIONS: int
#CODE_FREQUENCY_START_BIN: int
random.seed(int(KEY_FROM_PASSWORD[idx_key]))
diff_bins = configuration.CODE_FREQUENCY_END_BIN - configuration.CODE_FREQUENCY_START_BIN
configuration.CODE_FREQUENCY_START_BIN = configuration.CODE_FREQUENCY_START_BIN + random.randint(-configuration.CODE_FREQUENCY_START_BIN//20, configuration.CODE_FREQUENCY_START_BIN//10)
logging.info("Messed up configuration.CODE_FREQUENCY_START_BIN = " + str(configuration.CODE_FREQUENCY_START_BIN))
idx_key = (idx_key + 1) % len_key
random.seed(int(KEY_FROM_PASSWORD[idx_key]))
configuration.CODE_FREQUENCY_END_BIN = configuration.CODE_FREQUENCY_START_BIN + diff_bins + random.randint(-diff_bins//10, diff_bins//5)
logging.info("Messed up configuration.CODE_FREQUENCY_END_BIN = " + str(configuration.CODE_FREQUENCY_END_BIN))
idx_key = (idx_key + 1) % len_key
#### CHECK_IMAG_TOO: bool
#### KEEP_TEMP_FILES: bool
#### BITRATE: int
#### INTERPOLATE_AND_DUMMY_CODE_ALL: bool
#### AVG_INTERPOLATION: bool #### good candidate to mess-up
#### INTERPOLATE_WITH_MEAN: bool #### good candidate to mess-up
#### CODE_WITH_MAGNITUDE: bool ## could mess-up this as well
#### RECODE_FACTOR_PLUS: float
#### CODE_FACTOR_PERCENT: float
#### CODE_FACTOR_PERCENT_DETECTION_THRESHOLD: float
#### FFMPEG_VERSION: str
logging.info("Finished messing up with configuration based on password..")
# config_filename does not exist
################################
if not os.path.isfile(config_filename):
config.add_section('myConfig')
config.add_section('myAdvancedConfig')
# basic configuration:
######################
config['myConfig']['CHUNK_LEN_SAMPLES'] = str(configuration.CHUNK_LEN_SAMPLES)
config['myConfig']['MAX_VOLUME'] = str(configuration.MAX_VOLUME)
config['myConfig']['SEED_IGNORE'] = str(configuration.SEED_IGNORE)
config['myConfig']['SEED_IGNORE_CODE_DECEPTION'] = str(configuration.SEED_IGNORE_CODE_DECEPTION)
config['myConfig']['SEED_THRESHOLD'] = str(configuration.SEED_THRESHOLD)
config['myConfig']['IGNORE_THRESHOLD'] = str(configuration.IGNORE_THRESHOLD)
config['myConfig']['DO_IGNORE_SOME'] = str(configuration.DO_IGNORE_SOME)
config['myConfig']['DO_DECEPTION'] = str(configuration.DO_DECEPTION)
config['myConfig']['BSF_MIN_ATTENUATION_DB'] = str(configuration.BSF_MIN_ATTENUATION_DB)
config['myConfig']['SKIP_CODING_IF_MIN_EXCEEDED_DEFAULT'] = str(configuration.SKIP_CODING_IF_MIN_EXCEEDED_DEFAULT)
config['myConfig']['SKIP_CODING_IF_MAX_EXCEEDED_DEFAULT'] = str(configuration.SKIP_CODING_IF_MAX_EXCEEDED_DEFAULT)
config['myConfig']['INTERLEAVED_CHUNKS'] = str(configuration.INTERLEAVED_CHUNKS)
config['myConfig']['INTERLEAVED_FC'] = str(configuration.INTERLEAVED_FC)
config['myConfig']['SAMPLING_FREQUENCY'] = str(configuration.SAMPLING_FREQUENCY)
config['myConfig']['NORMALIZE_SETTINGS'] = str(configuration.NORMALIZE_SETTINGS)
config['myConfig']['MAX_NR_OF_ITERATIONS'] = str(configuration.MAX_NR_OF_ITERATIONS)
# advanced configuration:
#########################
config['myAdvancedConfig']['CODE_FREQUENCY_START_BIN'] = str(configuration.CODE_FREQUENCY_START_BIN)
config['myAdvancedConfig']['CODE_FREQUENCY_END_BIN'] = str(configuration.CODE_FREQUENCY_END_BIN)
config['myAdvancedConfig']['CHECK_IMAG_TOO'] = str(configuration.CHECK_IMAG_TOO)
config['myAdvancedConfig']['KEEP_TEMP_FILES'] = str(configuration.KEEP_TEMP_FILES)
config['myAdvancedConfig']['BITRATE'] = str(configuration.BITRATE)
config['myAdvancedConfig']['INTERPOLATE_AND_DUMMY_CODE_ALL'] = str(configuration.INTERPOLATE_AND_DUMMY_CODE_ALL)
config['myAdvancedConfig']['AVG_INTERPOLATION'] = str(configuration.AVG_INTERPOLATION)
config['myAdvancedConfig']['INTERPOLATE_WITH_MEAN'] = str(configuration.INTERPOLATE_WITH_MEAN)
config['myAdvancedConfig']['CODE_WITH_MAGNITUDE'] = str(configuration.CODE_WITH_MAGNITUDE)
config['myAdvancedConfig']['RECODE_FACTOR_PLUS'] = str(configuration.RECODE_FACTOR_PLUS)
config['myAdvancedConfig']['CODE_FACTOR_PERCENT'] = str(configuration.CODE_FACTOR_PERCENT)
config['myAdvancedConfig']['CODE_FACTOR_PERCENT_DETECTION_THRESHOLD'] = str(configuration.CODE_FACTOR_PERCENT_DETECTION_THRESHOLD)
config['myAdvancedConfig']['FFMPEG_VERSION'] = str(configuration.FFMPEG_VERSION)
# created default config.ini? then exit..
#########################################
if args.defaultconfig == True:
# create default config file
with open(config_filename, 'w') as configfile:
# write new settings into file
config.write(configfile)
print("Created default config.ini")
exit(cf.f_lineno)
else:
logging.info("No config.ini, we use default values.")
# TODO: uncomment next code-block to always force creation...
# for now we dont want to have this file if not really required, this shall keep things simpler.
'''
# create default config file
with open(config_filename, 'w') as configfile:
# write new settings into file
config.write(configfile)
print("Created default config.ini")
# '''
# check if files exist
######################
if WRITE == True:
if not os.path.isfile(message_file):
logging.error("Error: message file " + message_file + " not found!")
exit(cf.f_lineno)
if not os.path.isfile(carrier_file):
logging.error("Error: carrier file " + carrier_file + " not found!")
exit(cf.f_lineno)
else:
if not os.path.isfile(stego_file):
logging.error("Error: stego file " + stego_file + " not found!")
exit(cf.f_lineno)
NORMALIZE_SETTINGS = configuration.NORMALIZE_SETTINGS
logging.info("NORMALIZE_SETTINGS = " + str(NORMALIZE_SETTINGS))
CHECK_IMAG_TOO = configuration.CHECK_IMAG_TOO
logging.info("CHECK_IMAG_TOO = " + str(CHECK_IMAG_TOO))
FILE_NAME_HDR = ""
FILE_TYPE = "no_file_type_specified" # includes the point!
if WRITE:
FILE_TYPE = str.lower(carrier_file[carrier_file.rfind("."):])
else:
FILE_TYPE = str.lower(stego_file[stego_file.rfind("."):])
if " "+FILE_TYPE[1:]+" " not in FFMPEG_FORMATS: # if FILE_TYPE != ".mp3" and FILE_TYPE != ".flac":
print("Error: carrier file type not supported. ffmpeg -formats:")
print(FFMPEG_FORMATS)
exit(cf.f_lineno)
else:
# TODO: extend list according to tests..
if FILE_TYPE[1:] != "mp3" and FILE_TYPE[1:] != "ogg" and FILE_TYPE[1:] != "flac" and FILE_TYPE[1:] != "wav":
print("Warning: file type " + FILE_TYPE[1:] + " not yet tested!")
if WRITE:
CARRIER_FILE_NAME = carrier_file
logging.info("CARRIER_FILE_NAME = " + CARRIER_FILE_NAME)
# Note: output directory of carrier also used as temp dir
index_of_last_slash = CARRIER_FILE_NAME.rfind('/')
OUT_DIR_NAME = CARRIER_FILE_NAME[:index_of_last_slash+1] # +1 to include the slash
logging.info("OUT_DIR_NAME (also used as directory for temporary files) = " + OUT_DIR_NAME)
MESSAGE_FILE_NAME = message_file
logging.info("MESSAGE_FILE_NAME = " + MESSAGE_FILE_NAME)
if not isinstance(args.output_file, type(None)):
OUT_FILE_NAME = args.output_file
else:
OUT_FILE_NAME = OUT_DIR_NAME + "stego" + FILE_TYPE
logging.info("OUT_FILE_NAME = " + OUT_FILE_NAME)
# COMPRESSION may be set to True later if it really brings a reduction in msg length
COMPRESSION = False
# NOTE: if no pwd is provided and option -n was NOT used
# then we use the empty pwd as password.
########################################################
if not isinstance(args.no_encryption, type(None)):
ENCRYPTION = not args.no_encryption
else:
ENCRYPTION = True
logging.info("ENCRYPTION = " + str(ENCRYPTION))
index_of_last_slash = CARRIER_FILE_NAME.rfind('/')
index_of_last_point = CARRIER_FILE_NAME.rfind('.')
FILE_NAME = OUT_DIR_NAME + CARRIER_FILE_NAME[index_of_last_slash+1:index_of_last_point]
# Note: dont use any path...the path will be given when reading,
# then we use the same path as the path of the input file.
################################################################
index_of_last_slash = MESSAGE_FILE_NAME.rfind('/')
FILE_NAME_HDR = MESSAGE_FILE_NAME[index_of_last_slash + 1:]
if len(FILE_NAME_HDR) > MAX_LEN_MSG_FILE_NAME:
logging.error("Error: max. length of message file name = "+str(MAX_LEN_MSG_FILE_NAME))
exit(cf.f_lineno)
index_of_last_point = OUT_FILE_NAME.rfind('.')
index_of_last_point2 = MESSAGE_FILE_NAME.rfind('.')
OUT_MESSAGE_FILE_NAME = OUT_FILE_NAME[:index_of_last_point] + MESSAGE_FILE_NAME[index_of_last_point2:]
else:
# Note: directory of stego file also used as output dir for extracting message file
index_of_last_slash = stego_file.rfind('/')
OUT_DIR_NAME = stego_file[:index_of_last_slash+1] # +1 to include the slash
if not isinstance(args.output_file, type(None)):
if len(args.output_file) <= MAX_LEN_MSG_FILE_NAME:
if "/" not in args.output_file:
FILE_NAME_HDR = args.output_file
else:
logging.error("Error: file name shall not contain path.")
exit(cf.f_lineno)
else:
logging.error("Error: max. length of file name = 36.")
exit(cf.f_lineno)
MAX_NR_OF_ITERATIONS = configuration.MAX_NR_OF_ITERATIONS
logging.info("MAX_NR_OF_ITERATIONS = " + str(MAX_NR_OF_ITERATIONS))
#############
# NOTE: SCALING audio signal to MAX_VOLUME may be used before "normalizing" signals in order to always use similar
# configuration settings. High values of MAX_VOLUME are especially useful in signals with low level,
# which otherwise hide less bits.
# WARNING: scaling, as well as other signal manipulations such as adding noise, a tone, or saturation will affect
# the result irreversibly. Note: adding noise reduces correlation between chunks, this is not good.
# *** DO NOT SCALE if you intend to UNSCALE after coding...that will destroy coding ***
################################################################################################
SCALE_INPUT = True
logging.info("SCALE_INPUT = " + str(SCALE_INPUT))
###############################################
# TODO: if adding noise is useful (e.g. to hide coding) then create corresponding configuration parameters (type, level,..).
# Investigate if e.g. it is necessary to filter noise before addition.
# Note: adding noise is irreversible, and it may affect correlations between consecutive chunks which reduces coding capacity.
# when NOISE_LEVEL = 0.001, noise max value is 1000 times smaller than max. (with max 32768 we code up to 32 approx, which is 5 bits)
# when NOISE_LEVEL = 0.0001, noise max value is 10000 times smaller than max. (with max 32768 we code up to 3.2 approx, which is 2 bits)
# NOISE_LEVEL = 0.0 means noise is NOT added
LEVEL_ADDED_NOISE = 0.0 # 0.01 # 0.001 # 0.0001
###############################################
KEEP_TEMP_FILES = configuration.KEEP_TEMP_FILES
PLAY_ON = args.sound
DO_PLOT = args.plot
HIDE = args.hide
PLOT_SIG = True and DO_PLOT
PLOT_FFT = True and DO_PLOT
PLOT_CDF = True and DO_PLOT
PLOT_ERR = True and DO_PLOT
PLOT_3D = False and DO_PLOT # just a test, but it seems to be extremely slow!
PLOT_BIT_ERR_IN_ITERATIONS = True and DO_PLOT
# Note: no matter which sampling rate the input file has, we force the output to SAMPLING_FREQUENCY.
SAMPLING_FREQUENCY = configuration.SAMPLING_FREQUENCY
T = 1.0 / SAMPLING_FREQUENCY
NYQUIST_FREQUENCY = (SAMPLING_FREQUENCY/2.0)
NUM_CHANNELS = 1
BYTES_PER_SAMPLE = 2
BITS_PER_SAMPLE = 8*BYTES_PER_SAMPLE
MAX_AMPLITUDE = 2**(BITS_PER_SAMPLE-1)
BITRATE = configuration.BITRATE
BITRATE_STR = str(BITRATE)
# 32-bit floating reduces digitizing errors but is probably not supported by other tools
# flt not supported by .flac
SAMPLE_FORMAT = "s16" # "flt" # "s16" # "dbl"
WAV_SAMPLE_FORMAT = "pcm_f32le" # "pcm_s16le"
CHUNK_LEN_SAMPLES = configuration.CHUNK_LEN_SAMPLES
# Note: MAX_VOLUME is applied when SCALE_INPUT = True (see comments there)
# MAX_VOLUME shall probably not exceed 0.9 so there is still room for tolerances, coding, etc.
MAX_VOLUME = configuration.MAX_VOLUME
if MAX_VOLUME > 1.0:
print("Error: MAX_VOLUME > 1.0")
exit(cf.f_lineno)
# Note: INTERLEAVED_CHUNKS, required for chunk-interpolation, may also help "spreading" the message across
# the carrier (in time domain) in order to keep statistics and be robust against steganalysis.
INTERLEAVED_CHUNKS = configuration.INTERLEAVED_CHUNKS
if INTERLEAVED_CHUNKS < 2:
print("Error: INTERLEAVED_CHUNKS < 2")
exit(cf.f_lineno)
# Note: INTERLEAVED_FC, sometimes needed to separate coded frequencies and avoid interferences, may also help
# "spreading" the message across the carrier (in frequency domain) in order to keep
# statistics and be robust against steganalysis.
INTERLEAVED_FC = configuration.INTERLEAVED_FC
if INTERLEAVED_FC < 1:
print("Error: INTERLEAVED_FC < 1")
exit(cf.f_lineno)
# Note: on use of INTERPOLATE_AND_DUMMY_CODE_ALL
# if all chunks are interpolated, the statistics will be more regular and therefore more difficult to detect with
# steganalysis. If only the part of the message is interpolated, then we reduce noise noticeably and
# may even shorten iterations, but then we affect audio statistics.
INTERPOLATE_AND_DUMMY_CODE_ALL = configuration.INTERPOLATE_AND_DUMMY_CODE_ALL
logging.info("SAMPLING_FREQUENCY = " + str(SAMPLING_FREQUENCY))
logging.info("BITRATE_STR = " + BITRATE_STR)
logging.info("CHUNK_LEN_SAMPLES = " + str(CHUNK_LEN_SAMPLES))
logging.info("MAX_VOLUME = " + str(MAX_VOLUME))
logging.info("INTERLEAVED_CHUNKS = " + str(INTERLEAVED_CHUNKS))
logging.info("INTERLEAVED_FC = " + str(INTERLEAVED_FC))
logging.info("INTERPOLATE_AND_DUMMY_CODE_ALL = " + str(INTERPOLATE_AND_DUMMY_CODE_ALL))
AVG_INTERPOLATION = configuration.AVG_INTERPOLATION
logging.info("AVG_INTERPOLATION = " + str(AVG_INTERPOLATION))
INTERPOLATE_WITH_MEAN = configuration.INTERPOLATE_WITH_MEAN
logging.info("INTERPOLATE_WITH_MEAN = " + str(INTERPOLATE_WITH_MEAN))
###################################################
DO_IGNORE_SOME = configuration.DO_IGNORE_SOME
DO_DECEPTION = configuration.DO_DECEPTION
SEED_IGNORE = configuration.SEED_IGNORE
# SEED_IGNORE_CODE_DECEPTION also used to init dummy bits for padding after message (for cases with no encryption).
SEED_IGNORE_CODE_DECEPTION = configuration.SEED_IGNORE_CODE_DECEPTION
SEED_F_SHUFFLE = configuration.SEED_F_SHUFFLE
# IGNORE_THRESHOLD -> = 0.99 will result in approx. 1% of bits being NOT coded in order to confuse attacker.
IGNORE_THRESHOLD = configuration.IGNORE_THRESHOLD
SEED_THRESHOLD = configuration.SEED_THRESHOLD
logging.info("DO_IGNORE_SOME = " + str(DO_IGNORE_SOME))
logging.info("DO_DECEPTION = " + str(DO_DECEPTION))
logging.info("SEED_IGNORE = " + str(SEED_IGNORE))
logging.info("SEED_IGNORE_CODE_DECEPTION = " + str(SEED_IGNORE_CODE_DECEPTION))
logging.info("IGNORE_THRESHOLD = " + str(IGNORE_THRESHOLD))
logging.info("SEED_THRESHOLD = " + str(SEED_THRESHOLD))
##################################################
SKIP_CODING_IF_MIN_EXCEEDED_DEFAULT = configuration.SKIP_CODING_IF_MIN_EXCEEDED_DEFAULT
SKIP_CODING_IF_MAX_EXCEEDED_DEFAULT = configuration.SKIP_CODING_IF_MAX_EXCEEDED_DEFAULT
logging.info("SKIP_CODING_IF_MIN_EXCEEDED_DEFAULT = " + str(SKIP_CODING_IF_MIN_EXCEEDED_DEFAULT))
logging.info("SKIP_CODING_IF_MAX_EXCEEDED_DEFAULT = " + str(SKIP_CODING_IF_MAX_EXCEEDED_DEFAULT))
###################################################
# Note: if CODE_WITH_MAGNITUDE = False, then we code only with .real values
CODE_WITH_MAGNITUDE = configuration.CODE_WITH_MAGNITUDE
logging.info("CODE_WITH_MAGNITUDE = " + str(CODE_WITH_MAGNITUDE))
FFT_BIN_WIDTH_HZ = int(NYQUIST_FREQUENCY/(CHUNK_LEN_SAMPLES/2))
logging.info("FFT_BIN_WIDTH_HZ = "+str(FFT_BIN_WIDTH_HZ))
NR_OF_FFT_BINS = int(NYQUIST_FREQUENCY/FFT_BIN_WIDTH_HZ)
logging.info("NR_OF_FFT_BINS = "+str(NR_OF_FFT_BINS)+" (0->"+str(FFT_BIN_WIDTH_HZ)+"Hz, "+str(FFT_BIN_WIDTH_HZ)+"->"+str(FFT_BIN_WIDTH_HZ*2)+"Hz,...)")
###################################################
FREQUENCY = np.zeros(NR_OF_FFT_BINS)
for f in range(len(FREQUENCY)):
FREQUENCY[f] = FFT_BIN_WIDTH_HZ*f
logging.info("FREQUENCY["+str(f)+"] = "+str(FREQUENCY[f]))
CODE_FREQUENCY = np.zeros(NR_OF_FFT_BINS)
CODE_FREQUENCY_BIN = np.zeros(NR_OF_FFT_BINS, dtype=int)
for i in range(len(CODE_FREQUENCY)):
CODE_FREQUENCY[i] = FFT_BIN_WIDTH_HZ*i
CODE_FREQUENCY_BIN[i] = int(CODE_FREQUENCY[i]/FFT_BIN_WIDTH_HZ)
logging.info("CODE_FREQUENCY["+str(i)+"] = "+str(CODE_FREQUENCY[i]))
logging.info("CODE_FREQUENCY_BIN[" + str(i) + "] = " + str(CODE_FREQUENCY_BIN[i]))
###################################################
# Note:
# coding between 12kHz and 20kHz seems to work fine when output 320k
# Below 12kHz we get too much hearable noise, above 20kHz signal is too weak.
##################################################################################
if configuration.CODE_FREQUENCY_START_BIN < NR_OF_FFT_BINS:
CODE_FREQUENCY_START_BIN = configuration.CODE_FREQUENCY_START_BIN
else:
CODE_FREQUENCY_START_BIN = NR_OF_FFT_BINS//2
if configuration.CODE_FREQUENCY_END_BIN <= NR_OF_FFT_BINS:
CODE_FREQUENCY_END_BIN = configuration.CODE_FREQUENCY_END_BIN
else:
CODE_FREQUENCY_END_BIN = NR_OF_FFT_BINS-1
CODE_FREQUENCY_START = CODE_FREQUENCY[CODE_FREQUENCY_START_BIN]
CODE_FREQUENCY_END = CODE_FREQUENCY[CODE_FREQUENCY_END_BIN]
NR_OF_CODE_FREQUENCIES = (CODE_FREQUENCY_END_BIN - CODE_FREQUENCY_START_BIN) + 1
logging.info("CODE_FREQUENCY_START = " + str(CODE_FREQUENCY_START))
logging.info("CODE_FREQUENCY_START_BIN = " + str(CODE_FREQUENCY_START_BIN))
logging.info("CODE_FREQUENCY_END = " + str(CODE_FREQUENCY_END))
logging.info("CODE_FREQUENCY_END_BIN = " + str(CODE_FREQUENCY_END_BIN))
logging.info("NR_OF_CODE_FREQUENCIES = " + str(NR_OF_CODE_FREQUENCIES))
###################################################
# Example for coding ABOVE interpolated reference:
##################################################
#
# code (is approx. CODE_FACTOR_PERCENT % above interpolation-ref.)
# (o)
# \
# } ABS(code - interp) % shall be approx. CODE_FACTOR_PERCENT %
# /
# (*) interp
#
RECODE_FACTOR_PLUS = configuration.RECODE_FACTOR_PLUS
RECODE_FACTOR_MINUS = RECODE_FACTOR_PLUS
CODE_FACTOR_PERCENT = configuration.CODE_FACTOR_PERCENT
# Note: values below CODE_FACTOR_PERCENT_DETECTION_THRESHOLD will be SKIPPED.
CODE_FACTOR_PERCENT_DETECTION_THRESHOLD = configuration.CODE_FACTOR_PERCENT_DETECTION_THRESHOLD
if CODE_FACTOR_PERCENT_DETECTION_THRESHOLD >= CODE_FACTOR_PERCENT:
logging.info("Configuration ERROR: CODE_FACTOR_PERCENT_DETECTION_THRESHOLD >= CODE_FACTOR_PERCENT. We will skip all coded bits!")
exit(cf.f_lineno)
if CODE_FACTOR_PERCENT > 100:
logging.info("Configuration ERROR: CODE_FACTOR_PERCENT shall not exceed 100, otherwise lower delta cannot be coded!")
exit(cf.f_lineno)
elif CODE_FACTOR_PERCENT == 0:
logging.info("Configuration WARNING: with CODE_FACTOR_PERCENT == 0 coding will actually remove frequencies completely or double them, depending on ONE, ZERO value!")
CODE_FACTOR_PERCENT_PLUS_DEFAULT = (100.0 + CODE_FACTOR_PERCENT) / 100.0
CODE_FACTOR_PERCENT_MINUS_DEFAULT = (100.0 - CODE_FACTOR_PERCENT) / 100.0
logging.info("RECODE_FACTOR_PLUS = "+str(RECODE_FACTOR_PLUS))
logging.info("RECODE_FACTOR_MINUS = "+str(RECODE_FACTOR_MINUS))
logging.info("CODE_FACTOR_PERCENT = "+str(CODE_FACTOR_PERCENT))
logging.info("CODE_FACTOR_PERCENT_DETECTION_THRESHOLD = "+str(CODE_FACTOR_PERCENT_DETECTION_THRESHOLD))
logging.info("CODE_FACTOR_PERCENT_PLUS_DEFAULT = "+str(CODE_FACTOR_PERCENT_PLUS_DEFAULT))
logging.info("CODE_FACTOR_PERCENT_MINUS_DEFAULT = "+str(CODE_FACTOR_PERCENT_MINUS_DEFAULT))
# avoid peaks / big deviations and silences
###########################################
INTERPOLATION_FACTOR_PERCENT = CODE_FACTOR_PERCENT_DETECTION_THRESHOLD
INTERPOLATION_FACTOR_PERCENT_PLUS = (100.0 + INTERPOLATION_FACTOR_PERCENT) / 100.0
INTERPOLATION_FACTOR_PERCENT_MINUS = (100.0 - INTERPOLATION_FACTOR_PERCENT) / 100.0
logging.info("INTERPOLATION_FACTOR_PERCENT = "+str(INTERPOLATION_FACTOR_PERCENT))
logging.info("INTERPOLATION_FACTOR_PERCENT_MINUS = "+str(INTERPOLATION_FACTOR_PERCENT_MINUS))
##################
# NOTE: used to restore CODE_FACTOR_PERCENT_PLUS and CODE_FACTOR_PERCENT_MINUS after use in recode
CODE_FACTOR_PERCENT_PLUS_OLD = CODE_FACTOR_PERCENT_PLUS_DEFAULT
CODE_FACTOR_PERCENT_MINUS_OLD = CODE_FACTOR_PERCENT_MINUS_DEFAULT
# settings "band stop filter" to not interfere coding frequency when writing
############################################################################
# settings "elliptic filter"
# set BSF_MIN_ATTENUATION_DB = 0 to deactivate band stop filter
BSF_MIN_ATTENUATION_DB = configuration.BSF_MIN_ATTENUATION_DB
if BSF_MIN_ATTENUATION_DB > 145:
logging.error("Error: BSF_MIN_ATTENUATION_DB too high. Max. = 145 dB")
exit(cf.f_lineno)
elif BSF_MIN_ATTENUATION_DB > 0:
logging.info("Applying the band-stop-filter to the input signal will worsen concealment in frequency domain,\n\
thus increasing vulnerability against steganalysis. Apply this option only as a last measure.")
BSF_LEFT_MARGIN = 400 # 600
BSF_RIGHT_MARGIN = 400 # 600
BSF_ORDER = 7
BSF_MAX_RIPPLE = 0.1
BSF_F1 = CODE_FREQUENCY_START - BSF_LEFT_MARGIN
BSF_F2 = CODE_FREQUENCY_END + BSF_RIGHT_MARGIN
# TODO: update filter range each time we change NR_OF_CODE_FREQUENCIES_TO_CODE (and MAX_NR_OF_CODE_FREQUENCIES) ?
if BSF_F2 > FREQUENCY[NR_OF_FFT_BINS-1]:
BSF_F2 = FREQUENCY[NR_OF_FFT_BINS-1]
# code message
##############
message_temp = bitarray()
header_as_string = ""
# IMPORTANT: use SystemRandom() which uses os.urandom() internally to provide
# "secure" random numbers while still calling functions in random module (which is insecure).
# NOTE: results are no longer "reproducible", i.e. they are different in each run.
########################################################################################################
system_random = random.SystemRandom()
system_random.seed(SEED_IGNORE_CODE_DECEPTION)
# if writing:
# append header and input message to message_temp
#####################################################
if WRITE == True:
# compression
#############
len_msg_compressed = 0
with open(MESSAGE_FILE_NAME, 'rb') as fh:
a_bitarray = bitarray()
a_bitarray.fromfile(fh)
a_bytes = a_bitarray.tobytes()
a_bytes_compressed = zlib.compress(a_bytes, LEVEL_OF_COMPRESSION)
len_msg_compressed = len(a_bytes_compressed)
if len_msg_compressed < len(a_bytes):
COMPRESSION = True
compression_ratio = float(len(a_bytes)) / float(len_msg_compressed)
logging.info("Compressed msg with ratio = "+str(compression_ratio))
else:
logging.debug("No compression applied with len_msg_compressed = "+str(len_msg_compressed))
# encryption
############
if ENCRYPTION == False:
if COMPRESSION == True:
LEN_MSG_BYTES = len_msg_compressed + HEADER_SIZE_BYTES
else:
LEN_MSG_BYTES = os.path.getsize(MESSAGE_FILE_NAME) + HEADER_SIZE_BYTES
else:
if COMPRESSION == True:
a_bytes = a_bytes_compressed
a_bytes_encrypted = fernet.encrypt(a_bytes)
LEN_MSG_BYTES = len(a_bytes_encrypted) + HEADER_SIZE_BYTES
# add data to header which is needed later to recover the message
#################################################################
header_as_string += str(int(COMPRESSION == True))
header_as_string += str(int(ENCRYPTION==True))
header_as_string += "," + FILE_NAME_HDR
# add comma as field separator
header_as_string += "," + str(LEN_MSG_BYTES)
# add end marker
header_as_string += "#"
# transform str -> bytes
configuration_as_bytes = bytes(header_as_string, "utf-8")
# add padding bytes (as secure random bytes)
if len(configuration_as_bytes) <= HEADER_PAYLOAD_SIZE_BYTES:
padding = os.urandom(HEADER_PAYLOAD_SIZE_BYTES - len(configuration_as_bytes))
else:
logging.error("Error: configuration in header too big!")
exit(cf.f_lineno)
# to use # as a separator it shall NOT appear in the padding
# if it does, we re-generate padding until it does not.
############################################################
while b'#' in padding:
padding = os.urandom(HEADER_PAYLOAD_SIZE_BYTES - len(configuration_as_bytes))