diff --git a/.github/workflows/linux-cmake.yml b/.github/workflows/linux-cmake.yml new file mode 100644 index 0000000..ebefa49 --- /dev/null +++ b/.github/workflows/linux-cmake.yml @@ -0,0 +1,47 @@ +name: Linux CMake + +on: + push: + branches: [ master ] + pull_request: + branches: [ master ] + +env: + # Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.) + BUILD_TYPE: Release + +jobs: + build: + # The CMake configure and build commands are platform agnostic and should work equally + # well on Windows or Mac. You can convert this to a matrix build if you need + # cross-platform coverage. + # See: https://docs.github.com/en/free-pro-team@latest/actions/learn-github-actions/managing-complex-workflows#using-a-build-matrix + # OS Supported: https://docs.github.com/en/actions/using-github-hosted-runners/about-github-hosted-runners#supported-runners-and-hardware-resources + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ubuntu-20.04, ubuntu-18.04, ubuntu-16.04] + + steps: + - uses: actions/checkout@v2 + + - name: Configure CMake + # Configure CMake in a 'build' subdirectory. `CMAKE_BUILD_TYPE` is only required if you are using a single-configuration generator such as make. + # See https://cmake.org/cmake/help/latest/variable/CMAKE_BUILD_TYPE.html?highlight=cmake_build_type + run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} + + - name: Build + # Build your program with the given configuration + run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}} + + - name: Test + working-directory: ${{github.workspace}}/build + # Execute tests defined by the CMake configuration. + # See https://cmake.org/cmake/help/latest/manual/ctest.1.html for more detail + run: ctest -C ${{env.BUILD_TYPE}} + + - name: Upload a Build Artifact + uses: actions/upload-artifact@v2 + with: + name: Package + path: ${{github.workspace}}/build \ No newline at end of file diff --git a/.github/workflows/macos-cmake.yml b/.github/workflows/macos-cmake.yml new file mode 100644 index 0000000..91509d7 --- /dev/null +++ b/.github/workflows/macos-cmake.yml @@ -0,0 +1,44 @@ +name: macOS CMake + +on: + push: + branches: [ master ] + pull_request: + branches: [ master ] + +env: + # Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.) + BUILD_TYPE: Release + +jobs: + build: + # The CMake configure and build commands are platform agnostic and should work equally + # well on Windows or Mac. You can convert this to a matrix build if you need + # cross-platform coverage. + # See: https://docs.github.com/en/free-pro-team@latest/actions/learn-github-actions/managing-complex-workflows#using-a-build-matrix + # OS Supported: https://docs.github.com/en/actions/using-github-hosted-runners/about-github-hosted-runners#supported-runners-and-hardware-resources + runs-on: macos-10.15 + + steps: + - uses: actions/checkout@v2 + + - name: Configure CMake + # Configure CMake in a 'build' subdirectory. `CMAKE_BUILD_TYPE` is only required if you are using a single-configuration generator such as make. + # See https://cmake.org/cmake/help/latest/variable/CMAKE_BUILD_TYPE.html?highlight=cmake_build_type + run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} + + - name: Build + # Build your program with the given configuration + run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}} + + - name: Test + working-directory: ${{github.workspace}}/build + # Execute tests defined by the CMake configuration. + # See https://cmake.org/cmake/help/latest/manual/ctest.1.html for more detail + run: ctest -C ${{env.BUILD_TYPE}} + + - name: Upload a Build Artifact + uses: actions/upload-artifact@v2 + with: + name: Package + path: ${{github.workspace}}/build \ No newline at end of file diff --git a/.github/workflows/windows-cmake.yml b/.github/workflows/windows-cmake.yml new file mode 100644 index 0000000..5f5e893 --- /dev/null +++ b/.github/workflows/windows-cmake.yml @@ -0,0 +1,47 @@ +name: Windows CMake + +on: + push: + branches: [ master ] + pull_request: + branches: [ master ] + +env: + # Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.) + BUILD_TYPE: Release + +jobs: + build: + # The CMake configure and build commands are platform agnostic and should work equally + # well on Windows or Mac. You can convert this to a matrix build if you need + # cross-platform coverage. + # See: https://docs.github.com/en/free-pro-team@latest/actions/learn-github-actions/managing-complex-workflows#using-a-build-matrix + # OS Supported: https://docs.github.com/en/actions/using-github-hosted-runners/about-github-hosted-runners#supported-runners-and-hardware-resources + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [windows-2019, windows-2016] + + steps: + - uses: actions/checkout@v2 + + - name: Configure CMake + # Configure CMake in a 'build' subdirectory. `CMAKE_BUILD_TYPE` is only required if you are using a single-configuration generator such as make. + # See https://cmake.org/cmake/help/latest/variable/CMAKE_BUILD_TYPE.html?highlight=cmake_build_type + run: cmake -B ${{github.workspace}}/build -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} + + - name: Build + # Build your program with the given configuration + run: cmake --build ${{github.workspace}}/build --config ${{env.BUILD_TYPE}} + + - name: Test + working-directory: ${{github.workspace}}/build + # Execute tests defined by the CMake configuration. + # See https://cmake.org/cmake/help/latest/manual/ctest.1.html for more detail + run: ctest -C ${{env.BUILD_TYPE}} + + - name: Upload a Build Artifact + uses: actions/upload-artifact@v2 + with: + name: Package + path: ${{github.workspace}}/build \ No newline at end of file diff --git a/.gitignore b/.gitignore index 170cb77..a957afc 100644 --- a/.gitignore +++ b/.gitignore @@ -1,20 +1,73 @@ +# Created by https://www.toptal.com/developers/gitignore/api/intellij+all,visualstudio,visualstudiocode,c++,c,cmake,python +# Edit at https://www.toptal.com/developers/gitignore?templates=intellij+all,visualstudio,visualstudiocode,c++,c,cmake,python + +### C ### # Prerequisites *.d -# Compiled Object files -*.slo -*.lo +# Object files *.o +*.ko *.obj +*.elf + +# Linker output +*.ilk +*.map +*.exp # Precompiled Headers *.gch *.pch -# Compiled Dynamic libraries +# Libraries +*.lib +*.a +*.la +*.lo + +# Shared objects (inc. Windows DLLs) +*.dll *.so +*.so.* *.dylib -*.dll + +# Executables +*.exe +*.out +*.app +*.i*86 +*.x86_64 +*.hex + +# Debug files +*.dSYM/ +*.su +*.idb +*.pdb + +# Kernel Module Compile Results +*.mod* +*.cmd +.tmp_versions/ +modules.order +Module.symvers +Mkfile.old +dkms.conf + +### C++ ### +# Prerequisites + +# Compiled Object files +*.slo + +# Precompiled Headers + +# Linker files + +# Debugger Files + +# Compiled Dynamic libraries # Fortran module files *.mod @@ -22,13 +75,627 @@ # Compiled Static libraries *.lai -*.la -*.a -*.lib # Executables -*.exe -*.out -*.app -a.out +### CMake ### +CMakeLists.txt.user +CMakeCache.txt +CMakeFiles +CMakeScripts +Testing +Makefile +cmake_install.cmake +install_manifest.txt +compile_commands.json +CTestTestfile.cmake +_deps +CMakeUserPresets.json + +### CMake Patch ### +# External projects +*-prefix/ + +### Intellij+all ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### Intellij+all Patch ### +# Ignores the whole .idea folder and all .iml files +# See https://github.com/joeblau/gitignore.io/issues/186 and https://github.com/joeblau/gitignore.io/issues/360 + +.idea/ + +# Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-249601023 + +*.iml +modules.xml +.idea/misc.xml +*.ipr + +# Sonarlint plugin +.idea/sonarlint + +### Python ### +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +pytestdebug.log + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ +doc/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +#poetry.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +# .env +.env/ +.venv/ +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ +pythonenv* + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# operating system-related files +*.DS_Store #file properties cache/storage on macOS +Thumbs.db #thumbnail cache on Windows + +# profiling data +.prof + + +### VisualStudioCode ### +.vscode/* +!.vscode/tasks.json +!.vscode/launch.json +*.code-workspace + +### VisualStudioCode Patch ### +# Ignore all local history of files +.history +.ionide + +### VisualStudio ### +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.meta +*.iobj +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*[.json, .xml, .info] + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# 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 +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# End of https://www.toptal.com/developers/gitignore/api/intellij+all,visualstudio,visualstudiocode,c++,c,cmake,python \ No newline at end of file diff --git a/Base64.cpp b/Base64.cpp deleted file mode 100644 index 7481ec6..0000000 --- a/Base64.cpp +++ /dev/null @@ -1,220 +0,0 @@ -/////////////////////////////////////////////////////////////////////// -// Base64.cpp declares class that encodes binary data into a string // -// ver 2.0 and decodes the string back to binary data // -// // -// Language: Visual C++, ver 7.1 // -// Platfrom: Dell Dimension 8300, Windows XP, SP1 // -// Application: CSE687 - Object Oriented Design, Spring 2004 // -// Author: Jim Fawcett, CST 2-187, Syracuse University // -// (315) 443-3948, jfawcett@twcny.rr.com // -/////////////////////////////////////////////////////////////////////// -// based on: // -//********************************************************************* -//* Base64 - a simple base64 encoder and decoder. -//* -//* Copyright (c) 1999, Bob Withers - bwit@pobox.com -//* -//* This code may be freely used for any purpose, either personal -//* or commercial, provided the authors copyright notice remains -//* intact. -//********************************************************************* - -#include "Base64.h" -#include - -const char fillchar = '='; - - // 00000000001111111111222222 - // 01234567890123456789012345 -static std::string cvt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - - // 22223333333333444444444455 - // 67890123456789012345678901 - "abcdefghijklmnopqrstuvwxyz" - - // 555555556666 - // 234567890123 - "0123456789+/"; - -// -//----< convert vector of bytes to std::string >--------------------- - -std::string Base64::encode(const std::vector& data) -{ - std::string::size_type i; - char c; - unsigned int len = data.size(); - std::string ret; - - for (i = 0; i < len; ++i) - { - c = (data[i] >> 2) & 0x3f; - ret.append(1, cvt[c]); - c = (data[i] << 4) & 0x3f; - if (++i < len) - c |= (data[i] >> 4) & 0x0f; - - ret.append(1, cvt[c]); - if (i < len) - { - c = (data[i] << 2) & 0x3f; - if (++i < len) - c |= (data[i] >> 6) & 0x03; - - ret.append(1, cvt[c]); - } - else - { - ++i; - ret.append(1, fillchar); - } - - if (i < len) - { - c = data[i] & 0x3f; - ret.append(1, cvt[c]); - } - else - { - ret.append(1, fillchar); - } - } - - return(ret); -} -// -//----< convert std::string to vector of bytes >--------------------- - -std::vector Base64::decode(const std::string& data) -{ - std::string::size_type i; - char c; - char c1; - std::string::size_type len = data.length(); - std::vector ret; - - for (i = 0; i < len; ++i) - { - c = (char) cvt.find(data[i]); - ++i; - c1 = (char) cvt.find(data[i]); - c = (c << 2) | ((c1 >> 4) & 0x3); - ret.push_back(c); - if (++i < len) - { - c = data[i]; - if (fillchar == c) - break; - c = (char) cvt.find(c); - c1 = ((c1 << 4) & 0xf0) | ((c >> 2) & 0xf); - ret.push_back(c1); - } - if (++i < len) - { - c1 = data[i]; - if (fillchar == c1) - break; - c1 = (char) cvt.find(c1); - c = ((c << 6) & 0xc0) | c1; - ret.push_back(c); - } - } - return(ret); -} - -// -//----< create encoded string from binary file contents >------------ - -std::string Base64::encodeFromFile(const std::string& inFileName) -{ - std::ifstream in; - in.open(inFileName.c_str(),std::ios::binary); - if(!in.good()) - { - throw std::invalid_argument(std::string("can't open file ") + inFileName); - } - std::vector fBytes; - while(in.good()) - fBytes.push_back(in.get()); - fBytes.pop_back(); - in.close(); - - return Base64::encode(fBytes); -} -//----< create new binary file from encoded string >----------------- - -void Base64::decodeToFile( - const std::string& outFileName, const std::string& encodedString - ) -{ - std::ofstream out; - out.open(outFileName.c_str(),std::ios::binary); - if(!out.good()) - { - throw std::invalid_argument(std::string("can't open file ") + outFileName); - } - std::vector fdecodedBytes = Base64::decode(encodedString); - - for(unsigned int i=0; i -//#include - -void main() -{ - std::cout << "\n Demonstrate Base64 Encoding and Decoding " - << "\n ==========================================\n"; - - /////////////////////////////////////////////////////////////////// - // encoding ascii string - - std::string msg - = "We're not in Kansas anymore, Toto!"; - - std::vector vmsg(msg.begin(),msg.end()); - std::string encodedMsg = Base64::encode(vmsg); - std::vector vdecoded = Base64::decode(encodedMsg); - std::string decodedMsg(vdecoded.begin(),vdecoded.end()); - - std::cout << "\n original: " << msg; - std::cout << "\n encoded: " << encodedMsg; - std::cout << "\n decoded: " << decodedMsg; - std::cout << "\n"; - - //////////////////////////////////////////////////////////////////// - // encoding binary file - - const std::string ifile = "debug\\Base64Encoding.exe"; - const std::string ofile1 = "debug\\temp.dat"; - const std::string ofile2 = "debug\\temp.exe"; - - try - { - std::cout << "\n creating encoded string from binary file " - << ifile << std::endl; - std::string encodedString = Base64::encodeFromFile(ifile); - - std::string temp(encodedString.begin(), encodedString.begin() + 50); - std::cout << "\n First fifty bytes of encoded string:\n " - << temp << "\n"; - - std::cout << "\n writing decoded string to binary file " - << ofile2 << "\n"; - Base64::decodeToFile(ofile2,encodedString); - - std::cout << "\n Use fc to demonstrate that " - << ifile << "\n is identical to " << ofile2 << "\n\n"; - } - catch(std::exception& e) - { - std::cout << "\n " << e.what() << "\n\n"; - } -} - -#endif diff --git a/Base64.h b/Base64.h deleted file mode 100644 index 7d5b9be..0000000 --- a/Base64.h +++ /dev/null @@ -1,75 +0,0 @@ -#ifndef BASE64_H -#define BASE64_H -/////////////////////////////////////////////////////////////////////// -// Base64.h - declares class that encodes binary data into a string // -// ver 2.0 and decodes the string back to binary data // -// // -// Language: Visual C++, ver 7.1 // -// Platfrom: Dell Dimension 8300, Windows XP, SP1 // -// Application: CSE687 - Object Oriented Design, Spring 2004 // -// Author: Jim Fawcett, CST 2-187, Syracuse University // -// (315) 443-3948, jfawcett@twcny.rr.com // -/////////////////////////////////////////////////////////////////////// -// based on: // -//********************************************************************* -//* C_Base64 - a simple base64 encoder and decoder. -//* -//* Copyright (c) 1999, Bob Withers - bwit@pobox.com -//* -//* This code may be freely used for any purpose, either personal -//* or commercial, provided the authors copyright notice remains -//* intact. -//********************************************************************* -/* - * Module Operation: - * ================= - * The Base64 class provides static encode and decode functions that - * use base64 encoding to render a vector of bytes into a std::string - * of ASCII characters and back again. This supports the transmission - * of binary data as XML messages. - * - * Public Interface: - * ================= - * std::vector vBytes; - * // vBytes filed, perhaps from a file - * std::string encodedString = Base64::encode(vBytes); - * // do something with string, perhaps send as XML message - * std::vector vDecodedBytes = Base64::decode(encodedMsg); - * - * Build Process: - * ============== - * Required files - Base64.h, Base64.cpp - * - * compiler command - cl /EHsc /DTEST_BASE64 Base64.cpp - * - * Maintenance History: - * ==================== - * ver 1.0 : 25 Mar 04 - * - first release, based on code by Bob Withers - * ver 2.0 : 20 Apr 04 - * - changed interface from std::strings for both input and output - * to std::vector for binary data and std::string for its - * endcoding. Test stub shows how to use this to encode binary - * files. - * - * Planned Modifications: - * ====================== - * - add functions to support chunking of large files - */ - -// -#include -#include - -class Base64 -{ -public: - static std::string encode(const std::vector& data); - static std::vector decode(const std::string& data); - static std::string encodeFromFile(const std::string& inFileName); - static void decodeToFile( - const std::string& outFileName, const std::string& encodedString - ); -}; - -#endif diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..5252d86 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,12 @@ +cmake_minimum_required(VERSION 3.19) +project(easy_encryption) + +option(EASY_ENCRYPTION_EXAMPLES "Build examples?" ON) + +set(CMAKE_CXX_STANDARD 98) + +add_library(${PROJECT_NAME} STATIC src/base64/Base64.cc src/vigenere/Vigenere.cc src/EasyEncryption.cc) + +if(EASY_ENCRYPTION_EXAMPLES) + add_subdirectory(examples) +endif(EASY_ENCRYPTION_EXAMPLES) diff --git a/README.md b/README.md index 097ab3b..90fe471 100644 --- a/README.md +++ b/README.md @@ -1,34 +1,42 @@ +![](banner.jpg) +[![](https://img.shields.io/static/v1?label=C%2B%2B%20Version&message=98&color=%2300599C&logo=c%2B%2B&logoColor=%23FFFFFF&style=flat-square)](https://www.cplusplus.com/doc/oldtutorial/) +[![](https://img.shields.io/github/actions/workflow/status/philipperemy/easy-encryption/windows-cmake.yml?branch=master&label=Windows%20Build&logo=windows&logoColor=%23FFFFFF&style=flat-square)](https://github.com/philipperemy/easy-encryption/actions/workflows/windows-cmake.yml) +[![](https://img.shields.io/github/actions/workflow/status/philipperemy/easy-encryption/linux-cmake.yml?branch=master&label=Linux%20Build&logo=linux&logoColor=%23FFFFFF&style=flat-square)](https://github.com/philipperemy/easy-encryption/actions/workflows/linux-cmake.yml) +[![](https://img.shields.io/github/actions/workflow/status/philipperemy/easy-encryption/macos-cmake.yml?branch=master&label=macOS%20Build&logo=apple&logoColor=%23FFFFFF&style=flat-square)](https://github.com/philipperemy/easy-encryption/actions/workflows/macos-cmake.yml) + # Easy Encryption -A very simple standalone C++ module (API) to obfuscate/deobfuscate strings based on B64 and Vigenere ciper (symmetric cipher). +A very simple standalone C++98 library to obfuscate/deobfuscate strings based on Base64 and Vigenere cipher (Symmetric cipher). **DISCLAIMER: This encryption is NOT secure and can be used as a "cheap way" to obfuscate some messages in a communication channel. If you need a solid and unbreakable encryption, please use a widely adopted standard and well researched cipher like AES-GCM.** You can find more information there: [pyca](https://github.com/pyca/cryptography). - It works as follows: - -- Alice encodes in base64 the message, then uses the Vigenere private key to encrypt the message. +- Alice encodes in Base64 the message, then uses the Vigenere private key to encrypt the message. - The encrypted message is sent through an unsecured channel. -- Bob gets the message and decrypts it with the Vigenere private key. He then decodes it with base64. +- Bob gets the message and decrypts it with the Vigenere private key, and then decodes it with Base64. Diagram summary: -_______________________________________________________________________________________________________________ -**Message -> B64 ENCODE -> VIGENERE ENCRYPT -> encrypted message -> VIGENERE DECRYPT -> B64 DECODE -> Message** -_______________________________________________________________________________________________________________ +___ +**Message -> Base64 ENCODE -> Vigenere ENCRYPT -> Encrypted Message -> Vigenere DECRYPT -> Base64 DECODE -> Message** +___ -The reason why we apply b64 encode BEFORE Vigenere is because it's very easy for somebody to apply a b64 decode and see about the structure of the message. For example, if we send `{"hello":123}`, an attacker can sniff the message, b64 decode the message and get `{"qsggn":ygf}`. Of course the attacker still needs the Vigenere cipher key, but at least, he can get a pretty clear idea that JSON format messages are sent in the communication channel. The way to avoid this is to encode first in b64 then encrypt it with the Vigenere key. If the attacker tries to b64 decode first, it will see a random string of weird characters. +The reason why we apply Base64 encode **BEFORE** Vigenere is because it's very easy for somebody to apply a Base64 decode and see about the structure of the message. For example, if we send `{"hello":123}`, an attacker can sniff the message, Base64 decode the message and get `{"qsggn":ygf}`. Of course the attacker still needs the Vigenere cipher key, but at least, he can get a pretty clear idea that JSON format messages are sent in the communication channel. The way to avoid this is to encode first in Base64 then encrypt it with the Vigenere key. If the attacker tries to Base64 decode first, it will see a random string of weird characters. ## API ### C++ +- **Header** _(Always include this when you want to encrypt/decrypt something.)_ +```c++ +#include "/EasyEncryption.h" +``` - **Encrypt message** ```c++ -std::string encrypt(std::string& msg, std::string& key) +std::string EasyEncryption::encrypt(const std::string &encryptedString, const std::string &key) ``` - **Decrypt message** ```c++ -std::string decrypt(std::string& encrypted_msg, std::string& key) +std::string EasyEncryption::decrypt(const std::string &encryptedString, const std::string &key) ``` ### Python @@ -44,56 +52,10 @@ wrapper.decrypt(encrypted_message, key): returns decrypted message ``` ## Compilation and execution -```bash -g++ cl.cpp Base64.cpp -./a.out "Hello world" MYPRIVATEKEY 0 -``` - -The encrypted message is: `ttz9JqxZHBClNtu=`. - -```bash -./a.out ttz9JqxZHBClNtu= MYPRIVATEKEY 1 -``` - -The decrypted message is `Hello world`. +To compile this project, just add the files that are inside the "src" into your project, then give import to them and the magic happens! ## Python wrapper - +To run it in Python, you need to compile the example that is located in "examples/application.cpp". ```bash -g++ cl.cpp Base64.cpp python3 wrapper.py ``` - -## Example - Encoding/Decoding JSON format - -### Source code -```c++ -#include -#include -#include -#include -#include -#include -#include "encrypt.h" - -using namespace std; - -int main() { - // std::string msg = "HELLO WORLD"; - std::string msg = "{\"id\":1,\"method\":\"service.subscribe\",\"params\":[\"myapp/0.1c\", null,\"0.0.0.0\",\"80\"]}"; - std::string key = "THISISMYKEY"; - std::cout << " message to send: " << msg << std::endl; - std::string encrypted_msg = encrypt(msg, key); - std::cout << "encrypted message: " << encrypted_msg << std::endl; - std::string decrypted_msg = decrypt(encrypted_msg, key); - std::cout << "decrypted message: " << decrypted_msg << std::endl; - return 0; -} -``` - -### Output -``` - message to send: {"id":1,"method":"service.subscribe","params":["myapp/0.1c", null,"0.0.0.0","80"]} -encrypted message: X5g7wjjTllj1ItCxShWUb77PKJsfP VNMAB7VtqaLCccGTr0ijkjxqw0IutQvXfSFK4OKo8cnpD1Lge0pdMCZf0fqQ8bjjFjkNn1h pBtdwNJD== -decrypted message: {"id":1,"method":"service.subscribe","params":["myapp/0.1c", null,"0.0.0.0","80"]} -``` diff --git a/banner.jpg b/banner.jpg new file mode 100644 index 0000000..d0ab00a Binary files /dev/null and b/banner.jpg differ diff --git a/cl.cpp b/cl.cpp deleted file mode 100644 index 8dfe187..0000000 --- a/cl.cpp +++ /dev/null @@ -1,31 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include "encrypt.h" - -using namespace std; - -int main(int argc, char** argv) { - - if(argc != 4) { - std::cout << "Usage: ./a.out message key (0:encrypt|1:decrypt)" << std::endl; - std::cout << "./a.out \"Hello world\" MYPRIVATEKEY 0" << std::endl; - std::cout << "./a.out ttz9JqxZHBClNtu= MYPRIVATEKEY 1" << std::endl; - return -1; - } - - std::string msg = argv[1]; - std::string key = argv[2]; - int encrypt_flag = atoi(argv[3]); - - if(encrypt_flag == 0) { - std::cout << encrypt(msg, key) << std::endl; - } else { - std::cout << decrypt(msg, key) << std::endl; - } - - return 0; -} diff --git a/encrypt.h b/encrypt.h deleted file mode 100644 index 982fa45..0000000 --- a/encrypt.h +++ /dev/null @@ -1,102 +0,0 @@ -#include "Base64.h" -#include "vigenere.h" -#include -#include - - -std::string encrypt(std::string& msg, std::string& key) -{ - std::vector msg2(msg.begin(), msg.end()); - std::string b64_str = Base64::encode(msg2); - std::string vigenere_msg = encrypt_vigenere(b64_str, key); - return vigenere_msg; -} - -// https://stackoverflow.com/questions/17316506/strip-invalid-utf8-from-string-in-c-c -std::string sanitize_utf8(std::string& str) -{ - int i,f_size=str.size(); - unsigned char c,c2,c3,c4; - string to; - to.reserve(f_size); - - for(i=0 ; i127 && c2<192){//valid 2byte UTF8 - if(c==194 && c2<160){//control char, skipping - ; - }else{ - to.append(1,c); - to.append(1,c2); - } - i++; - continue; - } - }else if(c<240 && i+2127 && c2<192 && c3>127 && c3<192){//valid 3byte UTF8 - to.append(1,c); - to.append(1,c2); - to.append(1,c3); - i+=2; - continue; - } - }else if(c<245 && i+3127 && c2<192 && c3>127 && c3<192 && c4>127 && c4<192){//valid 4byte UTF8 - to.append(1,c); - to.append(1,c2); - to.append(1,c3); - to.append(1,c4); - i+=3; - continue; - } - } - //invalid UTF8, converting ASCII (c>245 || string too short for multi-byte)) - to.append(1,(unsigned char)195); - to.append(1,c-64); - } - return to; -} - - -std::string decrypt(std::string& encrypted_msg, std::string& key) -{ - std::string newKey = extend_key(encrypted_msg, key); - std::string b64_encoded_str = decrypt_vigenere(encrypted_msg, newKey); - std::vector b64_decode_vec = Base64::decode(b64_encoded_str); - std::string b64_decode_str(b64_decode_vec.begin(), b64_decode_vec.end()); - return sanitize_utf8(b64_decode_str); -} diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt new file mode 100644 index 0000000..f2a860c --- /dev/null +++ b/examples/CMakeLists.txt @@ -0,0 +1,6 @@ +link_libraries(${PROJECT_NAME}) + +add_executable(application application.cpp) +add_executable(application_main main.cpp) +add_executable(application_base64 main_base64.cpp) +add_executable(application_vigenere main_vigenere.cpp) diff --git a/examples/application.cpp b/examples/application.cpp new file mode 100644 index 0000000..5dc4b82 --- /dev/null +++ b/examples/application.cpp @@ -0,0 +1,27 @@ +#include +#include + +#include "../src/EasyEncryption.h" + +int main(int argc, char **argv) { + if (argc != 4) { + std::cout << "Usage: ./a.out message key (0:encrypt|1:decrypt)" << std::endl + << "./a.out \"Hello world\" MYPRIVATEKEY 0" << std::endl + << "./a.out ttz9JqxZHBClNtu= MYPRIVATEKEY 1" << std::endl; + + return -1; + } + + std::string msg = argv[1]; + std::string key = argv[2]; + int encrypt_flag = 0; + + std::stringstream(argv[3]) >> encrypt_flag; + + if (!encrypt_flag) + std::cout << EasyEncryption::encrypt(msg, key) << std::endl; + else + std::cout << EasyEncryption::decrypt(msg, key) << std::endl; + + return 0; +} diff --git a/examples/main.cpp b/examples/main.cpp new file mode 100644 index 0000000..833873c --- /dev/null +++ b/examples/main.cpp @@ -0,0 +1,22 @@ +#include +#include "../src/EasyEncryption.h" + +using namespace easy::encryption; + +int main() { + std::string msg = "{\"id\":1,\"method\":\"service.subscribe\",\"params\":[\"myapp/0.1c\", null,\"0.0.0.0\",\"80\"]}"; + std::string key = "THISISMYKEY"; + + std::string encryptedMsg = EasyEncryption::encrypt(msg, key); + std::string decryptedMsg = EasyEncryption::decrypt(encryptedMsg, key); + + std::cout << "Easy Encryption =================================" << std::endl + << "Key: " << key << std::endl + << "Original Message: " << msg << std::endl + << "Encrypted Message: " << encryptedMsg << std::endl + << "Decrypted Message: " << decryptedMsg << std::endl + << "Is message identical: " << (msg == decryptedMsg ? "True" : "False") << std::endl + << "=================================================" << std::endl; + + return 0; +} diff --git a/examples/main_base64.cpp b/examples/main_base64.cpp new file mode 100644 index 0000000..6aeff3d --- /dev/null +++ b/examples/main_base64.cpp @@ -0,0 +1,20 @@ +#include +#include "../src/base64/Base64.h" + +using namespace easy::encryption; + +int main() { + std::string msg = "HELLO WORLD"; + + std::string encodedMsg = Base64::encode(msg); + std::string decodedMsg = Base64::decode(encodedMsg); + + std::cout << "Base64 =================================" << std::endl + << "Original Message: " << msg << std::endl + << "Encoded Message: " << encodedMsg << std::endl + << "Decoded Message: " << decodedMsg << std::endl + << "Is message identical: " << (msg == decodedMsg ? "True" : "False") << std::endl + << "========================================" << std::endl; + + return 0; +} diff --git a/examples/main_vigenere.cpp b/examples/main_vigenere.cpp new file mode 100644 index 0000000..778c917 --- /dev/null +++ b/examples/main_vigenere.cpp @@ -0,0 +1,22 @@ +#include +#include "../src/vigenere/Vigenere.h" + +using namespace easy::encryption; + +int main() { + std::string msg = "HELLO WORLD"; + std::string key = "THISISALONGPRIVATEKEY"; + + std::string encryptedMsg = Vigenere::encrypt(msg, key); + std::string decryptedMsg = Vigenere::decrypt(encryptedMsg, key); + + std::cout << "Vigenere =================================" << std::endl + << "Key: " << key << std::endl + << "Original Message: " << msg << std::endl + << "Encrypted Message: " << encryptedMsg << std::endl + << "Decrypted Message: " << decryptedMsg << std::endl + << "Is message identical: " << (msg == decryptedMsg ? "True" : "False") << std::endl + << "==========================================" << std::endl; + + return 0; +} diff --git a/main.cpp b/main.cpp deleted file mode 100644 index 4c92cbd..0000000 --- a/main.cpp +++ /dev/null @@ -1,21 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include "encrypt.h" - -using namespace std; - -int main() { - // std::string msg = "HELLO WORLD"; - std::string msg = "{\"id\":1,\"method\":\"service.subscribe\",\"params\":[\"myapp/0.1c\", null,\"0.0.0.0\",\"80\"]}"; - std::string key = "THISISMYKEY"; - std::cout << " message to send: " << msg << std::endl; - std::string encrypted_msg = encrypt(msg, key); - std::cout << "encrypted message: " << encrypted_msg << std::endl; - std::string decrypted_msg = decrypt(encrypted_msg, key); - std::cout << "decrypted message: " << decrypted_msg << std::endl; - return 0; -} diff --git a/main_vigenere.cpp b/main_vigenere.cpp deleted file mode 100644 index 6fc8e7f..0000000 --- a/main_vigenere.cpp +++ /dev/null @@ -1,29 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include "vigenere.h" -#include "b64.h" - -using namespace std; - -int main() { - - // Vigenere encoding - - std::string msg = "HELLO WORLD"; - std::string key = "THISISALONGPRIVATEKEY"; - std::string encryptedMsg = encrypt_vigenere(msg, key); - std::string newKey = extend_key(msg, key); - std::string decryptedMsg = decrypt_vigenere(encryptedMsg, newKey); - - std::cout << "Original Message : " << msg << std::endl; - std::cout << "Key : " << key << std::endl; - std::cout << "New Generated Key: " << newKey << std::endl; - std::cout << "Enc Vigenere Msg : " << encryptedMsg << std::endl; - std::cout << "Dec Vigenere Msg : " << decryptedMsg << std::endl; - - return 0; -} diff --git a/src/EasyEncryption.cc b/src/EasyEncryption.cc new file mode 100644 index 0000000..ed4a777 --- /dev/null +++ b/src/EasyEncryption.cc @@ -0,0 +1,9 @@ +#include "EasyEncryption.h" + +std::string EasyEncryption::encrypt(const std::string &decryptedString, const std::string &key) { + return Vigenere::encrypt(Base64::encode(decryptedString), key); +} + +std::string EasyEncryption::decrypt(const std::string &encryptedString, const std::string &key) { + return Base64::decode(Vigenere::decrypt(encryptedString, key)); +} diff --git a/src/EasyEncryption.h b/src/EasyEncryption.h new file mode 100644 index 0000000..27d42c4 --- /dev/null +++ b/src/EasyEncryption.h @@ -0,0 +1,17 @@ +#pragma once + +#include "base64/Base64.h" +#include "vigenere/Vigenere.h" + +using namespace easy::encryption; +namespace easy { + namespace encryption { + + class EasyEncryption { + public: + static std::string encrypt(const std::string &decryptedString, const std::string &key); + static std::string decrypt(const std::string &encryptedString, const std::string &key); + }; + + } +} diff --git a/src/EasyEncryptionConsts.h b/src/EasyEncryptionConsts.h new file mode 100644 index 0000000..6200f15 --- /dev/null +++ b/src/EasyEncryptionConsts.h @@ -0,0 +1,7 @@ +#pragma once + +static const int BASE64_AVAILABLE_CHARS_SIZE = 65; +static const char BASE64_AVAILABLE_CHARS[BASE64_AVAILABLE_CHARS_SIZE] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/"; + +static const int VIGENERE_AVAILABLE_CHARS_SIZE = 63; +static const char VIGENERE_AVAILABLE_CHARS[VIGENERE_AVAILABLE_CHARS_SIZE] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; diff --git a/src/base64/Base64.cc b/src/base64/Base64.cc new file mode 100644 index 0000000..316f55b --- /dev/null +++ b/src/base64/Base64.cc @@ -0,0 +1,87 @@ +#include +#include "Base64.h" + +using namespace easy::encryption; + +int Base64::index(char c) { + for (int i = 0; i < BASE64_AVAILABLE_CHARS_SIZE; ++i) + if (BASE64_AVAILABLE_CHARS[i] == c) + return i; + return -1; +} + +std::string Base64::encode(const std::string &data) { + unsigned long long int inStringLen = data.size(); + int valA = 0, valB = -6; + std::string out; + + for (int i = 0; i < inStringLen; i++) { + valA = (valA << 8) + data[i]; + valB += 8; + + while (valB >= 0) { + out.push_back(BASE64_AVAILABLE_CHARS[(valA >> valB) & 0x3F]); + valB -= 6; + } + } + + if (valB > -6) + out.push_back(BASE64_AVAILABLE_CHARS[((valA << 8) >> (valB + 8)) & 0x3F]); + + while (out.size() % 4) + out.push_back(0x3D); + + return out; +} + +std::string Base64::decode(const std::string &data) { + unsigned long long int inStringLen = data.size(); + std::string out; + + int valA = 0, valB = -8; + for (int i = 0; i < inStringLen; i++) { + int charIndex = index(data[i]); + if (charIndex < 0) break; + + valA = (valA << 6) + charIndex; + valB += 6; + + if (valB >= 0) { + out.push_back(char((valA >> valB) & 0xFF)); + valB -= 8; + } + } + + return out; +} + +std::string Base64::encodeFromFile(const std::string &inFileName) { + std::ifstream in; + in.open(inFileName.c_str(), std::ios::binary); + + if (!in.good()) + throw std::invalid_argument(std::string("can't open file ") + inFileName); + + std::string encodedBytes; + while (in.good()) + encodedBytes.push_back((char) in.get()); + + encodedBytes.erase(encodedBytes.size() - 1); // Equivalent to pop_back + in.close(); + + return Base64::encode(encodedBytes); +} + +void Base64::decodeToFile(const std::string &outFileName, const std::string &encodedString) { + std::ofstream out; + out.open(outFileName.c_str(), std::ios::binary); + + if (!out.good()) + throw std::invalid_argument(std::string("can't open file ") + outFileName); + + std::string decodedString = Base64::decode(encodedString); + for (unsigned int i = 0; i < decodedString.size(); ++i) + out.put(decodedString[i]); + + out.close(); +} diff --git a/src/base64/Base64.h b/src/base64/Base64.h new file mode 100644 index 0000000..f9dfa35 --- /dev/null +++ b/src/base64/Base64.h @@ -0,0 +1,21 @@ +#pragma once + +#include +#include +#include "../EasyEncryptionConsts.h" + +namespace easy { + namespace encryption { + + class Base64 { + public: + static std::string encode(const std::string& data); + static std::string decode(const std::string& data); + static std::string encodeFromFile(const std::string& inFileName); + static void decodeToFile(const std::string& outFileName, const std::string& encodedString); + private: + static int index(char c); + }; + + } +} diff --git a/src/vigenere/Vigenere.cc b/src/vigenere/Vigenere.cc new file mode 100644 index 0000000..c1a7a41 --- /dev/null +++ b/src/vigenere/Vigenere.cc @@ -0,0 +1,43 @@ +#include "Vigenere.h" + +using namespace easy::encryption; + +int Vigenere::index(char c) { + for (int i = 0; i < VIGENERE_AVAILABLE_CHARS_SIZE; i++) + if (VIGENERE_AVAILABLE_CHARS[i] == c) + return i; + return -1; +} + +std::string Vigenere::extend_key(const std::string &string, const std::string &key) { + unsigned long long int keyLen = key.size(); + std::string newKey(string.size(), 0x0); + + // Generating new key + for (int i = 0, j = 0; i < newKey.size(); ++i, ++j) + newKey[i] = key[j == keyLen ? j = 0 : j]; + + return newKey; +} + +std::string Vigenere::encrypt(const std::string &decryptedString, const std::string &key) { + std::string newKey = extend_key(decryptedString, key); + std::string encryptedString(decryptedString.size(), 0x0); + + // Encryption + for (int i = 0; i < encryptedString.size(); ++i) + encryptedString[i] = isalnum(decryptedString[i]) ? VIGENERE_AVAILABLE_CHARS[((index(decryptedString[i]) + index(newKey[i])) % VIGENERE_AVAILABLE_CHARS_SIZE)] : decryptedString[i]; + + return encryptedString; +} + +std::string Vigenere::decrypt(const std::string &encryptedString, const std::string &key) { + std::string newKey = extend_key(encryptedString, key); + std::string decryptedString(encryptedString.size(), 0x0); + + // Decryption + for (int i = 0; i < decryptedString.size(); ++i) + decryptedString[i] = index(encryptedString[i]) >= 0 ? VIGENERE_AVAILABLE_CHARS[(((index(encryptedString[i]) - index(newKey[i])) + VIGENERE_AVAILABLE_CHARS_SIZE) % VIGENERE_AVAILABLE_CHARS_SIZE)] : encryptedString[i]; + + return decryptedString; +} diff --git a/src/vigenere/Vigenere.h b/src/vigenere/Vigenere.h new file mode 100644 index 0000000..3d91058 --- /dev/null +++ b/src/vigenere/Vigenere.h @@ -0,0 +1,19 @@ +#pragma once + +#include +#include "../EasyEncryptionConsts.h" + +namespace easy { + namespace encryption { + + class Vigenere { + public: + static std::string extend_key(const std::string &string, const std::string &key); + static std::string encrypt(const std::string &decryptedString, const std::string &key); + static std::string decrypt(const std::string &encryptedString, const std::string &key); + private: + static int index(char c); + }; + + } +} diff --git a/vigenere.h b/vigenere.h deleted file mode 100644 index ba26628..0000000 --- a/vigenere.h +++ /dev/null @@ -1,75 +0,0 @@ -#include -#include -#include -#include -#include -#include - -using namespace std; - -std::string AVAILABLE_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 "; - -int index(char c) { - for(int ii = 0; ii < AVAILABLE_CHARS.size(); ii++) { - if(AVAILABLE_CHARS[ii] == c) { - // std::cout << ii << " " << c << std::endl; - return ii; - } - } - return -1; -} - - -std::string extend_key(std::string& msg, std::string& key) { - //generating new key - int msgLen = msg.size(); - std::string newKey(msgLen, 'x'); - int keyLen = key.size(), i, j; - for(i = 0, j = 0; i < msgLen; ++i, ++j){ - if(j == keyLen) - j = 0; - - newKey[i] = key[j]; - } - newKey[i] = '\0'; - return newKey; -} - - -std::string encrypt_vigenere(std::string& msg, std::string& key) { - int msgLen = msg.size(), keyLen = key.size(), i, j; - std::string encryptedMsg(msgLen, 'x'); - // char newKey[msgLen], encryptedMsg[msgLen], decryptedMsg[msgLen]; - - std::string newKey = extend_key(msg, key); - - //encryption - for(i = 0; i < msgLen; ++i) { - // std::cout << msg[i] << " " << isalnum(msg[i]) << std::endl; - if(isalnum(msg[i]) or msg[i] == ' ') { - encryptedMsg[i] = AVAILABLE_CHARS[((index(msg[i]) + index(newKey[i])) % AVAILABLE_CHARS.size())]; - } else { - encryptedMsg[i] = msg[i]; - } - } - - encryptedMsg[i] = '\0'; - return encryptedMsg; -} - -std::string decrypt_vigenere(std::string& encryptedMsg, std::string& newKey) { - // decryption - int msgLen = encryptedMsg.size(); - std::string decryptedMsg(msgLen, 'x'); - int i; - for(i = 0; i < msgLen; ++i) { - if(isalnum(encryptedMsg[i]) or encryptedMsg[i] == ' ') { - decryptedMsg[i] = AVAILABLE_CHARS[(((index(encryptedMsg[i]) - index(newKey[i])) + AVAILABLE_CHARS.size()) % AVAILABLE_CHARS.size())]; - } else { - decryptedMsg[i] = encryptedMsg[i]; - } - } - decryptedMsg[i] = '\0'; - return decryptedMsg; -} - diff --git a/wrapper.py b/wrapper.py index 4796120..f740e5e 100644 --- a/wrapper.py +++ b/wrapper.py @@ -1,13 +1,10 @@ import subprocess - def decrypt(message, key): - return subprocess.check_output(['./a.out', message, key, "1"]).decode('utf8').strip() - + return subprocess.check_output(['./application.out', message, key, "1"]).decode('utf8').strip() def encrypt(message, key): - return subprocess.check_output(['./a.out', message, key, "0"]).decode('utf8').strip() - + return subprocess.check_output(['./application.out', message, key, "0"]).decode('utf8').strip() if __name__ == '__main__': original_msg = 'Hello world'