Fucking line endings

This commit is contained in:
Fergal Moran
2017-03-23 19:03:46 +00:00
parent 3b0338e663
commit 31d36cf2ed
12 changed files with 941 additions and 941 deletions

506
.gitignore vendored
View File

@@ -1,254 +1,254 @@
## Ignore Visual Studio temporary files, build results, and ## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons. ## files generated by popular Visual Studio add-ons.
# User-specific files # User-specific files
*.suo *.suo
*.user *.user
*.userosscache *.userosscache
*.sln.docstates *.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio) # User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs *.userprefs
# Build results # Build results
[Dd]ebug/ [Dd]ebug/
[Dd]ebugPublic/ [Dd]ebugPublic/
[Rr]elease/ [Rr]elease/
[Rr]eleases/ [Rr]eleases/
x64/ x64/
x86/ x86/
bld/ bld/
[Bb]in/ [Bb]in/
[Oo]bj/ [Oo]bj/
[Ll]og/ [Ll]og/
# Visual Studio 2015 cache/options directory # Visual Studio 2015 cache/options directory
.vs/ .vs/
# Uncomment if you have tasks that create the project's static files in wwwroot # Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/ #wwwroot/
# MSTest test Results # MSTest test Results
[Tt]est[Rr]esult*/ [Tt]est[Rr]esult*/
[Bb]uild[Ll]og.* [Bb]uild[Ll]og.*
# NUNIT # NUNIT
*.VisualState.xml *.VisualState.xml
TestResult.xml TestResult.xml
# Build Results of an ATL Project # Build Results of an ATL Project
[Dd]ebugPS/ [Dd]ebugPS/
[Rr]eleasePS/ [Rr]eleasePS/
dlldata.c dlldata.c
# DNX # DNX
project.lock.json project.lock.json
artifacts/ artifacts/
*_i.c *_i.c
*_p.c *_p.c
*_i.h *_i.h
*.ilk *.ilk
*.meta *.meta
*.obj *.obj
*.pch *.pch
*.pdb *.pdb
*.pgc *.pgc
*.pgd *.pgd
*.rsp *.rsp
*.sbr *.sbr
*.tlb *.tlb
*.tli *.tli
*.tlh *.tlh
*.tmp *.tmp
*.tmp_proj *.tmp_proj
*.log *.log
*.vspscc *.vspscc
*.vssscc *.vssscc
.builds .builds
*.pidb *.pidb
*.svclog *.svclog
*.scc *.scc
# Chutzpah Test files # Chutzpah Test files
_Chutzpah* _Chutzpah*
# Visual C++ cache files # Visual C++ cache files
ipch/ ipch/
*.aps *.aps
*.ncb *.ncb
*.opendb *.opendb
*.opensdf *.opensdf
*.sdf *.sdf
*.cachefile *.cachefile
*.VC.db *.VC.db
*.VC.VC.opendb *.VC.VC.opendb
# Visual Studio profiler # Visual Studio profiler
*.psess *.psess
*.vsp *.vsp
*.vspx *.vspx
*.sap *.sap
# TFS 2012 Local Workspace # TFS 2012 Local Workspace
$tf/ $tf/
# Guidance Automation Toolkit # Guidance Automation Toolkit
*.gpState *.gpState
# ReSharper is a .NET coding add-in # ReSharper is a .NET coding add-in
_ReSharper*/ _ReSharper*/
*.[Rr]e[Ss]harper *.[Rr]e[Ss]harper
*.DotSettings.user *.DotSettings.user
# JustCode is a .NET coding add-in # JustCode is a .NET coding add-in
.JustCode .JustCode
# TeamCity is a build add-in # TeamCity is a build add-in
_TeamCity* _TeamCity*
# DotCover is a Code Coverage Tool # DotCover is a Code Coverage Tool
*.dotCover *.dotCover
# NCrunch # NCrunch
_NCrunch_* _NCrunch_*
.*crunch*.local.xml .*crunch*.local.xml
nCrunchTemp_* nCrunchTemp_*
# MightyMoose # MightyMoose
*.mm.* *.mm.*
AutoTest.Net/ AutoTest.Net/
# Web workbench (sass) # Web workbench (sass)
.sass-cache/ .sass-cache/
# Installshield output folder # Installshield output folder
[Ee]xpress/ [Ee]xpress/
# DocProject is a documentation generator add-in # DocProject is a documentation generator add-in
DocProject/buildhelp/ DocProject/buildhelp/
DocProject/Help/*.HxT DocProject/Help/*.HxT
DocProject/Help/*.HxC DocProject/Help/*.HxC
DocProject/Help/*.hhc DocProject/Help/*.hhc
DocProject/Help/*.hhk DocProject/Help/*.hhk
DocProject/Help/*.hhp DocProject/Help/*.hhp
DocProject/Help/Html2 DocProject/Help/Html2
DocProject/Help/html DocProject/Help/html
# Click-Once directory # Click-Once directory
publish/ publish/
# Publish Web Output # Publish Web Output
*.[Pp]ublish.xml *.[Pp]ublish.xml
*.azurePubxml *.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings # TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted # but database connection strings (with potential passwords) will be unencrypted
*.pubxml *.pubxml
*.publishproj *.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to # Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained # checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted # in these scripts will be unencrypted
PublishScripts/ PublishScripts/
# NuGet Packages # NuGet Packages
*.nupkg *.nupkg
# The packages folder can be ignored because of Package Restore # The packages folder can be ignored because of Package Restore
**/packages/* **/packages/*
# except build/, which is used as an MSBuild target. # except build/, which is used as an MSBuild target.
!**/packages/build/ !**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed # Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config #!**/packages/repositories.config
# NuGet v3's project.json files produces more ignoreable files # NuGet v3's project.json files produces more ignoreable files
*.nuget.props *.nuget.props
*.nuget.targets *.nuget.targets
# Microsoft Azure Build Output # Microsoft Azure Build Output
csx/ csx/
*.build.csdef *.build.csdef
# Microsoft Azure Emulator # Microsoft Azure Emulator
ecf/ ecf/
rcf/ rcf/
# Windows Store app package directories and files # Windows Store app package directories and files
AppPackages/ AppPackages/
BundleArtifacts/ BundleArtifacts/
Package.StoreAssociation.xml Package.StoreAssociation.xml
_pkginfo.txt _pkginfo.txt
# Visual Studio cache files # Visual Studio cache files
# files ending in .cache can be ignored # files ending in .cache can be ignored
*.[Cc]ache *.[Cc]ache
# but keep track of directories ending in .cache # but keep track of directories ending in .cache
!*.[Cc]ache/ !*.[Cc]ache/
# Others # Others
ClientBin/ ClientBin/
~$* ~$*
*~ *~
*.dbmdl *.dbmdl
*.dbproj.schemaview *.dbproj.schemaview
*.pfx *.pfx
*.publishsettings *.publishsettings
node_modules/ node_modules/
orleans.codegen.cs orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components # Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/ #bower_components/
# RIA/Silverlight projects # RIA/Silverlight projects
Generated_Code/ Generated_Code/
# Backup & report files from converting an old project file # Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed, # to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-) # because we have git ;-)
_UpgradeReport_Files/ _UpgradeReport_Files/
Backup*/ Backup*/
UpgradeLog*.XML UpgradeLog*.XML
UpgradeLog*.htm UpgradeLog*.htm
# SQL Server files # SQL Server files
*.mdf *.mdf
*.ldf *.ldf
# Business Intelligence projects # Business Intelligence projects
*.rdl.data *.rdl.data
*.bim.layout *.bim.layout
*.bim_*.settings *.bim_*.settings
# Microsoft Fakes # Microsoft Fakes
FakesAssemblies/ FakesAssemblies/
# GhostDoc plugin setting file # GhostDoc plugin setting file
*.GhostDoc.xml *.GhostDoc.xml
# Node.js Tools for Visual Studio # Node.js Tools for Visual Studio
.ntvs_analysis.dat .ntvs_analysis.dat
# Visual Studio 6 build log # Visual Studio 6 build log
*.plg *.plg
# Visual Studio 6 workspace options file # Visual Studio 6 workspace options file
*.opt *.opt
# Visual Studio LightSwitch build output # Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts **/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts **/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml **/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts **/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml **/*.Server/ModelManifest.xml
_Pvt_Extensions _Pvt_Extensions
# Paket dependency manager # Paket dependency manager
.paket/paket.exe .paket/paket.exe
paket-files/ paket-files/
# FAKE - F# Make # FAKE - F# Make
.fake/ .fake/
# JetBrains Rider # JetBrains Rider
.idea/ .idea/
*.sln.iml *.sln.iml
.vscode/ .vscode/

View File

@@ -1,29 +1,29 @@
using Microsoft.Extensions.CommandLineUtils; using Microsoft.Extensions.CommandLineUtils;
using System; using System;
namespace StegoPrint { namespace StegoPrint {
public class AddFingerprintCommand : CommandLineApplication { public class AddFingerprintCommand : CommandLineApplication {
CommandOption _message; CommandOption _message;
CommandOption _keyfile; CommandOption _keyfile;
CommandOption _input; CommandOption _input;
CommandOption _output; CommandOption _output;
public AddFingerprintCommand() { public AddFingerprintCommand() {
Name = "add"; Name = "add";
Description = "Adds a fingerprint to an audio file"; Description = "Adds a fingerprint to an audio file";
_message = Option("-$|-m |--message <message>", "The message to embed in the file", CommandOptionType.SingleValue); _message = Option("-$|-m |--message <message>", "The message to embed in the file", CommandOptionType.SingleValue);
_keyfile = Option("-$|-k |--keyfile <keyfile>", "The keyfile for the fingerprint", CommandOptionType.SingleValue); _keyfile = Option("-$|-k |--keyfile <keyfile>", "The keyfile for the fingerprint", CommandOptionType.SingleValue);
_input = Option("-$|-i |--input <input>", "The input audio file to process", CommandOptionType.SingleValue); _input = Option("-$|-i |--input <input>", "The input audio file to process", CommandOptionType.SingleValue);
_output = Option("-$|-o |--output <output>", "The output file", CommandOptionType.SingleValue); _output = Option("-$|-o |--output <output>", "The output file", CommandOptionType.SingleValue);
HelpOption("-h | -? | --help"); HelpOption("-h | -? | --help");
OnExecute((Func<int>)RunCommand); OnExecute((Func<int>)RunCommand);
} }
private int RunCommand() { private int RunCommand() {
new Fingerprinter().AddMessage(_message.Value(), _keyfile.Value(), _input.Value(), _output.Value()); new Fingerprinter().AddMessage(_message.Value(), _keyfile.Value(), _input.Value(), _output.Value());
return -1; return -1;
} }
} }
} }

22
App.cs
View File

@@ -1,11 +1,11 @@
using Microsoft.Extensions.CommandLineUtils; using Microsoft.Extensions.CommandLineUtils;
using System; using System;
namespace StegoPrint { namespace StegoPrint {
class App : CommandLineApplication { class App : CommandLineApplication {
public App() { public App() {
Commands.Add(new AddFingerprintCommand()); Commands.Add(new AddFingerprintCommand());
Commands.Add(new ExtractFingerprintCommand()); Commands.Add(new ExtractFingerprintCommand());
} }
} }
} }

View File

@@ -1,24 +1,24 @@
using Microsoft.Extensions.CommandLineUtils; using Microsoft.Extensions.CommandLineUtils;
using System; using System;
namespace StegoPrint { namespace StegoPrint {
public class ExtractFingerprintCommand : CommandLineApplication { public class ExtractFingerprintCommand : CommandLineApplication {
CommandOption _keyfile; CommandOption _keyfile;
CommandOption _input; CommandOption _input;
public ExtractFingerprintCommand() { public ExtractFingerprintCommand() {
Name = "extract"; Name = "extract";
Description = "Extracts a fingerprint from a file"; Description = "Extracts a fingerprint from a file";
_keyfile = Option("-$|-k |--keyfile <keyfile>", "The keyfile for the fingerprint", CommandOptionType.SingleValue); _keyfile = Option("-$|-k |--keyfile <keyfile>", "The keyfile for the fingerprint", CommandOptionType.SingleValue);
_input = Option("-$|-i |--input <input>", "The input audio file to process", CommandOptionType.SingleValue); _input = Option("-$|-i |--input <input>", "The input audio file to process", CommandOptionType.SingleValue);
HelpOption("-h | -? | --help"); HelpOption("-h | -? | --help");
OnExecute((Func<int>)RunCommand); OnExecute((Func<int>)RunCommand);
} }
private int RunCommand() { private int RunCommand() {
new Fingerprinter().ExtractMessage(_keyfile.Value(), _input.Value()); new Fingerprinter().ExtractMessage(_keyfile.Value(), _input.Value());
return -1; return -1;
} }
} }
} }

View File

@@ -1,101 +1,101 @@
using System; using System;
using System.IO; using System.IO;
using System.Text; using System.Text;
namespace StegoPrint { namespace StegoPrint {
public class Fingerprinter { public class Fingerprinter {
private Stream GetMessageStream(string message) { private Stream GetMessageStream(string message) {
BinaryWriter messageWriter = new BinaryWriter(new MemoryStream()); BinaryWriter messageWriter = new BinaryWriter(new MemoryStream());
messageWriter.Write(message.Length); messageWriter.Write(message.Length);
messageWriter.Write(Encoding.ASCII.GetBytes(message)); messageWriter.Write(Encoding.ASCII.GetBytes(message));
messageWriter.Seek(0, SeekOrigin.Begin); messageWriter.Seek(0, SeekOrigin.Begin);
return messageWriter.BaseStream; return messageWriter.BaseStream;
} }
public void AddMessage(string message, string keyFile, string inputFile, string outputFile) { public void AddMessage(string message, string keyFile, string inputFile, string outputFile) {
Stream sourceStream = null; Stream sourceStream = null;
FileStream destinationStream = null; FileStream destinationStream = null;
WaveStream audioStream = null; WaveStream audioStream = null;
//create a stream that contains the message, preceeded by its length //create a stream that contains the message, preceeded by its length
Stream messageStream = GetMessageStream(message); Stream messageStream = GetMessageStream(message);
//open the key file //open the key file
Stream keyStream = new FileStream(keyFile, FileMode.Open); Stream keyStream = new FileStream(keyFile, FileMode.Open);
try { try {
//how man samples do we need? //how man samples do we need?
long countSamplesRequired = WaveUtility.CheckKeyForMessage(keyStream, messageStream.Length); long countSamplesRequired = WaveUtility.CheckKeyForMessage(keyStream, messageStream.Length);
if (countSamplesRequired > Int32.MaxValue) { if (countSamplesRequired > Int32.MaxValue) {
throw new Exception("Message too long, or bad key! This message/key combination requires " + countSamplesRequired + " samples, only " + Int32.MaxValue + " samples are allowed."); throw new Exception("Message too long, or bad key! This message/key combination requires " + countSamplesRequired + " samples, only " + Int32.MaxValue + " samples are allowed.");
} }
sourceStream = new FileStream(inputFile, FileMode.Open); sourceStream = new FileStream(inputFile, FileMode.Open);
//create an empty file for the carrier wave //create an empty file for the carrier wave
destinationStream = new FileStream(outputFile, FileMode.Create); destinationStream = new FileStream(outputFile, FileMode.Create);
//copy the carrier file's header //copy the carrier file's header
audioStream = new WaveStream(sourceStream, destinationStream); audioStream = new WaveStream(sourceStream, destinationStream);
if (audioStream.Length <= 0) { if (audioStream.Length <= 0) {
throw new Exception("Invalid WAV file"); throw new Exception("Invalid WAV file");
} }
//are there enough samples in the carrier wave? //are there enough samples in the carrier wave?
if (countSamplesRequired > audioStream.CountSamples) { if (countSamplesRequired > audioStream.CountSamples) {
String errorReport = "The carrier file is too small for this message and key!\r\n" + String errorReport = "The carrier file is too small for this message and key!\r\n" +
"Samples available: " + audioStream.CountSamples + "\r\n" + "Samples available: " + audioStream.CountSamples + "\r\n" +
"Samples needed: " + countSamplesRequired; "Samples needed: " + countSamplesRequired;
throw new Exception(errorReport); throw new Exception(errorReport);
} }
//hide the message //hide the message
WaveUtility utility = new WaveUtility(audioStream, destinationStream); WaveUtility utility = new WaveUtility(audioStream, destinationStream);
utility.Hide(messageStream, keyStream); utility.Hide(messageStream, keyStream);
} catch (Exception ex) { } catch (Exception ex) {
Console.WriteLine($"Error: {ex.Message}"); Console.WriteLine($"Error: {ex.Message}");
} finally { } finally {
if (keyStream != null) { keyStream.Dispose(); } if (keyStream != null) { keyStream.Dispose(); }
if (messageStream != null) { messageStream.Dispose(); } if (messageStream != null) { messageStream.Dispose(); }
if (audioStream != null) { audioStream.Dispose(); } if (audioStream != null) { audioStream.Dispose(); }
if (sourceStream != null) { sourceStream.Dispose(); } if (sourceStream != null) { sourceStream.Dispose(); }
if (destinationStream != null) { destinationStream.Dispose(); } if (destinationStream != null) { destinationStream.Dispose(); }
} }
} }
public void ExtractMessage(string keyFile, string inputFile) { public void ExtractMessage(string keyFile, string inputFile) {
FileStream sourceStream = null; FileStream sourceStream = null;
WaveStream audioStream = null; WaveStream audioStream = null;
//create an empty stream to receive the extracted message //create an empty stream to receive the extracted message
MemoryStream messageStream = new MemoryStream(); MemoryStream messageStream = new MemoryStream();
//open the key file //open the key file
Stream keyStream = new FileStream(keyFile, FileMode.Open); Stream keyStream = new FileStream(keyFile, FileMode.Open);
try { try {
//open the carrier file //open the carrier file
sourceStream = new FileStream(inputFile, FileMode.Open); sourceStream = new FileStream(inputFile, FileMode.Open);
audioStream = new WaveStream(sourceStream); audioStream = new WaveStream(sourceStream);
WaveUtility utility = new WaveUtility(audioStream); WaveUtility utility = new WaveUtility(audioStream);
//exctract the message from the carrier wave //exctract the message from the carrier wave
utility.Extract(messageStream, keyStream); utility.Extract(messageStream, keyStream);
messageStream.Seek(0, SeekOrigin.Begin); messageStream.Seek(0, SeekOrigin.Begin);
string extractedMessage = new StreamReader(messageStream).ReadToEnd(); string extractedMessage = new StreamReader(messageStream).ReadToEnd();
Console.WriteLine("Message is....."); Console.WriteLine("Message is.....");
Console.WriteLine(extractedMessage); Console.WriteLine(extractedMessage);
Console.ReadKey(); Console.ReadKey();
} catch (Exception ex) { } catch (Exception ex) {
Console.WriteLine($"Error extracting message {ex.Message}"); Console.WriteLine($"Error extracting message {ex.Message}");
} finally { } finally {
if (keyStream != null) { keyStream.Dispose(); } if (keyStream != null) { keyStream.Dispose(); }
if (messageStream != null) { messageStream.Dispose(); } if (messageStream != null) { messageStream.Dispose(); }
if (audioStream != null) { audioStream.Dispose(); } if (audioStream != null) { audioStream.Dispose(); }
if (sourceStream != null) { sourceStream.Dispose(); } if (sourceStream != null) { sourceStream.Dispose(); }
} }
} }
} }
} }

View File

@@ -1,16 +1,16 @@
using Microsoft.Extensions.CommandLineUtils; using Microsoft.Extensions.CommandLineUtils;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
namespace StegoPrint { namespace StegoPrint {
class Program { class Program {
static int Main(string[] args) { static int Main(string[] args) {
try { try {
return new App().Execute(args); return new App().Execute(args);
} catch (Exception ex) { } catch (Exception ex) {
Console.Write(ex); Console.Write(ex);
return 1; return 1;
} }
} }
} }
} }

View File

@@ -1,8 +1,8 @@
{ {
"profiles": { "profiles": {
"stegoprint": { "stegoprint": {
"commandName": "Project", "commandName": "Project",
"commandLineArgs": "extract -k \"C:\\dev\\working\\stegano\\mylib\\keyfile.txt\" -i \"C:\\dev\\working\\stegano\\mylib\\out.wav\"" "commandLineArgs": "extract -k \"C:\\dev\\working\\stegano\\mylib\\keyfile.txt\" -i \"C:\\dev\\working\\stegano\\mylib\\out.wav\""
} }
} }
} }

View File

@@ -1,29 +1,29 @@
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
namespace StegoPrint { namespace StegoPrint {
public enum WaveFormats { public enum WaveFormats {
Pcm = 1, Pcm = 1,
Float = 3 Float = 3
} }
[StructLayout (LayoutKind.Sequential)] [StructLayout (LayoutKind.Sequential)]
public class WaveFormat { public class WaveFormat {
public short wFormatTag; public short wFormatTag;
public short nChannels; public short nChannels;
public int nSamplesPerSec; public int nSamplesPerSec;
public int nAvgBytesPerSec; public int nAvgBytesPerSec;
public short nBlockAlign; public short nBlockAlign;
public short wBitsPerSample; public short wBitsPerSample;
public short cbSize; public short cbSize;
public WaveFormat (int rate, int bits, int channels) { public WaveFormat (int rate, int bits, int channels) {
wFormatTag = (short) WaveFormats.Pcm; wFormatTag = (short) WaveFormats.Pcm;
nChannels = (short) channels; nChannels = (short) channels;
nSamplesPerSec = rate; nSamplesPerSec = rate;
wBitsPerSample = (short) bits; wBitsPerSample = (short) bits;
cbSize = 0; cbSize = 0;
nBlockAlign = (short) (channels * (bits / 8)); nBlockAlign = (short) (channels * (bits / 8));
nAvgBytesPerSec = nSamplesPerSec * nBlockAlign; nAvgBytesPerSec = nSamplesPerSec * nBlockAlign;
} }
} }
} }

View File

@@ -1,263 +1,263 @@
using System; using System;
using System.IO; using System.IO;
namespace StegoPrint { namespace StegoPrint {
public class WaveStream : Stream, IDisposable { public class WaveStream : Stream, IDisposable {
private Stream m_Stream; private Stream m_Stream;
private long m_DataPos; private long m_DataPos;
private int m_Length; private int m_Length;
private WaveFormat m_Format; private WaveFormat m_Format;
public WaveFormat Format { public WaveFormat Format {
get { return m_Format; } get { return m_Format; }
} }
private string ReadChunk (BinaryReader reader) { private string ReadChunk (BinaryReader reader) {
byte[] ch = new byte[4]; byte[] ch = new byte[4];
reader.Read (ch, 0, ch.Length); reader.Read (ch, 0, ch.Length);
return System.Text.Encoding.ASCII.GetString (ch); return System.Text.Encoding.ASCII.GetString (ch);
} }
private void ReadHeader () { private void ReadHeader () {
BinaryReader Reader = new BinaryReader (m_Stream); BinaryReader Reader = new BinaryReader (m_Stream);
if (ReadChunk (Reader) != "RIFF") if (ReadChunk (Reader) != "RIFF")
throw new Exception ("Invalid file format"); throw new Exception ("Invalid file format");
Reader.ReadInt32 (); // File length minus first 8 bytes of RIFF description, we don't use it Reader.ReadInt32 (); // File length minus first 8 bytes of RIFF description, we don't use it
if (ReadChunk (Reader) != "WAVE") if (ReadChunk (Reader) != "WAVE")
throw new Exception ("Invalid file format"); throw new Exception ("Invalid file format");
if (ReadChunk (Reader) != "fmt ") if (ReadChunk (Reader) != "fmt ")
throw new Exception ("Invalid file format"); throw new Exception ("Invalid file format");
int len = Reader.ReadInt32 (); int len = Reader.ReadInt32 ();
if (len < 16) // bad format chunk length if (len < 16) // bad format chunk length
throw new Exception ("Invalid file format"); throw new Exception ("Invalid file format");
m_Format = new WaveFormat (22050, 16, 2); // initialize to any format m_Format = new WaveFormat (22050, 16, 2); // initialize to any format
m_Format.wFormatTag = Reader.ReadInt16 (); m_Format.wFormatTag = Reader.ReadInt16 ();
m_Format.nChannels = Reader.ReadInt16 (); m_Format.nChannels = Reader.ReadInt16 ();
m_Format.nSamplesPerSec = Reader.ReadInt32 (); m_Format.nSamplesPerSec = Reader.ReadInt32 ();
m_Format.nAvgBytesPerSec = Reader.ReadInt32 (); m_Format.nAvgBytesPerSec = Reader.ReadInt32 ();
m_Format.nBlockAlign = Reader.ReadInt16 (); m_Format.nBlockAlign = Reader.ReadInt16 ();
m_Format.wBitsPerSample = Reader.ReadInt16 (); m_Format.wBitsPerSample = Reader.ReadInt16 ();
// advance in the stream to skip the wave format block // advance in the stream to skip the wave format block
len -= 16; // minimum format size len -= 16; // minimum format size
while (len > 0) { while (len > 0) {
Reader.ReadByte (); Reader.ReadByte ();
len--; len--;
} }
// assume the data chunk is aligned // assume the data chunk is aligned
while (m_Stream.Position < m_Stream.Length && ReadChunk (Reader) != "data") while (m_Stream.Position < m_Stream.Length && ReadChunk (Reader) != "data")
; ;
if (m_Stream.Position >= m_Stream.Length) if (m_Stream.Position >= m_Stream.Length)
throw new Exception ("Invalid file format"); throw new Exception ("Invalid file format");
m_Length = Reader.ReadInt32 (); m_Length = Reader.ReadInt32 ();
m_DataPos = m_Stream.Position; m_DataPos = m_Stream.Position;
Position = 0; Position = 0;
} }
/// <summary>ReadChunk(reader) - Changed to CopyChunk(reader, writer)</summary> /// <summary>ReadChunk(reader) - Changed to CopyChunk(reader, writer)</summary>
/// <param name="reader">source stream</param> /// <param name="reader">source stream</param>
/// <returns>four characters</returns> /// <returns>four characters</returns>
private string CopyChunk (BinaryReader reader, BinaryWriter writer) { private string CopyChunk (BinaryReader reader, BinaryWriter writer) {
byte[] ch = new byte[4]; byte[] ch = new byte[4];
reader.Read (ch, 0, ch.Length); reader.Read (ch, 0, ch.Length);
//copy the chunk //copy the chunk
writer.Write (ch); writer.Write (ch);
return System.Text.Encoding.ASCII.GetString (ch); return System.Text.Encoding.ASCII.GetString (ch);
} }
/// <summary>ReadHeader() - Changed to CopyHeader(destination)</summary> /// <summary>ReadHeader() - Changed to CopyHeader(destination)</summary>
private void CopyHeader (Stream destinationStream) { private void CopyHeader (Stream destinationStream) {
BinaryReader reader = new BinaryReader (m_Stream); BinaryReader reader = new BinaryReader (m_Stream);
BinaryWriter writer = new BinaryWriter (destinationStream); BinaryWriter writer = new BinaryWriter (destinationStream);
if (CopyChunk (reader, writer) != "RIFF") if (CopyChunk (reader, writer) != "RIFF")
throw new Exception ("Invalid file format"); throw new Exception ("Invalid file format");
writer.Write (reader.ReadInt32 ()); // File length minus first 8 bytes of RIFF description writer.Write (reader.ReadInt32 ()); // File length minus first 8 bytes of RIFF description
if (CopyChunk (reader, writer) != "WAVE") if (CopyChunk (reader, writer) != "WAVE")
throw new Exception ("Invalid file format"); throw new Exception ("Invalid file format");
if (CopyChunk (reader, writer) != "fmt ") if (CopyChunk (reader, writer) != "fmt ")
throw new Exception ("Invalid file format"); throw new Exception ("Invalid file format");
int len = reader.ReadInt32 (); int len = reader.ReadInt32 ();
if (len < 16) { // bad format chunk length if (len < 16) { // bad format chunk length
throw new Exception ("Invalid file format"); throw new Exception ("Invalid file format");
} else { } else {
writer.Write (len); writer.Write (len);
} }
m_Format = new WaveFormat (22050, 16, 2); // initialize to any format m_Format = new WaveFormat (22050, 16, 2); // initialize to any format
m_Format.wFormatTag = reader.ReadInt16 (); m_Format.wFormatTag = reader.ReadInt16 ();
m_Format.nChannels = reader.ReadInt16 (); m_Format.nChannels = reader.ReadInt16 ();
m_Format.nSamplesPerSec = reader.ReadInt32 (); m_Format.nSamplesPerSec = reader.ReadInt32 ();
m_Format.nAvgBytesPerSec = reader.ReadInt32 (); m_Format.nAvgBytesPerSec = reader.ReadInt32 ();
m_Format.nBlockAlign = reader.ReadInt16 (); m_Format.nBlockAlign = reader.ReadInt16 ();
m_Format.wBitsPerSample = reader.ReadInt16 (); m_Format.wBitsPerSample = reader.ReadInt16 ();
//copy format information //copy format information
writer.Write (m_Format.wFormatTag); writer.Write (m_Format.wFormatTag);
writer.Write (m_Format.nChannels); writer.Write (m_Format.nChannels);
writer.Write (m_Format.nSamplesPerSec); writer.Write (m_Format.nSamplesPerSec);
writer.Write (m_Format.nAvgBytesPerSec); writer.Write (m_Format.nAvgBytesPerSec);
writer.Write (m_Format.nBlockAlign); writer.Write (m_Format.nBlockAlign);
writer.Write (m_Format.wBitsPerSample); writer.Write (m_Format.wBitsPerSample);
// advance in the stream to skip the wave format block // advance in the stream to skip the wave format block
len -= 16; // minimum format size len -= 16; // minimum format size
writer.Write (reader.ReadBytes (len)); writer.Write (reader.ReadBytes (len));
len = 0; len = 0;
/*while (len > 0) /*while (len > 0)
{ {
reader.ReadByte(); reader.ReadByte();
len--; len--;
}*/ }*/
// assume the data chunk is aligned // assume the data chunk is aligned
while (m_Stream.Position < m_Stream.Length && CopyChunk (reader, writer) != "data") while (m_Stream.Position < m_Stream.Length && CopyChunk (reader, writer) != "data")
; ;
if (m_Stream.Position >= m_Stream.Length) if (m_Stream.Position >= m_Stream.Length)
throw new Exception ("Invalid file format"); throw new Exception ("Invalid file format");
m_Length = reader.ReadInt32 (); m_Length = reader.ReadInt32 ();
writer.Write (m_Length); writer.Write (m_Length);
m_DataPos = m_Stream.Position; m_DataPos = m_Stream.Position;
Position = 0; Position = 0;
} }
/// <summary>Write a new header</summary> /// <summary>Write a new header</summary>
public static Stream CreateStream (Stream waveData, WaveFormat format) { public static Stream CreateStream (Stream waveData, WaveFormat format) {
MemoryStream stream = new MemoryStream (); MemoryStream stream = new MemoryStream ();
BinaryWriter writer = new BinaryWriter (stream); BinaryWriter writer = new BinaryWriter (stream);
writer.Write (System.Text.Encoding.ASCII.GetBytes ("RIFF".ToCharArray ())); writer.Write (System.Text.Encoding.ASCII.GetBytes ("RIFF".ToCharArray ()));
writer.Write ((Int32) (waveData.Length + 36)); //File length minus first 8 bytes of RIFF description writer.Write ((Int32) (waveData.Length + 36)); //File length minus first 8 bytes of RIFF description
writer.Write (System.Text.Encoding.ASCII.GetBytes ("WAVEfmt ".ToCharArray ())); writer.Write (System.Text.Encoding.ASCII.GetBytes ("WAVEfmt ".ToCharArray ()));
writer.Write ((Int32) 16); //length of following chunk: 16 writer.Write ((Int32) 16); //length of following chunk: 16
writer.Write ((Int16) format.wFormatTag); writer.Write ((Int16) format.wFormatTag);
writer.Write ((Int16) format.nChannels); writer.Write ((Int16) format.nChannels);
writer.Write ((Int32) format.nSamplesPerSec); writer.Write ((Int32) format.nSamplesPerSec);
writer.Write ((Int32) format.nAvgBytesPerSec); writer.Write ((Int32) format.nAvgBytesPerSec);
writer.Write ((Int16) format.nBlockAlign); writer.Write ((Int16) format.nBlockAlign);
writer.Write ((Int16) format.wBitsPerSample); writer.Write ((Int16) format.wBitsPerSample);
writer.Write (System.Text.Encoding.ASCII.GetBytes ("data".ToCharArray ())); writer.Write (System.Text.Encoding.ASCII.GetBytes ("data".ToCharArray ()));
writer.Write ((Int32) waveData.Length); writer.Write ((Int32) waveData.Length);
waveData.Seek (0, SeekOrigin.Begin); waveData.Seek (0, SeekOrigin.Begin);
byte[] b = new byte[waveData.Length]; byte[] b = new byte[waveData.Length];
waveData.Read (b, 0, (int) waveData.Length); waveData.Read (b, 0, (int) waveData.Length);
writer.Write (b); writer.Write (b);
writer.Seek (0, SeekOrigin.Begin); writer.Seek (0, SeekOrigin.Begin);
return stream; return stream;
} }
public WaveStream (Stream sourceStream, Stream destinationStream) { public WaveStream (Stream sourceStream, Stream destinationStream) {
m_Stream = sourceStream; m_Stream = sourceStream;
CopyHeader (destinationStream); CopyHeader (destinationStream);
} }
public WaveStream (Stream sourceStream) { public WaveStream (Stream sourceStream) {
m_Stream = sourceStream; m_Stream = sourceStream;
ReadHeader (); ReadHeader ();
} }
~WaveStream () { ~WaveStream () {
Dispose (); Dispose ();
} }
public new void Dispose () { public new void Dispose () {
base.Dispose (); base.Dispose ();
GC.SuppressFinalize (this); GC.SuppressFinalize (this);
} }
public override bool CanRead { public override bool CanRead {
get { return true; } get { return true; }
} }
public override bool CanSeek { public override bool CanSeek {
get { return true; } get { return true; }
} }
public override bool CanWrite { public override bool CanWrite {
get { return false; } get { return false; }
} }
public override long Length { public override long Length {
get { return m_Length; } get { return m_Length; }
} }
/// <summary>Length of the data (in samples)</summary> /// <summary>Length of the data (in samples)</summary>
public long CountSamples { public long CountSamples {
get { return (long) ((m_Length - m_DataPos) / (m_Format.wBitsPerSample / 8)); } get { return (long) ((m_Length - m_DataPos) / (m_Format.wBitsPerSample / 8)); }
} }
public override long Position { public override long Position {
get { return m_Stream.Position - m_DataPos; } get { return m_Stream.Position - m_DataPos; }
set { Seek (value, SeekOrigin.Begin); } set { Seek (value, SeekOrigin.Begin); }
} }
public override void Flush () { } public override void Flush () { }
public override void SetLength (long len) { public override void SetLength (long len) {
throw new InvalidOperationException (); throw new InvalidOperationException ();
} }
public override long Seek (long pos, SeekOrigin o) { public override long Seek (long pos, SeekOrigin o) {
switch (o) { switch (o) {
case SeekOrigin.Begin: case SeekOrigin.Begin:
m_Stream.Position = pos + m_DataPos; m_Stream.Position = pos + m_DataPos;
break; break;
case SeekOrigin.Current: case SeekOrigin.Current:
m_Stream.Seek (pos, SeekOrigin.Current); m_Stream.Seek (pos, SeekOrigin.Current);
break; break;
case SeekOrigin.End: case SeekOrigin.End:
m_Stream.Position = m_DataPos + m_Length - pos; m_Stream.Position = m_DataPos + m_Length - pos;
break; break;
} }
return this.Position; return this.Position;
} }
public override int Read (byte[] buf, int ofs, int count) { public override int Read (byte[] buf, int ofs, int count) {
int toread = (int) Math.Min (count, m_Length - Position); int toread = (int) Math.Min (count, m_Length - Position);
return m_Stream.Read (buf, ofs, toread); return m_Stream.Read (buf, ofs, toread);
} }
/// <summary>Read - Changed to Copy</summary> /// <summary>Read - Changed to Copy</summary>
/// <param name="buf">Buffer to receive the data</param> /// <param name="buf">Buffer to receive the data</param>
/// <param name="ofs">Offset</param> /// <param name="ofs">Offset</param>
/// <param name="count">Count of bytes to read</param> /// <param name="count">Count of bytes to read</param>
/// <param name="destination">Where to copy the buffer</param> /// <param name="destination">Where to copy the buffer</param>
/// <returns>Count of bytes actually read</returns> /// <returns>Count of bytes actually read</returns>
public int Copy (byte[] buf, int ofs, int count, Stream destination) { public int Copy (byte[] buf, int ofs, int count, Stream destination) {
int toread = (int) Math.Min (count, m_Length - Position); int toread = (int) Math.Min (count, m_Length - Position);
int read = m_Stream.Read (buf, ofs, toread); int read = m_Stream.Read (buf, ofs, toread);
destination.Write (buf, ofs, read); destination.Write (buf, ofs, read);
if (m_Stream.Position != destination.Position) { if (m_Stream.Position != destination.Position) {
Console.WriteLine (); Console.WriteLine ();
} }
return read; return read;
} }
public override void Write (byte[] buf, int ofs, int count) { public override void Write (byte[] buf, int ofs, int count) {
throw new InvalidOperationException (); throw new InvalidOperationException ();
} }
} }
} }

View File

@@ -1,203 +1,203 @@
using System.IO; using System.IO;
namespace StegoPrint { namespace StegoPrint {
public class WaveUtility { public class WaveUtility {
/// <summary> /// <summary>
/// The read-only stream. /// The read-only stream.
/// Clean wave for hiding, /// Clean wave for hiding,
/// Carrier wave for extracting /// Carrier wave for extracting
/// </summary> /// </summary>
private WaveStream sourceStream; private WaveStream sourceStream;
/// <summary>Stream to receive the edited carrier wave</summary> /// <summary>Stream to receive the edited carrier wave</summary>
private Stream destinationStream; private Stream destinationStream;
/// <summary>bits per sample / 8</summary> /// <summary>bits per sample / 8</summary>
private int bytesPerSample; private int bytesPerSample;
/// <summary>Initializes a new WaveUtility for hiding a message</summary> /// <summary>Initializes a new WaveUtility for hiding a message</summary>
/// <param name="sourceStream">Clean wave</param> /// <param name="sourceStream">Clean wave</param>
/// <param name="destinationStream"> /// <param name="destinationStream">
/// Header of the clean wave /// Header of the clean wave
/// This stream will receive the complete carrier wave /// This stream will receive the complete carrier wave
/// </param> /// </param>
public WaveUtility (WaveStream sourceStream, Stream destinationStream) : this (sourceStream) { public WaveUtility (WaveStream sourceStream, Stream destinationStream) : this (sourceStream) {
this.destinationStream = destinationStream; this.destinationStream = destinationStream;
} }
/// <summary>Initializes a new WaveUtility for extracting a message</summary> /// <summary>Initializes a new WaveUtility for extracting a message</summary>
/// <param name="sourceStream">Carrier wave</param> /// <param name="sourceStream">Carrier wave</param>
public WaveUtility (WaveStream sourceStream) { public WaveUtility (WaveStream sourceStream) {
this.sourceStream = sourceStream; this.sourceStream = sourceStream;
this.bytesPerSample = sourceStream.Format.wBitsPerSample / 8; this.bytesPerSample = sourceStream.Format.wBitsPerSample / 8;
} }
/// <summary> /// <summary>
/// Hide [messageStream] in [sourceStream], /// Hide [messageStream] in [sourceStream],
/// write the result to [destinationStream] /// write the result to [destinationStream]
/// </summary> /// </summary>
/// <param name="messageStream">The message to hide</param> /// <param name="messageStream">The message to hide</param>
/// <param name="keyStream"> /// <param name="keyStream">
/// A key stream that specifies how many samples shall be /// A key stream that specifies how many samples shall be
/// left clean between two changed samples /// left clean between two changed samples
/// </param> /// </param>
public void Hide (Stream messageStream, Stream keyStream) { public void Hide (Stream messageStream, Stream keyStream) {
byte[] waveBuffer = new byte[bytesPerSample]; byte[] waveBuffer = new byte[bytesPerSample];
byte message, bit, waveByte; byte message, bit, waveByte;
int messageBuffer; //receives the next byte of the message or -1 int messageBuffer; //receives the next byte of the message or -1
int keyByte; //distance of the next carrier sample int keyByte; //distance of the next carrier sample
while ((messageBuffer = messageStream.ReadByte ()) >= 0) { while ((messageBuffer = messageStream.ReadByte ()) >= 0) {
//read one byte of the message stream //read one byte of the message stream
message = (byte) messageBuffer; message = (byte) messageBuffer;
//for each bit in message //for each bit in message
for (int bitIndex = 0; bitIndex < 8; bitIndex++) { for (int bitIndex = 0; bitIndex < 8; bitIndex++) {
//read a byte from the key //read a byte from the key
keyByte = GetKeyValue (keyStream); keyByte = GetKeyValue (keyStream);
//skip a couple of samples //skip a couple of samples
for (int n = 0; n < keyByte - 1; n++) { for (int n = 0; n < keyByte - 1; n++) {
//copy one sample from the clean stream to the carrier stream //copy one sample from the clean stream to the carrier stream
sourceStream.Copy (waveBuffer, 0, waveBuffer.Length, destinationStream); sourceStream.Copy (waveBuffer, 0, waveBuffer.Length, destinationStream);
} }
//read one sample from the wave stream //read one sample from the wave stream
sourceStream.Read (waveBuffer, 0, waveBuffer.Length); sourceStream.Read (waveBuffer, 0, waveBuffer.Length);
waveByte = waveBuffer[bytesPerSample - 1]; waveByte = waveBuffer[bytesPerSample - 1];
//get the next bit from the current message byte... //get the next bit from the current message byte...
bit = (byte) (((message & (byte) (1<<bitIndex))> 0) ? 1 : 0); bit = (byte) (((message & (byte) (1<<bitIndex))> 0) ? 1 : 0);
//...place it in the last bit of the sample //...place it in the last bit of the sample
if ((bit == 1) && ((waveByte % 2) == 0)) { if ((bit == 1) && ((waveByte % 2) == 0)) {
waveByte += 1; waveByte += 1;
} else if ((bit == 0) && ((waveByte % 2) == 1)) { } else if ((bit == 0) && ((waveByte % 2) == 1)) {
waveByte -= 1; waveByte -= 1;
} }
waveBuffer[bytesPerSample - 1] = waveByte; waveBuffer[bytesPerSample - 1] = waveByte;
//write the result to destinationStream //write the result to destinationStream
destinationStream.Write (waveBuffer, 0, bytesPerSample); destinationStream.Write (waveBuffer, 0, bytesPerSample);
} }
} }
//copy the rest of the wave without changes //copy the rest of the wave without changes
waveBuffer = new byte[sourceStream.Length - sourceStream.Position]; waveBuffer = new byte[sourceStream.Length - sourceStream.Position];
sourceStream.Read (waveBuffer, 0, waveBuffer.Length); sourceStream.Read (waveBuffer, 0, waveBuffer.Length);
destinationStream.Write (waveBuffer, 0, waveBuffer.Length); destinationStream.Write (waveBuffer, 0, waveBuffer.Length);
} }
/// <summary>Extract a message from [sourceStream] into [messageStream]</summary> /// <summary>Extract a message from [sourceStream] into [messageStream]</summary>
/// <param name="messageStream">Empty stream to receive the extracted message</param> /// <param name="messageStream">Empty stream to receive the extracted message</param>
/// <param name="keyStream"> /// <param name="keyStream">
/// A key stream that specifies how many samples shall be /// A key stream that specifies how many samples shall be
/// skipped between two carrier samples /// skipped between two carrier samples
/// </param> /// </param>
public void Extract (Stream messageStream, Stream keyStream) { public void Extract (Stream messageStream, Stream keyStream) {
byte[] waveBuffer = new byte[bytesPerSample]; byte[] waveBuffer = new byte[bytesPerSample];
byte message, bit, waveByte; byte message, bit, waveByte;
int messageLength = 0; //expected length of the message int messageLength = 0; //expected length of the message
int keyByte; //distance of the next carrier sample int keyByte; //distance of the next carrier sample
while ((messageLength == 0 || messageStream.Length < messageLength)) { while ((messageLength == 0 || messageStream.Length < messageLength)) {
//clear the message-byte //clear the message-byte
message = 0; message = 0;
//for each bit in message //for each bit in message
for (int bitIndex = 0; bitIndex < 8; bitIndex++) { for (int bitIndex = 0; bitIndex < 8; bitIndex++) {
//read a byte from the key //read a byte from the key
keyByte = GetKeyValue (keyStream); keyByte = GetKeyValue (keyStream);
//skip a couple of samples //skip a couple of samples
for (int n = 0; n < keyByte - 1; n++) { for (int n = 0; n < keyByte - 1; n++) {
//read one sample from the wave stream //read one sample from the wave stream
sourceStream.Read (waveBuffer, 0, waveBuffer.Length); sourceStream.Read (waveBuffer, 0, waveBuffer.Length);
} }
sourceStream.Read (waveBuffer, 0, waveBuffer.Length); sourceStream.Read (waveBuffer, 0, waveBuffer.Length);
waveByte = waveBuffer[bytesPerSample - 1]; waveByte = waveBuffer[bytesPerSample - 1];
//get the last bit of the sample... //get the last bit of the sample...
bit = (byte) (((waveByte % 2) == 0) ? 0 : 1); bit = (byte) (((waveByte % 2) == 0) ? 0 : 1);
//...write it into the message-byte //...write it into the message-byte
message += (byte) (bit << bitIndex); message += (byte) (bit << bitIndex);
} }
//add the re-constructed byte to the message //add the re-constructed byte to the message
messageStream.WriteByte (message); messageStream.WriteByte (message);
if (messageLength == 0 && messageStream.Length == 4) { if (messageLength == 0 && messageStream.Length == 4) {
//first 4 bytes contain the message's length //first 4 bytes contain the message's length
messageStream.Seek (0, SeekOrigin.Begin); messageStream.Seek (0, SeekOrigin.Begin);
messageLength = new BinaryReader (messageStream).ReadInt32 (); messageLength = new BinaryReader (messageStream).ReadInt32 ();
messageStream.Seek (0, SeekOrigin.Begin); messageStream.Seek (0, SeekOrigin.Begin);
messageStream.SetLength (0); messageStream.SetLength (0);
} }
} }
} }
/// <summary>Counts the samples that will be skipped using the specified key stream</summary> /// <summary>Counts the samples that will be skipped using the specified key stream</summary>
/// <param name="keyStream">Key stream</param> /// <param name="keyStream">Key stream</param>
/// <param name="messageLength">Length of the message</param> /// <param name="messageLength">Length of the message</param>
/// <returns>Minimum length (in samples) of an audio file</returns> /// <returns>Minimum length (in samples) of an audio file</returns>
public static long CheckKeyForMessage (Stream keyStream, long messageLength) { public static long CheckKeyForMessage (Stream keyStream, long messageLength) {
long messageLengthBits = messageLength * 8; long messageLengthBits = messageLength * 8;
long countRequiredSamples = 0; long countRequiredSamples = 0;
if (messageLengthBits > keyStream.Length) { if (messageLengthBits > keyStream.Length) {
long keyLength = keyStream.Length; long keyLength = keyStream.Length;
// read existing key // read existing key
byte[] keyBytes = new byte[keyLength]; byte[] keyBytes = new byte[keyLength];
keyStream.Read (keyBytes, 0, keyBytes.Length); keyStream.Read (keyBytes, 0, keyBytes.Length);
// Every byte stands for the distance between two useable samples. // Every byte stands for the distance between two useable samples.
// The sum of those distances is the required count of samples. // The sum of those distances is the required count of samples.
countRequiredSamples = SumKeyArray (keyBytes); countRequiredSamples = SumKeyArray (keyBytes);
// The key must be repeated, until every bit of the message has a key byte. // The key must be repeated, until every bit of the message has a key byte.
double countKeyCopies = messageLengthBits / keyLength; double countKeyCopies = messageLengthBits / keyLength;
countRequiredSamples = (long) (countRequiredSamples * countKeyCopies); countRequiredSamples = (long) (countRequiredSamples * countKeyCopies);
} else { } else {
byte[] keyBytes = new byte[messageLengthBits]; byte[] keyBytes = new byte[messageLengthBits];
keyStream.Read (keyBytes, 0, keyBytes.Length); keyStream.Read (keyBytes, 0, keyBytes.Length);
countRequiredSamples = SumKeyArray (keyBytes); countRequiredSamples = SumKeyArray (keyBytes);
} }
keyStream.Seek (0, SeekOrigin.Begin); keyStream.Seek (0, SeekOrigin.Begin);
return countRequiredSamples; return countRequiredSamples;
} }
private static long SumKeyArray (byte[] values) { private static long SumKeyArray (byte[] values) {
long sum = 0; long sum = 0;
foreach (int value in values) { // '0' causes a distance of one sample, foreach (int value in values) { // '0' causes a distance of one sample,
// every other key causes a distance of its exact value. // every other key causes a distance of its exact value.
sum += (value == 0) ? 1 : value; sum += (value == 0) ? 1 : value;
} }
return sum; return sum;
} }
/// <summary> /// <summary>
/// Read the next byte of the key stream. /// Read the next byte of the key stream.
/// Reset the stream if it is too short. /// Reset the stream if it is too short.
/// </summary> /// </summary>
/// <param name="keyStream">The key stream</param> /// <param name="keyStream">The key stream</param>
/// <returns>The next key byte</returns> /// <returns>The next key byte</returns>
private static byte GetKeyValue (Stream keyStream) { private static byte GetKeyValue (Stream keyStream) {
int keyValue; int keyValue;
if ((keyValue = keyStream.ReadByte ()) < 0) { if ((keyValue = keyStream.ReadByte ()) < 0) {
keyStream.Seek (0, SeekOrigin.Begin); keyStream.Seek (0, SeekOrigin.Begin);
keyValue = keyStream.ReadByte (); keyValue = keyStream.ReadByte ();
if (keyValue == 0) { keyValue = 1; } if (keyValue == 0) { keyValue = 1; }
} }
return (byte) keyValue; return (byte) keyValue;
} }
} }
} }

View File

@@ -1,2 +1,2 @@
add -m "ArgleBargle" -k "C:\dev\working\stegano\mylib\keyfile.txt" -i "C:\dev\working\stegano\mylib\candidate.wav" -o "C:\dev\working\stegano\mylib\out.wav" add -m "ArgleBargle" -k "C:\dev\working\stegano\mylib\keyfile.txt" -i "C:\dev\working\stegano\mylib\candidate.wav" -o "C:\dev\working\stegano\mylib\out.wav"
extract -k "C:\dev\working\stegano\mylib\keyfile.txt" -i "C:\dev\working\stegano\mylib\out.wav" extract -k "C:\dev\working\stegano\mylib\keyfile.txt" -i "C:\dev\working\stegano\mylib\out.wav"

View File

@@ -1,10 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
<TargetFramework>netcoreapp1.1</TargetFramework> <TargetFramework>netcoreapp1.1</TargetFramework>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.Extensions.CommandLineUtils" Version="1.1.0" /> <PackageReference Include="Microsoft.Extensions.CommandLineUtils" Version="1.1.0" />
<PackageReference Include="System.Runtime.InteropServices" Version="4.3.0" /> <PackageReference Include="System.Runtime.InteropServices" Version="4.3.0" />
</ItemGroup> </ItemGroup>
</Project> </Project>