Compare commits

...

126 Commits

Author SHA1 Message Date
Martchus ea0503ce62 Avoid warning about invoking function marked as nodiscard 2024-05-21 20:37:36 +02:00
Martchus 8efa6461fe Bump patch version 2024-05-21 20:37:36 +02:00
Martchus e3e7f731bf Apply change of `global.h` template 2024-04-02 11:12:34 +02:00
Martchus acdc1d80ba Allow compilation of tests when doing unity builds
Ensure all formatting overloads are always included before CppUnit's
headers
2024-02-04 20:58:45 +01:00
Martchus 3cb0812c62 Bump patch version 2024-02-04 20:42:27 +01:00
Martchus 17f6d4cfe5 Update `global.h` via updated template in c++utilities 2024-02-04 20:41:25 +01:00
Martchus fd5c19dd9f Update copyright date 2024-02-04 20:38:44 +01:00
Martchus 2e1d9a700b Apply clang-format 2023-11-21 22:10:44 +01:00
Martchus 9f134725c7 Fix handling of non-ASCII characters when resizing file 2023-11-07 23:33:46 +01:00
Martchus 3da25a39a4 Improve documentation of save/write
* Mention std::filesystem::filesystem_error explicitly
* Mention std::runtime_error last as it is the most generic exception type
* Use fully qualified class names
2023-11-07 23:00:33 +01:00
Martchus 7d8d837cb1 Increment patch version 2023-11-07 22:57:28 +01:00
Martchus 1f42f5fffb Truncate file if it became smaller in all cases 2023-11-07 16:18:41 +01:00
Martchus 962054a3fe Increment patch version 2023-11-07 16:17:42 +01:00
Martchus 282c819ea2 Avoid CMake deprecation warning by bumping version 2023-07-23 21:06:28 +02:00
Martchus 92d8324cdc Improve condition for use of `pubsetbuf`
Using this function like this seems only be possible with `libstdc++`. The
standard lib of MSVC does not support it as well. So use it only with
`libstdc++`.
2023-02-28 21:01:23 +01:00
Martchus 7bb9134fd3 Avoid unqualified calls to `std::move` 2023-02-18 19:03:29 +01:00
Martchus 9f8deafd5a Update copyright notice 2023-01-17 18:36:48 +01:00
Martchus 2e2c3ba4fc Avoid using deprecated OpenSSL functions 2022-11-03 22:29:08 +01:00
Martchus facfc879b5 Add stalebot config 2022-04-12 01:08:06 +02:00
Martchus 52a3ac32f7 Add copyright notice 2022-04-05 20:18:35 +02:00
Martchus a725550d17 Increment patch version 2022-03-15 21:40:17 +01:00
Martchus a367edc81f Clarify that license is "GPL-2-or-later" 2022-03-15 21:39:33 +01:00
Martchus 98a11787c1 Use constant for additional buffer size used to decrypt/encrypt 2021-12-11 23:51:52 +01:00
Martchus ff7dc8d772 Fix comment 2021-12-11 23:49:29 +01:00
Martchus 5ca417069a Fix compilation of AES implementation, document that is is not actually used 2021-08-22 00:17:04 +02:00
Martchus d1b7187085 Fix shadowing warning 2021-08-22 00:02:29 +02:00
Martchus 9b4fcdc2b3 Fix typos found via `codespell --skip .git -w` 2021-07-03 19:42:20 +02:00
Martchus 5935ea0691 Fix warnings 2021-03-20 21:55:40 +01:00
Martchus f7c6db0132 Use NativeFileStream and actually throw exceptions in export 2020-02-14 17:37:04 +01:00
Marius Kittler b1a55def8b Use consistent order for visibility attribute 2020-01-29 18:31:23 +01:00
Martchus 334a2093f6 Mention that CBC and OpenSSL is used 2020-01-02 20:17:02 +01:00
Martchus 463c1f871f Reformat CMake scripts against cmake-format 0.6.3 2019-12-15 19:45:47 +01:00
Martchus fb8c99b2d4 Don't suppress IO errors when writing files
* Close or flush streams explicitely so writing is not
  deferred
    * to catch errors in the right place
    * to avoid suppressing errors completely when writing
      would be deferred to the destructor invocation
* Improve comments
2019-12-15 19:43:31 +01:00
Marius Kittler 3afa954ebd Fix old namespaces being mentioned in the documentation 2019-09-04 18:47:45 +02:00
Martchus a3d104cf8b Reduce code for flag enum classes 2019-08-14 01:22:33 +02:00
Martchus d89c7b7bf1 Set project() on top-level
See https://github.com/Martchus/cpp-utilities/pull/15
2019-07-20 18:10:36 +02:00
Martchus a1b694a50b Allow creating a new file in PasswordFile::save()
to ease saving a file under a different location
2019-07-03 23:59:07 +02:00
Marius Kittler b6ad06faa2 Do not close file if not opened in PasswordFile::save() 2019-06-25 11:36:47 +02:00
Martchus a2772506a3 Adapt to changes in c++utilities 2019-06-12 21:02:09 +02:00
Martchus b323460dbb Adapt to changes in c++utilities 2019-06-10 22:44:29 +02:00
Marius Kittler 0754760b19 Adapt to c++utilities v5 2019-05-04 22:25:14 +02:00
Martchus 986ceaf567 Bump version 2019-02-17 17:07:11 +01:00
Marius Kittler 4642f56d0d Apply cmake-format 2019-02-06 18:02:40 +01:00
Marius Kittler 1d06d52f18 Add override to ~ParsingException() 2019-02-06 18:02:14 +01:00
Martchus 2828061193 Let CMake generate code for test application 2019-01-13 22:30:54 +01:00
Martchus e29457dfd0 Improve const correctness 2018-12-23 18:57:03 +01:00
Martchus a25282b3d1 Make exception c'tors/d'tors non-inline again
Otherwise it is not possible to throw/catch it accross
library boundaries under Android.
2018-12-22 02:47:33 +01:00
Martchus 42f37a1852 Fix warning about implicit conversion 2018-12-22 02:46:55 +01:00
Martchus 4412c62433 Add remark regarding PasswordFile::isEncryptionUsed() 2018-12-22 02:46:24 +01:00
Marius Kittler 292a8668bf Extend tests 2018-12-21 17:52:15 +01:00
Marius Kittler 35b09d73b2 Allow inlining simple PasswordFile methods 2018-12-21 17:33:05 +01:00
Marius Kittler 70f62bf94a Set open options
Not used yet but maybe useful later
2018-12-21 17:32:31 +01:00
Marius Kittler c04fdd6cc2 Use override 2018-12-21 17:31:50 +01:00
Marius Kittler af5d9147b4 Improve exception constructors 2018-12-21 17:31:24 +01:00
Martchus 2c856e3976 Add statistics 2018-12-21 01:12:53 +01:00
Martchus b9af93adbd Fix |= operator for flags 2018-12-19 00:14:59 +01:00
Martchus d4e24046d0 Fix includes in utils/openssl.h 2018-12-18 23:59:24 +01:00
Martchus 448c5b1a37 Improve reading/writing overall file
* Allow to hash password N times using SHA-256
* Use flags instead of bool parameter
* Expose extended header
* Fix bugs when reading/writing extended headers
* Store password as std::string

Reading files written with previous versions is still
possible. If new features are not used it is also possible
to read new files with previous versions.
2018-12-18 23:17:19 +01:00
Martchus d9edcc4083 Apply clang-format 2018-12-08 19:09:17 +01:00
Martchus ff76846e8b Don't use pubsetbuf() when using libc++
Otherwise the eof bit is set on attempt to read
2018-12-03 00:28:24 +01:00
Martchus 60d8972dcb Improve error handling when loading file
* Handle IO errors when reading internal buffer
* Throw an error when the decompressed or decrypted buffer
  is empty
2018-12-03 00:26:11 +01:00
Martchus 7fd253f895 Read directly from the vector's buffer 2018-09-08 19:50:28 +02:00
Martchus 51442d0b68 Improve coding style in PasswordFile 2018-09-08 19:50:28 +02:00
Martchus e6f66ce932 Fix warnings, improve coding style 2018-09-07 01:14:21 +02:00
Martchus 30a95e2ffc Add a separate write() method to handle file opening manually
Opening the file manually can be useful, eg. when dealing with
Androids storage access framework.
2018-09-07 00:58:40 +02:00
Martchus e265bbe733 Allow to access underlying file stream directly 2018-09-05 00:33:01 +02:00
Martchus 4c6a271eb8 Improve c'tors and d'tors
* Provide move c'tor
* Actually copy the entries and header info
* Remove useless close() in d'tor (should be called anyways)
2018-09-05 00:32:32 +02:00
Martchus f448e34cd8 Use IoUtilities::NativeFileStream in PasswordFile
* Allows to support UTF-8 characters in the path under Windows
* Allows to open a file from existing file descriptor
* Requires c++utilities to be compiled with USE_NATIVE_FILE_BUFFER
  to take effect.
2018-09-05 00:29:36 +02:00
Martchus ed872b0486 Fix typo 2018-09-04 20:24:43 +02:00
Martchus 405afe4e31 Make Field default-constructable 2018-06-13 00:40:16 +02:00
Martchus 69161989ae Fix missing std prefix 2018-06-12 21:49:16 +02:00
Martchus 968e597c24 Support "file://" protocol 2018-06-12 21:47:38 +02:00
Martchus ca9ac4f747 Make include guards more unique and consistent 2018-06-09 22:30:07 +02:00
Martchus 537c326510 Test Field 2018-06-09 22:24:03 +02:00
Martchus 132be3fd8b Fix making labels unique 2018-06-09 22:09:33 +02:00
Martchus 76e5eec85b Add tests for entry classes 2018-06-09 21:44:43 +02:00
Martchus c6dd177799 Fix NodeEntry::replaceChild() to update indices/children correctly 2018-06-09 21:18:13 +02:00
Martchus ba1e58c1e5 Fix NodeEntry::deleteChildren() to update indices correctly 2018-06-09 21:17:50 +02:00
Martchus a7b597759b Improve coding style in Io classes 2018-06-09 21:17:01 +02:00
Martchus 5eec94baac Make OpenSslRandomDevice usable with uniform_int_distribution 2018-06-09 19:47:50 +02:00
Martchus 0e40562866 Improve coding style in PasswordFile tests 2018-06-09 18:35:26 +02:00
Martchus 7c619b6d62 Fix error message for compression 2018-06-09 18:35:05 +02:00
Martchus d80cb7233a Apply clang-format 2018-03-20 20:11:31 +01:00
Martchus fbd43b86e9 Use noexcept directly, C++ 14 is required anyways 2018-03-20 20:11:13 +01:00
Martchus 2e65843687 Fix typo 2017-07-04 22:45:10 +02:00
Martchus fa38238f96 Fix compiling tests under 32-bit arch 2017-05-31 00:41:44 +02:00
Martchus 29220159fa Apply clang-format 2017-05-01 03:25:30 +02:00
Martchus d4bb111800 Extend README.md 2017-04-27 22:41:42 +02:00
Martchus cf04af93a4 Don't load OpenSSL config
* Doesn't seem to be required for just doing some AES
* OPENSSL_config(NULL) is deprecated anyways
2017-04-27 22:31:10 +02:00
Martchus 2b28fbcc66 Use CPPUNIT_ASSERT_EQUAL with C++14 string literal 2017-02-06 18:38:02 +01:00
Martchus 94bddabd36 Declare public dependencies 2016-11-08 20:02:31 +01:00
Martchus 0b9a0fe326 Fix decoration for static builds 2016-08-29 15:42:07 +02:00
Martchus a628f0383a Fix detecting static 3rd party libs 2016-08-19 16:17:26 +02:00
Martchus 78b4f9f286 Generate config header in extra module 2016-07-27 21:40:22 +02:00
Martchus dffcb742f9 Find 3rd party libs using new module 2016-07-22 01:36:23 +02:00
Martchus 5ffe22a3a9 Use workaround for GCC Bug 66145 2016-06-14 22:56:41 +02:00
Martchus c92fdf2256 Remove doxygen file (use template instead) 2016-06-10 23:58:02 +02:00
Martchus dcfadcc5d8 Add API doc 2016-06-10 23:25:21 +02:00
Martchus c6f12b31f9 added version constraints 2016-04-25 22:24:44 +02:00
Martchus d20cf3b5b1 reduce code duplication in build system
- get rid of qmake project file
- provide CMake modules for common tasks
- provide templates for *.desktop files
2016-04-16 00:51:17 +02:00
Martchus f6ebea4c49 fixed description 2016-03-10 22:18:50 +01:00
Martchus 22619af7fb added tests 2016-02-28 01:07:58 +01:00
Martchus 76b5abb5ba check whether the current file is empty before creating backup 2016-02-27 23:21:44 +01:00
Martchus 3128d31536 mingw-w64: build both, shared and static libs 2016-02-27 01:32:27 +01:00
Martchus cf15c9487f ignore *.txt.user files 2016-01-25 19:10:12 +01:00
Martchus 6879de884f ensure custom install targets don't conflict
(required when building as subdirectory)
2016-01-21 16:36:52 +01:00
Martchus 9450d6c8c2 removed creation of Windows icon 2016-01-05 17:15:47 +01:00
Martchus cadd3e6c59 updated version 2015-12-27 21:38:03 +01:00
Martchus b1076a81fe disable new ABI (can't catch ios_base::failure with new ABI) 2015-12-13 20:44:29 +01:00
Martchus 1f8eb4305c added resources 2015-12-13 20:44:09 +01:00
Martchus 840ecfb61e improved project files 2015-12-08 08:36:00 +01:00
Martchus 9e49cdfdaa added simple CMake project file 2015-12-05 22:50:00 +01:00
Martchus 6ad5c6937e updated version 2015-10-16 21:38:53 +02:00
Martchus 1834154f03 set meta data (win32) 2015-09-22 01:59:16 +02:00
Martchus bcefbb66e8 fixed includes 2015-09-06 20:33:27 +02:00
Martchus 7750466d75 updated project files 2015-08-26 21:12:09 +02:00
Martchus 083c6dadeb added .directory, docs/ 2015-07-31 01:24:31 +02:00
Martchus 807c4bfc1a provide defines for application info provided in the project file 2015-07-27 23:32:59 +02:00
Martchus a59ac8e0d6 improved project config 2015-07-18 00:41:58 +02:00
Martchus 6714631fc4 outsourced PKGBUILD files 2015-06-26 02:32:04 +02:00
Martchus b3d76635b1 added version, checking for TARGET_PREFIX variable 2015-06-24 00:59:58 +02:00
Martchus d39fd6a598 added support for reading/writing an extended header which might be
useful later
2015-06-21 21:44:07 +02:00
Martchus d82492720e updated PKGBUILD file 2015-06-08 22:09:52 +02:00
Martchus 59af736dea added readme and license file 2015-06-08 22:09:37 +02:00
Martchus b860d01b1e - added global extended header (introducing global file format version
4)
- unknown extended headers will not be just ignored anymore, they will
be read and written again when saving the file
2015-06-07 00:14:00 +02:00
Martchus a6a089d765 increased version number 2015-06-07 00:10:20 +02:00
36 changed files with 2799 additions and 3967 deletions

19
.github/stale.yml vendored Normal file
View File

@ -0,0 +1,19 @@
# Number of days of inactivity before an issue becomes stale
daysUntilStale: 60
# Number of days of inactivity before a stale issue is closed
daysUntilClose: 7
# Issues with these labels will never be considered stale
exemptLabels:
- pinned
- security
- feature request
- enhancement
# Label to use when marking an issue as stale
staleLabel: stale
# Comment to post when marking an issue as stale. Set to `false` to disable
markComment: >
This issue has been automatically marked as stale because it has not had
recent activity. It will be closed if no further activity occurs. Thank you
for your contributions.
# Comment to post when closing a stale issue. Set to `false` to disable
closeComment: false

13
.gitignore vendored
View File

@ -15,6 +15,7 @@
/.qmake.cache
/.qmake.stash
*.pro.user
*.txt.user
*.pro.user.*
*.qbs.user
*.qbs.user.*
@ -32,3 +33,15 @@ Makefile*
#QtCtreator Qml
*.qmlproject.user
*.qmlproject.user.*
# Dolphin
.directory
# documentation
/doc
# tests
*.backup
# clang-format
/.clang-format

64
CMakeLists.txt Normal file
View File

@ -0,0 +1,64 @@
cmake_minimum_required(VERSION 3.17.0 FATAL_ERROR)
# set meta data
project(passwordfile)
set(META_PROJECT_NAME ${PROJECT_NAME})
set(META_PROJECT_VARNAME PASSWORD_FILE)
set(META_APP_NAME "Passwordfile library")
set(META_APP_AUTHOR "Martchus")
set(META_APP_URL "https://github.com/${META_APP_AUTHOR}/${META_PROJECT_NAME}")
set(META_APP_DESCRIPTION "C++ library to read/write passwords from/to encrypted files")
set(META_VERSION_MAJOR 5)
set(META_VERSION_MINOR 0)
set(META_VERSION_PATCH 12)
set(META_ADD_DEFAULT_CPP_UNIT_TEST_APPLICATION ON)
# add project files
set(HEADER_FILES
io/cryptoexception.h
io/entry.h
io/field.h
io/parsingexception.h
io/passwordfile.h
util/openssl.h
util/opensslrandomdevice.h)
set(SRC_FILES
io/cryptoexception.cpp
io/entry.cpp
io/field.cpp
io/parsingexception.cpp
io/passwordfile.cpp
util/openssl.cpp
util/opensslrandomdevice.cpp)
set(TEST_HEADER_FILES)
set(TEST_SRC_FILES tests/utils.h tests/passwordfiletests.cpp tests/entrytests.cpp tests/fieldtests.cpp
tests/opensslrandomdevice.cpp tests/opensslutils.cpp)
set(DOC_FILES README.md)
option(COMPILE_AES_SOURCES "compile AES sources" OFF)
if (COMPILE_AES_SOURCES)
list(APPEND HEADER_FILES aes/aes.h)
list(APPEND SRC_FILES aes/aes.cpp)
endif ()
# find c++utilities
set(CONFIGURATION_PACKAGE_SUFFIX
""
CACHE STRING "sets the suffix for find_package() calls to packages configured via c++utilities")
find_package(c++utilities${CONFIGURATION_PACKAGE_SUFFIX} 5.14.0 REQUIRED)
use_cpp_utilities(VISIBILITY PUBLIC)
# find 3rd party libraries
include(3rdParty)
use_zlib()
use_crypto()
use_standard_filesystem()
# include modules to apply configuration
include(BasicConfig)
include(WindowsResources)
include(LibraryTarget)
include(TestTarget)
include(Doxygen)
include(ConfigHeader)

View File

@ -1,6 +1,14 @@
# passwordfile
C++ library to read/write passwords from/to encrypted files.
C++ library to read/write key-value pairs from/to AES-256-CBC encrypted files.
It is using OpenSSL under the hood. The key-value pairs are organized in tables
within an hierarchical structure. The data can be compressed with gzip before
applying the encryption.
## Build instructions
The passwordfile library depends on c++utilities and is built in the same way.
It also depends on OpenSSL and zlib.
## Copyright notice and license
Copyright © 2015-2024 Marius Kittler
All code is licensed under [GPL-2-or-later](LICENSE).

View File

@ -1,411 +1,395 @@
#include "aes.h"
#include <cstring>
namespace Crypto {
Aes::byte Aes::sbox[16][16] = {
{ 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76 },
{ 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0 },
{ 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15 },
{ 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75 },
{ 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84 },
{ 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF },
{ 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8 },
{ 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2 },
{ 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73 },
{ 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB },
{ 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79 },
{ 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08 },
{ 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A },
{ 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E },
{ 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF },
{ 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16 }
};
Aes::byte Aes::inv_sbox[16][16] = {
{ 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb },
{ 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb },
{ 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e },
{ 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25 },
{ 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92 },
{ 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84 },
{ 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06 },
{ 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b },
{ 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73 },
{ 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e },
{ 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b },
{ 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4 },
{ 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f },
{ 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef },
{ 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61 },
{ 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d }
};
Aes::word Aes::rcon[52] = {
0x00000000, 0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000, 0x20000000, 0x40000000,
0x80000000, 0x1B000000, 0x36000000, 0x6C000000, 0xD8000000, 0xAB000000, 0x4D000000, 0x9A000000,
0x2F000000, 0x5E000000, 0xBC000000, 0x63000000, 0xC6000000, 0x97000000, 0x35000000, 0x6A000000,
0xD4000000, 0xB3000000, 0x7D000000, 0xFA000000, 0xEF000000, 0xC5000000, 0x91000000, 0x39000000,
0x72000000, 0xE4000000, 0xD3000000, 0xBD000000, 0x61000000, 0xC2000000, 0x9F000000, 0x25000000,
0x4A000000, 0x94000000, 0x33000000, 0x66000000, 0xCC000000, 0x83000000, 0x1D000000, 0x3A000000,
0x74000000, 0xE8000000, 0xCB000000, 0x8D000000
};
Aes::Aes() :
key_length(0),
num_rounds(0),
w(0)
{
memset(state, 0, 16);
}
Aes::~Aes()
{
}
Aes::byte Aes::gmul(byte a, byte b)
{
unsigned char p = 0;
unsigned char hi;
for(byte i = 0; i < 8; ++i) {
if((b & 1) == 1)
p ^= a;
hi = (a & 0x80);
a <<= 1;
if(hi == 0x80)
a ^= 0x1b;
b >>= 1;
}
return p;
}
void Aes::rotWord(word *b)
{
byte tmp[4];
memcpy(tmp, b, 4);
byte tmpb = tmp[3];
for(byte i = 3; i > 0; --i)
tmp[i] = tmp[i - 1];
tmp[0] = tmpb;
memcpy(b, tmp, 4);
}
void Aes::subWord( word *b )
{
byte tmp[ 4 ];
memcpy( tmp, b, 4 );
for( byte i = 0; i < 4; ++i )
tmp[ i ] = sbox[ tmp[ i ] >> 4 ][ tmp[ i ] & 0x0f ];
memcpy( b, tmp, 4 );
}
void Aes::expandKey( byte *key )
{
if( w )
delete [] w;
w = new word[ 4 * ( num_rounds + 1 ) ];
for( byte iw = 0, ib = 0; iw < key_length; ++iw, ib += 4 )
w[ iw ] = ( key[ ib ] << 24 ) + ( key[ ib + 1 ] << 16 ) + ( key[ ib + 2 ] << 8 ) + key[ ib + 3 ];
word tmp;
for( byte i = key_length; i < ( 4 * ( num_rounds + 1 ) ); ++i ) {
tmp = w[ i - 1 ];
if( ( i % key_length ) == 0 ) {
rotWord( &tmp );
subWord( &tmp );
tmp ^= rcon[ i / key_length ];
} else if( ( key_length > 6 ) && ( ( i % key_length ) == 4 ) ) {
subWord( &tmp );
}
w[ i ] = w[ i - key_length ] ^ tmp;
}
}
void Aes::addRoundKey( byte round )
{
for( byte col = 0; col < 4; ++col )
for( byte row = 0; row < 4; ++row )
state[ row ][ col ] ^= ( w[ round * 4 + col ] >> ( 24 - row * 8 ) ) & 0x000000ff;
}
void Aes::shiftRows( void )
{
byte tmp = 0;
tmp = state[ 1 ][ 0 ];
state[ 1 ][ 0 ] = state[ 1 ][ 1 ];
state[ 1 ][ 1 ] = state[ 1 ][ 2 ];
state[ 1 ][ 2 ] = state[ 1 ][ 3 ];
state[ 1 ][ 3 ] = tmp;
tmp = state[ 2 ][ 0 ];
state[ 2 ][ 0 ] = state[ 2 ][ 2 ];
state[ 2 ][ 2 ] = tmp;
tmp = state[ 2 ][ 1 ];
state[ 2 ][ 1 ] = state[ 2 ][ 3 ];
state[ 2 ][ 3 ] = tmp;
tmp = state[ 3 ][ 3 ];
state[ 3 ][ 3 ] = state[ 3 ][ 2 ];
state[ 3 ][ 2 ] = state[ 3 ][ 1 ];
state[ 3 ][ 1 ] = state[ 3 ][ 0 ];
state[ 3 ][ 0 ] = tmp;
}
void Aes::invShiftRows( void )
{
byte tmp = 0;
tmp = state[ 3 ][ 0 ];
state[ 3 ][ 0 ] = state[ 3 ][ 1 ];
state[ 3 ][ 1 ] = state[ 3 ][ 2 ];
state[ 3 ][ 2 ] = state[ 3 ][ 3 ];
state[ 3 ][ 3 ] = tmp;
tmp = state[ 2 ][ 0 ];
state[ 2 ][ 0 ] = state[ 2 ][ 2 ];
state[ 2 ][ 2 ] = tmp;
tmp = state[ 2 ][ 1 ];
state[ 2 ][ 1 ] = state[ 2 ][ 3 ];
state[ 2 ][ 3 ] = tmp;
tmp = state[ 1 ][ 3 ];
state[ 1 ][ 3 ] = state[ 1 ][ 2 ];
state[ 1 ][ 2 ] = state[ 1 ][ 1 ];
state[ 1 ][ 1 ] = state[ 1 ][ 0 ];
state[ 1 ][ 0 ] = tmp;
}
void Aes::mixColumns( void )
{
unsigned char a[4];
unsigned char b[4];
unsigned char h = 0;
for( byte col = 0; col < 4; ++col ) {
for( byte row = 0; row < 4; ++row ) {
a[ row ] = state[ row ][ col ];
h = state[ row ][ col ] & 0x80;
b[ row ] = state[ row ][ col ] << 1;
if( h == 0x80 )
b[ row ] ^= 0x1b;
}
state[ 0 ][ col ] = b[ 0 ] ^ a[ 3 ] ^ a[ 2 ] ^ b[ 1 ] ^ a[ 1 ];
state[ 1 ][ col ] = b[ 1 ] ^ a[ 0 ] ^ a[ 3 ] ^ b[ 2 ] ^ a[ 2 ];
state[ 2 ][ col ] = b[ 2 ] ^ a[ 1 ] ^ a[ 0 ] ^ b[ 3 ] ^ a[ 3 ];
state[ 3 ][ col ] = b[ 3 ] ^ a[ 2 ] ^ a[ 1 ] ^ b[ 0 ] ^ a[ 0 ];
}
}
void Aes::invMixColumns( void )
{
unsigned char a[4];
for( byte col = 0; col < 4; ++col ) {
for( byte row = 0; row < 4; ++ row )
a[ row ] = state[ row ][ col ];
state[ 0 ][ col ] = gmul( a[ 0 ], 14 ) ^ gmul( a[ 3 ], 9 ) ^ gmul( a[ 2 ], 13 ) ^ gmul( a[ 1 ], 11 );
state[ 1 ][ col ] = gmul( a[ 1 ], 14 ) ^ gmul( a[ 0 ], 9 ) ^ gmul( a[ 3 ], 13 ) ^ gmul( a[ 2 ], 11 );
state[ 2 ][ col ] = gmul( a[ 2 ], 14 ) ^ gmul( a[ 1 ], 9 ) ^ gmul( a[ 0 ], 13 ) ^ gmul( a[ 3 ], 11 );
state[ 3 ][ col ] = gmul( a[ 3 ], 14 ) ^ gmul( a[ 2 ], 9 ) ^ gmul( a[ 1 ], 13 ) ^ gmul( a[ 0 ], 11 );
}
}
bool Aes::setKey( char *key )
{
size_t key_len = strlen( key );
byte *w_key = 0;
byte des_key_len = 0;
if( key_len <= 16 ) {
key_length = 4;
num_rounds = 10;
des_key_len = 16;
} else if( key_len <= 24 ) {
key_length = 6;
num_rounds = 12;
des_key_len = 24;
} else if( key_len <= 32 ) {
key_length = 8;
num_rounds = 14;
des_key_len = 32;
}
w_key = new byte[ des_key_len ];
for( byte i = 0, t = 0; t < des_key_len; ++i, ++t ) {
if( i == key_len )
i = 0;
*( w_key + t ) = *( key + i );
}
expandKey( w_key );
delete [] w_key;
return true;
}
void Aes::cipher( void )
{
addRoundKey( 0 );
for( byte round = 1; round < num_rounds; ++round ) {
for( byte row = 0; row < 4; ++row )
for( byte col = 0; col < 4; ++col )
state[ row ][ col ] = sbox[ state[ row ][ col ] >> 4 ][ state[ row ][ col ] & 0x0f ];
shiftRows( );
mixColumns( );
addRoundKey( round );
}
for( byte row = 0; row < 4; ++row )
for( byte col = 0; col < 4; ++col )
state[ row ][ col ] = sbox[ state[ row ][ col ] >> 4 ][ state[ row ][ col ] & 0x0f ];
shiftRows( );
addRoundKey( num_rounds );
}
void Aes::invCipher( void )
{
addRoundKey( num_rounds );
for( byte round = ( num_rounds - 1 ); round > 0; --round ) {
invShiftRows( );
for( byte row = 0; row < 4; ++row )
for( byte col = 0; col < 4; ++col )
state[ row ][ col ] = inv_sbox[ state[ row ][ col ] >> 4 ][ state[ row ][ col ] & 0x0f ];
addRoundKey( round );
invMixColumns( );
}
invShiftRows( );
for( byte row = 0; row < 4; ++row )
for( byte col = 0; col < 4; ++col )
state[ row ][ col ] = inv_sbox[ state[ row ][ col ] >> 4 ][ state[ row ][ col ] & 0x0f ];
addRoundKey( 0 );
}
size_t Aes::encrypt( char **data, size_t length, char *key )
{
if( length == 0 )
return 0;
if( !setKey( key ) )
return 0;
size_t old_length = length;
while( length % 16 )
++length;
char *buffer = new char[ length ];
memset( buffer, 0, length );
memcpy( buffer, *data, old_length );
delete [] *data;
*data = buffer;
size_t cur_block = 0;
do {
for( byte col = 0; col < 4; ++col )
for( byte row = 0; row < 4; ++row )
state[ row ][ col ] = static_cast< byte >( ( *data )[ cur_block * 16 + row + 4 * col ] );
cipher( );
for( byte col = 0; col < 4; ++col )
for( byte row = 0; row < 4; ++row )
( *data )[ cur_block * 16 + row + 4 * col ] = static_cast< char >( state[ row ][ col ] );
++cur_block;
} while( cur_block * 16 != length );
return cur_block;
}
size_t Aes::decrypt( char **data, size_t length, char *key )
{
if( length == 0 )
return 0;
if( !setKey( key ) )
return 0;
size_t old_length = length;
while( length % 16 )
++length;
char *buffer = new char[ length ];
memset( buffer, 0, length );
memcpy( buffer, *data, old_length );
delete [] *data;
*data = buffer;
size_t cur_block = 0;
do {
for( byte col = 0; col < 4; ++col )
for( byte row = 0; row < 4; ++row )
state[ row ][ col ] = static_cast< byte >( ( *data )[ cur_block * 16 + row + 4 * col ] );
invCipher( );
for( byte col = 0; col < 4; ++col )
for( byte row = 0; row < 4; ++row )
( *data )[ cur_block * 16 + row + 4 * col ] = static_cast< char >( state[ row ][ col ] );
++cur_block;
} while( cur_block * 16 != length );
--length;
while( ! ( ( *buffer ) + length ) )
--length;
++length;
return length;
}
}
#include "./aes.h"
#include <cstring>
namespace Crypto {
/*!
* \class Aes
* \brief The Aes class implements AES encryption/decryption.
* \deprecated This class is not used by the rest of the library and not compiled by default.
* OpenSSL's crypto library is used instead. This class only serves educational
* purposes.
*/
// clang-format off
Aes::byte Aes::sbox[16][16] = {
{ 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76 },
{ 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0 },
{ 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15 },
{ 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75 },
{ 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84 },
{ 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF },
{ 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8 },
{ 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2 },
{ 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73 },
{ 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB },
{ 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79 },
{ 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08 },
{ 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A },
{ 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E },
{ 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF },
{ 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16 }
};
Aes::byte Aes::inv_sbox[16][16] = {
{ 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb },
{ 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb },
{ 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e },
{ 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25 },
{ 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92 },
{ 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84 },
{ 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06 },
{ 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b },
{ 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73 },
{ 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e },
{ 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b },
{ 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4 },
{ 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f },
{ 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef },
{ 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61 },
{ 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d }
};
Aes::word Aes::rcon[52] = {
0x00000000, 0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000, 0x20000000, 0x40000000,
0x80000000, 0x1B000000, 0x36000000, 0x6C000000, 0xD8000000, 0xAB000000, 0x4D000000, 0x9A000000,
0x2F000000, 0x5E000000, 0xBC000000, 0x63000000, 0xC6000000, 0x97000000, 0x35000000, 0x6A000000,
0xD4000000, 0xB3000000, 0x7D000000, 0xFA000000, 0xEF000000, 0xC5000000, 0x91000000, 0x39000000,
0x72000000, 0xE4000000, 0xD3000000, 0xBD000000, 0x61000000, 0xC2000000, 0x9F000000, 0x25000000,
0x4A000000, 0x94000000, 0x33000000, 0x66000000, 0xCC000000, 0x83000000, 0x1D000000, 0x3A000000,
0x74000000, 0xE8000000, 0xCB000000, 0x8D000000
};
// clang-format on
Aes::Aes()
: keyLength(0)
, numRounds(0)
, w(0)
{
memset(state, 0, 16);
}
Aes::~Aes()
{
}
Aes::byte Aes::gmul(byte a, byte b)
{
unsigned char p = 0;
unsigned char hi;
for (byte i = 0; i < 8; ++i) {
if ((b & 1) == 1)
p ^= a;
hi = (a & 0x80);
a <<= 1;
if (hi == 0x80)
a ^= 0x1b;
b >>= 1;
}
return p;
}
void Aes::rotWord(word *b)
{
byte tmp[4];
memcpy(tmp, b, 4);
byte tmpb = tmp[3];
for (byte i = 3; i > 0; --i)
tmp[i] = tmp[i - 1];
tmp[0] = tmpb;
memcpy(b, tmp, 4);
}
void Aes::subWord(word *b)
{
byte tmp[4];
memcpy(tmp, b, 4);
for (byte i = 0; i < 4; ++i)
tmp[i] = sbox[tmp[i] >> 4][tmp[i] & 0x0f];
memcpy(b, tmp, 4);
}
void Aes::expandKey(byte *key)
{
if (w)
delete[] w;
w = new word[4 * (numRounds + 1)];
for (byte iw = 0, ib = 0; iw < keyLength; ++iw, ib += 4)
w[iw] = static_cast<word>((key[ib] << 24) + (key[ib + 1] << 16) + (key[ib + 2] << 8) + key[ib + 3]);
word tmp;
for (byte i = keyLength; i < (4 * (numRounds + 1)); ++i) {
tmp = w[i - 1];
if ((i % keyLength) == 0) {
rotWord(&tmp);
subWord(&tmp);
tmp ^= rcon[i / keyLength];
} else if ((keyLength > 6) && ((i % keyLength) == 4)) {
subWord(&tmp);
}
w[i] = w[i - keyLength] ^ tmp;
}
}
void Aes::addRoundKey(byte round)
{
for (byte col = 0; col < 4; ++col)
for (byte row = 0; row < 4; ++row)
state[row][col] ^= static_cast<byte>((w[round * 4 + col] >> (24 - row * 8)) & 0x000000ff);
}
void Aes::shiftRows(void)
{
byte tmp = 0;
tmp = state[1][0];
state[1][0] = state[1][1];
state[1][1] = state[1][2];
state[1][2] = state[1][3];
state[1][3] = tmp;
tmp = state[2][0];
state[2][0] = state[2][2];
state[2][2] = tmp;
tmp = state[2][1];
state[2][1] = state[2][3];
state[2][3] = tmp;
tmp = state[3][3];
state[3][3] = state[3][2];
state[3][2] = state[3][1];
state[3][1] = state[3][0];
state[3][0] = tmp;
}
void Aes::invShiftRows(void)
{
byte tmp = 0;
tmp = state[3][0];
state[3][0] = state[3][1];
state[3][1] = state[3][2];
state[3][2] = state[3][3];
state[3][3] = tmp;
tmp = state[2][0];
state[2][0] = state[2][2];
state[2][2] = tmp;
tmp = state[2][1];
state[2][1] = state[2][3];
state[2][3] = tmp;
tmp = state[1][3];
state[1][3] = state[1][2];
state[1][2] = state[1][1];
state[1][1] = state[1][0];
state[1][0] = tmp;
}
void Aes::mixColumns(void)
{
unsigned char a[4];
unsigned char b[4];
unsigned char h = 0;
for (byte col = 0; col < 4; ++col) {
for (byte row = 0; row < 4; ++row) {
a[row] = state[row][col];
h = state[row][col] & 0x80;
b[row] = static_cast<byte>(state[row][col] << 1);
if (h == 0x80)
b[row] ^= 0x1b;
}
state[0][col] = b[0] ^ a[3] ^ a[2] ^ b[1] ^ a[1];
state[1][col] = b[1] ^ a[0] ^ a[3] ^ b[2] ^ a[2];
state[2][col] = b[2] ^ a[1] ^ a[0] ^ b[3] ^ a[3];
state[3][col] = b[3] ^ a[2] ^ a[1] ^ b[0] ^ a[0];
}
}
void Aes::invMixColumns(void)
{
unsigned char a[4];
for (byte col = 0; col < 4; ++col) {
for (byte row = 0; row < 4; ++row)
a[row] = state[row][col];
state[0][col] = gmul(a[0], 14) ^ gmul(a[3], 9) ^ gmul(a[2], 13) ^ gmul(a[1], 11);
state[1][col] = gmul(a[1], 14) ^ gmul(a[0], 9) ^ gmul(a[3], 13) ^ gmul(a[2], 11);
state[2][col] = gmul(a[2], 14) ^ gmul(a[1], 9) ^ gmul(a[0], 13) ^ gmul(a[3], 11);
state[3][col] = gmul(a[3], 14) ^ gmul(a[2], 9) ^ gmul(a[1], 13) ^ gmul(a[0], 11);
}
}
bool Aes::setKey(char *key)
{
size_t keyLen = strlen(key);
byte *wKey = 0;
byte desKeyLen = 0;
if (keyLen <= 16) {
keyLength = 4;
numRounds = 10;
desKeyLen = 16;
} else if (keyLen <= 24) {
keyLength = 6;
numRounds = 12;
desKeyLen = 24;
} else if (keyLen <= 32) {
keyLength = 8;
numRounds = 14;
desKeyLen = 32;
}
wKey = new byte[desKeyLen];
for (byte i = 0, t = 0; t < desKeyLen; ++i, ++t) {
if (i == keyLen)
i = 0;
*(wKey + t) = static_cast<byte>(*(key + i));
}
expandKey(wKey);
delete[] wKey;
return true;
}
void Aes::cipher(void)
{
addRoundKey(0);
for (byte round = 1; round < numRounds; ++round) {
for (byte row = 0; row < 4; ++row)
for (byte col = 0; col < 4; ++col)
state[row][col] = sbox[state[row][col] >> 4][state[row][col] & 0x0f];
shiftRows();
mixColumns();
addRoundKey(round);
}
for (byte row = 0; row < 4; ++row)
for (byte col = 0; col < 4; ++col)
state[row][col] = sbox[state[row][col] >> 4][state[row][col] & 0x0f];
shiftRows();
addRoundKey(numRounds);
}
void Aes::invCipher(void)
{
addRoundKey(numRounds);
for (byte round = (numRounds - 1); round > 0; --round) {
invShiftRows();
for (byte row = 0; row < 4; ++row)
for (byte col = 0; col < 4; ++col)
state[row][col] = inv_sbox[state[row][col] >> 4][state[row][col] & 0x0f];
addRoundKey(round);
invMixColumns();
}
invShiftRows();
for (byte row = 0; row < 4; ++row)
for (byte col = 0; col < 4; ++col)
state[row][col] = inv_sbox[state[row][col] >> 4][state[row][col] & 0x0f];
addRoundKey(0);
}
size_t Aes::encrypt(char **data, std::size_t length, char *key)
{
if (length == 0)
return 0;
if (!setKey(key))
return 0;
size_t oldLength = length;
while (length % 16)
++length;
char *buffer = new char[length];
memset(buffer, 0, length);
memcpy(buffer, *data, oldLength);
delete[] * data;
*data = buffer;
size_t curBlock = 0;
do {
for (byte col = 0; col < 4; ++col)
for (byte row = 0; row < 4; ++row)
state[row][col] = static_cast<byte>((*data)[curBlock * 16 + row + 4 * col]);
cipher();
for (byte col = 0; col < 4; ++col)
for (byte row = 0; row < 4; ++row)
(*data)[curBlock * 16 + row + 4 * col] = static_cast<char>(state[row][col]);
++curBlock;
} while (curBlock * 16 != length);
return curBlock;
}
size_t Aes::decrypt(char **data, std::size_t length, char *key)
{
if (length == 0)
return 0;
if (!setKey(key))
return 0;
std::size_t oldLength = length;
while (length % 16)
++length;
char *buffer = new char[length];
memset(buffer, 0, length);
memcpy(buffer, *data, oldLength);
delete[] * data;
*data = buffer;
std::size_t curBlock = 0;
do {
for (byte col = 0; col < 4; ++col)
for (byte row = 0; row < 4; ++row)
state[row][col] = static_cast<byte>((*data)[curBlock * 16 + row + 4 * col]);
invCipher();
for (byte col = 0; col < 4; ++col)
for (byte row = 0; row < 4; ++row)
(*data)[curBlock * 16 + row + 4 * col] = static_cast<char>(state[row][col]);
++curBlock;
} while (curBlock * 16 != length);
--length;
while (!(static_cast<decltype(length)>(*buffer) + length))
--length;
++length;
return length;
}
} // namespace Crypto

108
aes/aes.h
View File

@ -1,54 +1,54 @@
#ifndef AES_INCLUDED
#define AES_INCLUDED AES_INCLUDED
#include <c++utilities/application/global.h>
#include <cstring>
namespace Crypto {
class LIB_EXPORT Aes {
public:
typedef unsigned char byte;
typedef unsigned long word;
Aes();
~Aes();
size_t encrypt(char **data, size_t length, char *key);
size_t decrypt(char **data, size_t length, char *key);
private:
static byte gmul(byte a, byte b);
static void rotWord(word *b );
static void subWord(word *b );
bool setKey(char *key);
void expandKey(byte *key);
void addRoundKey(byte round);
void shiftRows(void);
void invShiftRows(void);
void mixColumns(void);
void invMixColumns(void);
void cipher(void);
void invCipher(void);
static byte sbox[16][16];
static byte inv_sbox[16][16];
static word rcon[52];
byte key_length;
byte num_rounds;
word *w;
byte state[4][4];
};
}
#endif /* AES_INCLUDED */
#ifndef AES_INCLUDED
#define AES_INCLUDED AES_INCLUDED
#include "../global.h"
#include <cstring>
namespace Crypto {
class PASSWORD_FILE_EXPORT Aes {
public:
using byte = unsigned char;
using word = unsigned long;
Aes();
~Aes();
std::size_t encrypt(char **data, std::size_t length, char *key);
std::size_t decrypt(char **data, std::size_t length, char *key);
private:
static byte gmul(byte a, byte b);
static void rotWord(word *b);
static void subWord(word *b);
bool setKey(char *key);
void expandKey(byte *key);
void addRoundKey(byte round);
void shiftRows(void);
void invShiftRows(void);
void mixColumns(void);
void invMixColumns(void);
void cipher(void);
void invCipher(void);
static byte sbox[16][16];
static byte inv_sbox[16][16];
static word rcon[52];
byte keyLength;
byte numRounds;
word *w;
byte state[4][4];
};
} // namespace Crypto
#endif /* AES_INCLUDED */

View File

@ -1,71 +0,0 @@
# template
TEMPLATE = lib
#dirs
UI_DIR = ./gui
MOC_DIR = ./moc
OBJECTS_DIR = ./obj
RCC_DIR = ./res
# compiler flags
QMAKE_CXXFLAGS += -std=c++11
QMAKE_LFLAGS += -std=c++11
unix {
QMAKE_LFLAGS += "-Wl,--rpath=./"
}
# prefix
targetprefix = .
# target
CONFIG(debug, debug|release) {
TARGET = $$targetprefix/$${projectname}d
} else {
TARGET = $$targetprefix/$$projectname
}
# variables to check target architecture
win32-g++:QMAKE_TARGET.arch = $$QMAKE_HOST.arch
win32-g++-32:QMAKE_TARGET.arch = x86
win32-g++-64:QMAKE_TARGET.arch = x86_64
linux-g++:QMAKE_TARGET.arch = $$QMAKE_HOST.arch
linux-g++-32:QMAKE_TARGET.arch = x86
linux-g++-64:QMAKE_TARGET.arch = x86_64
# configuration
mobile {
DEFINES += CONFIG_MOBILE
} else:desktop {
DEFINES += CONFIG_DESKTOP
} else:android {
CONFIG += mobile
DEFINES += CONFIG_MOBILE
} else {
CONFIG += desktop
DEFINES += CONFIG_DESKTOP
}
no-gui {
QT -= gui
DEFINES += GUI_NONE
guiqtquick || guiqtwidgets {
error("Can not use no-gui with guiqtquick or guiqtwidgets.")
} else {
message("Configured for no GUI support.")
}
} else {
QT += gui
mobile {
CONFIG += guiqtquick
}
desktop {
CONFIG += guiqtwidgets
}
}
guiqtquick {
message("Configured for Qt Quick GUI support.")
greaterThan(QT_MAJOR_VERSION, 4): QT += quick
CONFIG(debug, debug|release) {
CONFIG += qml_debug
}
DEFINES += GUI_QTQUICK
}
guiqtwidgets {
message("Configured for Qt widgets GUI support.")
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
DEFINES += GUI_QTWIDGETS
DEFINES += MODEL_UNDO_SUPPORT
}

28
global.h Normal file
View File

@ -0,0 +1,28 @@
// Created via CMake from template global.h.in
// WARNING! Any changes to this file will be overwritten by the next CMake run!
#ifndef PASSWORD_FILE_GLOBAL
#define PASSWORD_FILE_GLOBAL
#include "passwordfile-definitions.h"
#include <c++utilities/application/global.h>
#ifdef PASSWORD_FILE_STATIC
#define PASSWORD_FILE_EXPORT
#define PASSWORD_FILE_IMPORT
#else
#define PASSWORD_FILE_EXPORT CPP_UTILITIES_GENERIC_LIB_EXPORT
#define PASSWORD_FILE_IMPORT CPP_UTILITIES_GENERIC_LIB_IMPORT
#endif
/*!
* \def PASSWORD_FILE_EXPORT
* \brief Marks the symbol to be exported by the passwordfile library.
*/
/*!
* \def PASSWORD_FILE_IMPORT
* \brief Marks the symbol to be imported from the passwordfile library.
*/
#endif // PASSWORD_FILE_GLOBAL

View File

@ -1,22 +1,34 @@
#include "cryptoexception.h"
#include "./cryptoexception.h"
namespace Io {
/*!
* \class CryptoException
* \brief The exception that is thrown when an encryption/decryption error occurs.
* \remarks Must not have any inline methods/c'tors/d'tors (so the vtable is invoked in any compile unit).
* Otherwise it is not possible to throw/catch it across library boundaries under Android.
*/
/*!
* \brief Constructs a crypto exception.
*/
CryptoException::CryptoException(const std::string &openSslErrorQueue) USE_NOTHROW :
runtime_error(openSslErrorQueue)
{}
CryptoException::CryptoException(const std::string &message) noexcept
: runtime_error(message)
{
}
/*!
* \brief Destroys the exception.
* \brief Constructs a crypto exception.
*/
CryptoException::~CryptoException() USE_NOTHROW
{}
CryptoException::CryptoException(const char *message) noexcept
: runtime_error(message)
{
}
/*!
* \brief Destroys the crypto exception.
*/
CryptoException::~CryptoException()
{
}
} // namespace Io

View File

@ -1,20 +1,20 @@
#ifndef CRYPTOFAILUREEXCEPTION_H
#define CRYPTOFAILUREEXCEPTION_H
#ifndef PASSWORD_FILE_IO_CRYPTOFAILUREEXCEPTION_H
#define PASSWORD_FILE_IO_CRYPTOFAILUREEXCEPTION_H
#include <c++utilities/application/global.h>
#include "../global.h"
#include <stdexcept>
#include <string>
namespace Io {
class LIB_EXPORT CryptoException : public std::runtime_error
{
class PASSWORD_FILE_EXPORT CryptoException : public std::runtime_error {
public:
CryptoException(const std::string &openSslErrorQueue) USE_NOTHROW;
virtual ~CryptoException() USE_NOTHROW;
explicit CryptoException(const std::string &message) noexcept;
explicit CryptoException(const char *message) noexcept;
~CryptoException() override;
};
}
} // namespace Io
#endif // CRYPTOFAILUREEXCEPTION_H
#endif // PASSWORD_FILE_IO_CRYPTOFAILUREEXCEPTION_H

View File

@ -1,15 +1,15 @@
#include "entry.h"
#include "parsingexception.h"
#include "./entry.h"
#include "./parsingexception.h"
#include <c++utilities/conversion/stringbuilder.h>
#include <c++utilities/io/binaryreader.h>
#include <c++utilities/io/binarywriter.h>
#include <sstream>
#include <algorithm>
#include <sstream>
using namespace std;
using namespace IoUtilities;
using namespace ConversionUtilities;
using namespace CppUtilities;
namespace Io {
@ -20,7 +20,7 @@ namespace Io {
/*!
* \class Entry
* \brief Instances of the Entry class form a hierarchic data strucutre used to store
* \brief Instances of the Entry class form a hierarchic data structure used to store
* account information.
*
* Entries can be serialized and deserialized using the parse() and make() methods.
@ -29,24 +29,25 @@ namespace Io {
/*!
* \brief Constructs a new entry with the specified \a label and \a parent.
*/
Entry::Entry(const string &label, NodeEntry *parent) :
m_parent(nullptr),
m_index(-1)
Entry::Entry(const string &label, NodeEntry *parent)
: m_parent(nullptr)
, m_index(-1)
{
setParent(parent);
setLabel(label);
}
/*!
* \brief Constructs a copy of the another entry.
* \brief Constructs a copy of another entry.
* \remarks The copy will be parentless and thus not be embedded in the hierarchy
* of \a other. Child entries will be copied as well.
*/
Entry::Entry(const Entry &other) :
m_label(other.m_label),
m_parent(nullptr),
m_index(-1)
{}
Entry::Entry(const Entry &other)
: m_label(other.m_label)
, m_parent(nullptr)
, m_index(-1)
{
}
/*!
* \brief Destroys the entry.
@ -57,29 +58,30 @@ Entry::~Entry()
}
/*!
* \brief Internally called to make the label unique.
* \brief Internally called to make the entry's label unique within the parent.
* \sa setLabel()
*/
void Entry::makeLabelUnique()
{
if(m_parent) {
int index = 1;
string currentLabel(label());
checkLabel:
for(Entry *sibling : m_parent->children()) {
if(sibling != this && currentLabel == sibling->label()) {
stringstream newLabel(currentLabel);
newLabel.seekp(0, ios_base::end);
if(newLabel.tellp()) {
newLabel << ' ';
}
newLabel << ++index;
currentLabel = newLabel.str();
goto checkLabel;
}
}
m_label = currentLabel;
if (!m_parent) {
return;
}
string newLabel(label());
for (unsigned int index = 2;; ++index) {
bool needsNewLabel = false;
for (Entry *const sibling : m_parent->children()) {
if (sibling == this || newLabel != sibling->label()) {
continue;
}
needsNewLabel = true;
newLabel = argsToString(label(), ' ', index);
break;
}
if (!needsNewLabel) {
break;
}
}
m_label.swap(newLabel);
}
/*!
@ -87,49 +89,63 @@ void Entry::makeLabelUnique()
*
* If an \a index is specified the entry will be inserted as child at this position.
* If \a parent is nullptr, the entry will be parentless.
*
* \remarks
* - The label might be adjusted to be unique within the new parent.
* - If the entry is just moved within its current parent (\a parent equals parent()), the
* specified \a index doesn't take the entry itself into account as it is removed from
* the children of \a parent and then re-inserted at \a index.
*/
void Entry::setParent(NodeEntry *parent, int index)
{
if(m_parent != parent || (m_index != index && index >= 0)) {
if(m_parent) {
m_parent->m_children.erase(m_parent->m_children.begin() + m_index);
for(auto i = m_parent->m_children.begin() + m_index; i < m_parent->m_children.end(); ++i) {
(*i)->m_index -= 1;
}
}
if(parent) {
if(index < 0 || static_cast<size_t>(index) >= parent->m_children.size()) {
m_index = parent->m_children.size();
parent->m_children.push_back(this);
} else {
for(auto i = parent->m_children.insert(parent->m_children.begin() + index, this) + 1;
i != parent->m_children.end(); ++i) {
(*i)->m_index += 1;
}
m_index = index;
}
} else {
m_index = -1;
}
m_parent = parent;
makeLabelUnique();
// skip if \a parent already assigned and the index doesn't change, too
if (m_parent == parent && !(m_index != index && index >= 0)) {
return;
}
// detach the current parent
if (m_parent) {
m_parent->m_children.erase(m_parent->m_children.begin() + m_index);
for (auto i = m_parent->m_children.begin() + m_index; i < m_parent->m_children.end(); ++i) {
(*i)->m_index -= 1;
}
}
// attach the new parent
if (parent) {
if (index < 0 || static_cast<size_t>(index) >= parent->m_children.size()) {
m_index = static_cast<int>(parent->m_children.size());
parent->m_children.push_back(this);
} else {
for (auto i = parent->m_children.insert(parent->m_children.begin() + index, this) + 1; i != parent->m_children.end(); ++i) {
(*i)->m_index += 1;
}
m_index = index;
}
} else {
m_index = -1;
}
// actually assign the parent
m_parent = parent;
// ensure the label is still unique within the new parent
makeLabelUnique();
}
/*!
* \brief Returns an indication whether the instance is an indirect child of the specified \a entry.
*/
bool Entry::isIndirectChildOf(NodeEntry *entry) const
bool Entry::isIndirectChildOf(const NodeEntry *entry) const
{
if(parent()) {
if(parent() == entry) {
return true;
} else {
return parent()->isIndirectChildOf(entry);
}
} else {
if (!parent()) {
return false;
}
if (parent() == entry) {
return true;
} else {
return parent()->isIndirectChildOf(entry);
}
}
/*!
@ -147,7 +163,7 @@ std::list<string> Entry::path() const
*/
void Entry::path(std::list<string> &res) const
{
if(m_parent) {
if (m_parent) {
m_parent->path(res);
}
res.push_back(label());
@ -159,8 +175,8 @@ void Entry::path(std::list<string> &res) const
*/
Entry *Entry::parse(istream &stream)
{
byte version = stream.peek();
if(denotesNodeEntry(version)) {
const auto version = static_cast<std::uint8_t>(stream.peek());
if (denotesNodeEntry(version)) {
return new NodeEntry(stream);
} else {
return new AccountEntry(stream);
@ -192,49 +208,50 @@ Entry *Entry::parse(istream &stream)
/*!
* \brief Constructs a new node entry.
*/
NodeEntry::NodeEntry() :
Entry(),
m_expandedByDefault(true)
{}
NodeEntry::NodeEntry()
: Entry()
, m_expandedByDefault(true)
{
}
/*!
* \brief Constructs a new node entry with the specified \a label and \a parent.
*/
NodeEntry::NodeEntry(const string &label, NodeEntry *parent) :
Entry(label, parent),
m_expandedByDefault(true)
{}
NodeEntry::NodeEntry(const string &label, NodeEntry *parent)
: Entry(label, parent)
, m_expandedByDefault(true)
{
}
/*!
* \brief Constructs a new node entry which is deserialized from the specified \a stream.
*/
NodeEntry::NodeEntry(istream &stream) :
m_expandedByDefault(true)
NodeEntry::NodeEntry(istream &stream)
: m_expandedByDefault(true)
{
BinaryReader reader(&stream);
byte version = reader.readByte();
if(denotesNodeEntry(version)) {
if(version == 0x0 || version == 0x1) {
setLabel(reader.readLengthPrefixedString());
if(version == 0x1) { // version 0x1 has an extended header
uint16 extendedHeaderSize = reader.readUInt16BE();
if(extendedHeaderSize >= 1) {
byte flags = reader.readByte();
m_expandedByDefault = flags & 0x80;
extendedHeaderSize -= 1;
}
stream.seekg(extendedHeaderSize, ios_base::cur);
}
uint32 childCount = reader.readUInt32BE();
for(uint32 i = 0; i < childCount; ++i) {
Entry::parse(stream)->setParent(this);
}
} else {
throw ParsingException("Entry version not supported.");
}
} else {
const std::uint8_t version = reader.readByte();
if (!denotesNodeEntry(version)) {
throw ParsingException("Node entry expected.");
}
if (version != 0x0 && version != 0x1) {
throw ParsingException("Entry version not supported.");
}
setLabel(reader.readLengthPrefixedString());
// read extended header for version 0x1
if (version == 0x1) {
std::uint16_t extendedHeaderSize = reader.readUInt16BE();
if (extendedHeaderSize >= 1) {
std::uint8_t flags = reader.readByte();
m_expandedByDefault = flags & 0x80;
extendedHeaderSize -= 1;
}
m_extendedData = reader.readString(extendedHeaderSize);
}
const std::uint32_t childCount = reader.readUInt32BE();
for (std::uint32_t i = 0; i != childCount; ++i) {
Entry::parse(stream)->setParent(this);
}
}
/*!
@ -242,13 +259,13 @@ NodeEntry::NodeEntry(istream &stream) :
* \remarks The copy will be parentless and thus not be embedded in the hierarchy
* of \a other. Child entries will be copied as well.
*/
NodeEntry::NodeEntry(const NodeEntry &other) :
Entry(other)
NodeEntry::NodeEntry(const NodeEntry &other)
: Entry(other)
{
for(Entry *otherChild : other.m_children) {
for (Entry *const otherChild : other.m_children) {
Entry *clonedChild = otherChild->clone();
clonedChild->m_parent = this;
clonedChild->m_index = m_children.size();
clonedChild->m_index = static_cast<int>(m_children.size());
m_children.push_back(clonedChild);
}
}
@ -258,7 +275,7 @@ NodeEntry::NodeEntry(const NodeEntry &other) :
*/
NodeEntry::~NodeEntry()
{
for(Entry *child : m_children) {
for (Entry *const child : m_children) {
child->m_parent = nullptr;
delete child;
}
@ -268,27 +285,57 @@ NodeEntry::~NodeEntry()
* \brief Deletes children from the node entry.
* \param begin Specifies the index of the first children to delete.
* \param end Specifies the index after the last children to delete.
* \remarks The children are actually destructed and deallocated.
*/
void NodeEntry::deleteChildren(int begin, int end)
{
auto iterator = m_children.cbegin() + begin;
auto endIterator = m_children.begin() + end;
for(; iterator < endIterator; ++iterator) {
const auto endIterator = m_children.begin() + end;
// delete the children
for (auto iterator = m_children.cbegin() + begin; iterator != endIterator; ++iterator) {
(*iterator)->m_parent = nullptr;
delete *iterator;
}
// remove the children from the list
m_children.erase(m_children.begin() + begin, endIterator);
// adjust indices of subsequent children
const int diff = end - begin;
for (auto iterator = m_children.begin() + begin, end2 = m_children.end(); iterator != end2; ++iterator) {
(*iterator)->m_index -= diff;
}
}
/*!
* \brief Replaces the child \a at the specified index with the specified \a newChild.
* \remarks The current child at the specified index is not destroyed and remains without
* a parent.
* \deprecated Since this leaves a parentless entry leading to potential memory leaks, this method
* will be removed in future releases (in its current form).
*/
void NodeEntry::replaceChild(size_t at, Entry *newChild)
{
if(at < m_children.size()) {
m_children.at(at)->m_parent = nullptr;
m_children[at] = newChild;
if (at >= m_children.size()) {
return;
}
// detach the old child
m_children[at]->m_parent = nullptr;
m_children[at]->m_index = -1;
// detach new child from its previous parent
if (auto *newChildOldParent = newChild->m_parent) {
newChildOldParent->m_children.erase(newChildOldParent->m_children.begin() + newChild->m_index);
for (auto i = newChildOldParent->m_children.begin() + newChild->m_index; i < newChildOldParent->m_children.end(); ++i) {
(*i)->m_index -= 1;
}
}
// do the actual assignment
newChild->m_parent = this;
newChild->m_index = static_cast<int>(at);
m_children[at] = newChild;
}
/*!
@ -300,59 +347,67 @@ void NodeEntry::replaceChild(size_t at, Entry *newChild)
* to be created must exist. Specify nullptr if no entries should be created (default).
* \returns Returns the entry if found (or created); otherwise nullptr is returned.
*/
Entry *NodeEntry::entryByPath(list<string> &path, bool includeThis, EntryType *creationType)
Entry *NodeEntry::entryByPath(list<string> &path, bool includeThis, const EntryType *creationType)
{
if(path.size()) {
if(includeThis) {
if(path.front() == label()) {
path.pop_front();
} else {
return nullptr;
}
}
if(path.size()) {
for(Entry *child : m_children) {
if(path.front() == child->label()) {
path.pop_front();
if(path.empty()) {
return child;
} else if(child->type() == EntryType::Node) {
return static_cast<NodeEntry *>(child)->entryByPath(path, false, creationType);
} else {
return nullptr; // can not resolve path since an account entry can not have children
}
}
}
if(creationType) {
if(path.size() == 1) {
switch(*creationType) {
case EntryType::Account:
return new AccountEntry(path.front(), this);
case EntryType::Node:
return new NodeEntry(path.front(), this);
}
} else {
return nullptr;
}
}
if (path.empty()) {
return nullptr;
}
// check for current instance
if (includeThis) {
if (path.front() == label()) {
path.pop_front();
} else {
return this;
return nullptr;
}
}
if (path.empty()) {
return this;
}
for (Entry *const child : m_children) {
if (path.front() != child->label()) {
continue;
}
path.pop_front();
if (path.empty()) {
return child;
} else if (child->type() == EntryType::Node) {
return static_cast<NodeEntry *>(child)->entryByPath(path, false, creationType);
} else {
return nullptr; // can not resolve path since an account entry can not have children
}
}
// create a new entry
if (!creationType || path.size() != 1) {
return nullptr;
}
switch (*creationType) {
case EntryType::Account:
return new AccountEntry(path.front(), this);
case EntryType::Node:
return new NodeEntry(path.front(), this);
}
return nullptr;
}
void NodeEntry::make(ostream &stream) const
{
BinaryWriter writer(&stream);
writer.writeByte(isExpandedByDefault() ? 0x0 : 0x1); // version
writer.writeByte(isExpandedByDefault() && m_extendedData.empty() ? 0x0 : 0x1); // version
writer.writeLengthPrefixedString(label());
if(!isExpandedByDefault()) {
writer.writeUInt16BE(1); // extended header is 1 byte long
writer.writeByte(0x00); // all flags cleared
if (!isExpandedByDefault() || !m_extendedData.empty()) {
writer.writeUInt16BE(static_cast<std::uint16_t>(1 + m_extendedData.size())); // extended header is 1 byte long
std::uint8_t flags = 0x00;
if (isExpandedByDefault()) {
flags |= 0x80;
}
writer.writeByte(flags);
writer.writeString(m_extendedData);
}
writer.writeUInt32BE(m_children.size());
for(const Entry *child : m_children) {
writer.writeUInt32BE(static_cast<std::uint32_t>(m_children.size()));
for (const Entry *const child : m_children) {
child->make(stream);
}
}
@ -362,20 +417,33 @@ NodeEntry *NodeEntry::clone() const
return new NodeEntry(*this);
}
/*!
* \brief Accumulates the statistics for this node entry and its children.
*/
void NodeEntry::accumulateStatistics(EntryStatistics &stats) const
{
++stats.nodeCount;
for (const auto *children : children()) {
children->accumulateStatistics(stats);
}
}
/*!
* \class AccountEntry
* \brief The exception that is thrown when a parsing error occurs.
*/
AccountEntry::AccountEntry()
{}
{
}
/*!
* \brief Constructs a new account entry with the specified \a label and \a parent.
*/
AccountEntry::AccountEntry(const string &label, NodeEntry *parent) :
Entry(label, parent)
{}
AccountEntry::AccountEntry(const string &label, NodeEntry *parent)
: Entry(label, parent)
{
}
/*!
* \brief Constructs a new account entry which is deserialized from the specified \a stream.
@ -383,26 +451,25 @@ AccountEntry::AccountEntry(const string &label, NodeEntry *parent) :
AccountEntry::AccountEntry(istream &stream)
{
BinaryReader reader(&stream);
byte version = reader.readByte();
if(!denotesNodeEntry(version)) {
version ^= 0x80; // set bit 0 to false
if(version == 0x0 || version == 0x1) {
setLabel(reader.readLengthPrefixedString());
if(version == 0x1) { // version 0x1 has an extended header
uint16 extendedHeaderSize = reader.readUInt16BE();
// currently there's nothing to read here
stream.seekg(extendedHeaderSize, ios_base::cur);
}
uint32 fieldCount = reader.readUInt32BE();
for(uint32 i = 0; i < fieldCount; ++i) {
m_fields.push_back(Field(this, stream));
}
} else {
throw ParsingException("Entry version not supported.");
}
} else {
std::uint8_t version = reader.readByte();
if (denotesNodeEntry(version)) {
throw ParsingException("Account entry expected.");
}
version ^= 0x80; // set first bit to zero
if (version != 0x0 && version != 0x1) {
throw ParsingException("Entry version not supported.");
}
setLabel(reader.readLengthPrefixedString());
// read extended header for version 0x1
if (version == 0x1) {
const std::uint16_t extendedHeaderSize = reader.readUInt16BE();
// currently there's nothing to read here
m_extendedData = reader.readString(extendedHeaderSize);
}
const std::uint32_t fieldCount = reader.readUInt32BE();
for (std::uint32_t i = 0; i != fieldCount; ++i) {
m_fields.push_back(Field(this, stream));
}
}
/*!
@ -410,8 +477,8 @@ AccountEntry::AccountEntry(istream &stream)
* \remarks The copy will be parentless and thus not be embedded in the hierarchy
* of \a other. Child entries will be copied as well.
*/
AccountEntry::AccountEntry(const AccountEntry &other) :
Entry(other)
AccountEntry::AccountEntry(const AccountEntry &other)
: Entry(other)
{
m_fields = other.m_fields;
}
@ -420,15 +487,20 @@ AccountEntry::AccountEntry(const AccountEntry &other) :
* \brief Destroys the entry.
*/
AccountEntry::~AccountEntry()
{}
{
}
void AccountEntry::make(ostream &stream) const
{
BinaryWriter writer(&stream);
writer.writeByte(0x80 | 0x0); // version
writer.writeByte(0x80 | (m_extendedData.empty() ? 0x0 : 0x1)); // version
writer.writeLengthPrefixedString(label());
writer.writeUInt32BE(m_fields.size());
for(const Field &field : m_fields) {
if (!m_extendedData.empty()) {
writer.writeUInt16BE(static_cast<std::uint16_t>(m_extendedData.size()));
writer.writeString(m_extendedData);
}
writer.writeUInt32BE(static_cast<std::uint32_t>(m_fields.size()));
for (const Field &field : m_fields) {
field.make(stream);
}
}
@ -438,4 +510,12 @@ AccountEntry *AccountEntry::clone() const
return new AccountEntry(*this);
}
/*!
* \brief Accumulates the statistics for this account entry and its fields.
*/
void AccountEntry::accumulateStatistics(EntryStatistics &stats) const
{
stats.accountCount += 1;
stats.fieldCount += fields().size();
}
} // namespace Io

View File

@ -1,32 +1,35 @@
#ifndef ENTRY_H
#define ENTRY_H
#ifndef PASSWORD_FILE_IO_ENTRY_H
#define PASSWORD_FILE_IO_ENTRY_H
#include "field.h"
#include <c++utilities/conversion/types.h>
#include <c++utilities/application/global.h>
#include "./field.h"
#include <cstdint>
#include <iostream>
#include <list>
#include <string>
#include <vector>
#include <list>
namespace Io {
/*!
* \brief Specifies the entry type.
*/
enum class EntryType : int
{
enum class EntryType : int {
Node, /**< denotes a NodeEntry */
Account /**< denotes an AccountEntry */
};
struct EntryStatistics {
std::size_t nodeCount = 0;
std::size_t accountCount = 0;
std::size_t fieldCount = 0;
};
class NodeEntry;
class LIB_EXPORT Entry
{
class PASSWORD_FILE_EXPORT Entry {
friend class NodeEntry;
public:
virtual ~Entry();
Entry &operator=(const Entry &other) = delete;
@ -37,13 +40,16 @@ public:
NodeEntry *parent() const;
void setParent(NodeEntry *parent, int index = -1);
int index() const;
bool isIndirectChildOf(NodeEntry *entry) const;
bool isIndirectChildOf(const NodeEntry *entry) const;
std::list<std::string> path() const;
void path(std::list<std::string> &res) const;
virtual void make(std::ostream &stream) const = 0;
virtual Entry *clone() const = 0;
EntryStatistics computeStatistics() const;
virtual void accumulateStatistics(EntryStatistics &stats) const = 0;
static Entry *parse(std::istream &stream);
static bool denotesNodeEntry(byte version);
static bool denotesNodeEntry(std::uint8_t version);
static constexpr EntryType denotedEntryType(std::uint8_t version);
protected:
Entry(const std::string &label = std::string(), NodeEntry *parent = nullptr);
@ -53,6 +59,9 @@ private:
std::string m_label;
NodeEntry *m_parent;
int m_index;
protected:
std::string m_extendedData;
};
/*!
@ -91,25 +100,38 @@ inline int Entry::index() const
return m_index;
}
class LIB_EXPORT NodeEntry : public Entry
/*!
* \brief Computes statistics for this entry.
* \remarks Takes the current instance and children into account but not parents.
*/
inline EntryStatistics Entry::computeStatistics() const
{
EntryStatistics stats;
accumulateStatistics(stats);
return stats;
}
class PASSWORD_FILE_EXPORT NodeEntry : public Entry {
friend class Entry;
public:
NodeEntry();
NodeEntry(const std::string &label, NodeEntry *parent = nullptr);
NodeEntry(std::istream &stream);
NodeEntry(const NodeEntry &other);
~NodeEntry();
~NodeEntry() override;
virtual EntryType type() const;
EntryType type() const override;
const std::vector<Entry *> &children() const;
void deleteChildren(int begin, int end);
void replaceChild(size_t at, Entry *newChild);
Entry *entryByPath(std::list<std::string> &path, bool includeThis = true, EntryType *creationType = nullptr);
void replaceChild(std::size_t at, Entry *newChild);
Entry *entryByPath(std::list<std::string> &path, bool includeThis = true, const EntryType *creationType = nullptr);
bool isExpandedByDefault() const;
void setExpandedByDefault(bool expandedByDefault);
virtual void make(std::ostream &stream) const;
virtual NodeEntry *clone() const;
void make(std::ostream &stream) const override;
NodeEntry *clone() const override;
void accumulateStatistics(EntryStatistics &stats) const override;
private:
std::vector<Entry *> m_children;
bool m_expandedByDefault;
@ -135,25 +157,31 @@ inline void NodeEntry::setExpandedByDefault(bool expandedByDefault)
m_expandedByDefault = expandedByDefault;
}
inline bool Entry::denotesNodeEntry(byte version)
inline bool Entry::denotesNodeEntry(std::uint8_t version)
{
return (version & 0x80) == 0;
}
class LIB_EXPORT AccountEntry : public Entry
constexpr EntryType Entry::denotedEntryType(std::uint8_t version)
{
return (version & 0x80) == 0 ? EntryType::Node : EntryType::Account;
}
class PASSWORD_FILE_EXPORT AccountEntry : public Entry {
public:
AccountEntry();
AccountEntry(const std::string &label, NodeEntry *parent = nullptr);
AccountEntry(std::istream &stream);
AccountEntry(const AccountEntry &other);
~AccountEntry();
~AccountEntry() override;
virtual EntryType type() const;
EntryType type() const override;
const std::vector<Field> &fields() const;
std::vector<Field> &fields();
virtual void make(std::ostream &stream) const;
virtual AccountEntry *clone() const;
void make(std::ostream &stream) const override;
AccountEntry *clone() const override;
void accumulateStatistics(EntryStatistics &stats) const override;
private:
std::vector<Field> m_fields;
};
@ -172,7 +200,6 @@ inline std::vector<Field> &AccountEntry::fields()
{
return m_fields;
}
} // namespace Io
}
#endif // ENTRY_H
#endif // PASSWORD_FILE_IO_ENTRY_H

View File

@ -1,12 +1,11 @@
#include "field.h"
#include "parsingexception.h"
#include "./field.h"
#include "./parsingexception.h"
#include <c++utilities/io/binaryreader.h>
#include <c++utilities/io/binarywriter.h>
using namespace std;
using namespace IoUtilities;
using namespace ConversionUtilities;
using namespace CppUtilities;
namespace Io {
@ -20,12 +19,13 @@ namespace Io {
* \brief Constructs a new account entry for the specified account with the specified \a name
* and \a value.
*/
Field::Field(AccountEntry *tiedAccount, const string &name, const string &value) :
m_name(name),
m_value(value),
m_type(FieldType::Normal),
m_tiedAccount(tiedAccount)
{}
Field::Field(AccountEntry *tiedAccount, const string &name, const string &value)
: m_name(name)
, m_value(value)
, m_type(FieldType::Normal)
, m_tiedAccount(tiedAccount)
{
}
/*!
* \brief Constructs a new account entry for the specified account which is deserialize from
@ -35,25 +35,24 @@ Field::Field(AccountEntry *tiedAccount, const string &name, const string &value)
Field::Field(AccountEntry *tiedAccount, istream &stream)
{
BinaryReader reader(&stream);
int version = reader.readByte();
if(version == 0x0 || version == 0x1) {
m_name = reader.readLengthPrefixedString();
m_value = reader.readLengthPrefixedString();
byte type = reader.readByte();
if(isValidType(type)) {
m_type = static_cast<FieldType>(type);
} else {
throw ParsingException("Field type is not supported.");
}
if(version == 0x1) { // version 0x1 has an extended header
uint16 extendedHeaderSize = reader.readUInt16BE();
// currently there's nothing to read here
stream.seekg(extendedHeaderSize, ios_base::cur);
}
m_tiedAccount = tiedAccount;
} else {
const int version = reader.readByte();
if (version != 0x0 && version != 0x1) {
throw ParsingException("Field version is not supported.");
}
m_name = reader.readLengthPrefixedString();
m_value = reader.readLengthPrefixedString();
std::uint8_t type = reader.readByte();
if (!isValidType(type)) {
throw ParsingException("Field type is not supported.");
}
m_type = static_cast<FieldType>(type);
// read extended header for version 0x1
if (version == 0x1) {
const std::uint16_t extendedHeaderSize = reader.readUInt16BE();
// currently there's nothing to read here
m_extendedData = reader.readString(extendedHeaderSize);
}
m_tiedAccount = tiedAccount;
}
/*!
@ -62,10 +61,13 @@ Field::Field(AccountEntry *tiedAccount, istream &stream)
void Field::make(ostream &stream) const
{
BinaryWriter writer(&stream);
writer.writeByte(0x0); // version
writer.writeByte(m_extendedData.empty() ? 0x0 : 0x1); // version
writer.writeLengthPrefixedString(m_name);
writer.writeLengthPrefixedString(m_value);
writer.writeByte(static_cast<byte>(m_type));
}
writer.writeByte(static_cast<std::uint8_t>(m_type));
if (!m_extendedData.empty()) {
writer.writeUInt16BE(static_cast<std::uint16_t>(m_extendedData.size()));
writer.writeString(m_extendedData);
}
}
} // namespace Io

View File

@ -1,24 +1,20 @@
#ifndef FIELD_H
#define FIELD_H
#ifndef PASSWORD_FILE_IO_FIELD_H
#define PASSWORD_FILE_IO_FIELD_H
#include <c++utilities/application/global.h>
#include "../global.h"
#include <iostream>
#include <string>
namespace Io {
enum class FieldType : int
{
Normal,
Password
};
enum class FieldType : int { Normal, Password };
class AccountEntry;
class LIB_EXPORT Field
{
class PASSWORD_FILE_EXPORT Field {
public:
Field();
Field(AccountEntry *tiedAccount, const std::string &name = std::string(), const std::string &value = std::string());
Field(AccountEntry *tiedAccount, std::istream &stream);
@ -38,8 +34,17 @@ private:
std::string m_value;
FieldType m_type;
AccountEntry *m_tiedAccount;
protected:
std::string m_extendedData;
};
inline Field::Field()
: m_type(FieldType::Normal)
, m_tiedAccount(nullptr)
{
}
/*!
* \brief Returns an indication whether the entry is empty.
*/
@ -111,7 +116,6 @@ inline bool Field::isValidType(int number)
{
return number >= 0 && number <= 1;
}
} // namespace Io
}
#endif // FIELD_H
#endif // PASSWORD_FILE_IO_FIELD_H

View File

@ -1,23 +1,35 @@
#include "parsingexception.h"
#include "./parsingexception.h"
namespace Io {
/*!
* \class ParsingException
* \brief The exception that is thrown when a parsing error occurs.
* \remarks Must not have any inline methods/c'tors/d'tors (so the vtable is invoked in any compile unit).
* Otherwise it is not possible to throw/catch it across library boundaries under Android.
*/
/*!
* \brief Constructs a parsing exception.
*/
ParsingException::ParsingException(const std::string &message) USE_NOTHROW :
runtime_error(message)
{}
ParsingException::ParsingException(const std::string &message) noexcept
: runtime_error(message)
{
}
/*!
* \brief Destroys the exception.
* \brief Constructs a parsing exception.
*/
ParsingException::~ParsingException() USE_NOTHROW
{}
ParsingException::ParsingException(const char *message) noexcept
: runtime_error(message)
{
}
/*!
* \brief Destroys the parsing exception.
*/
ParsingException::~ParsingException()
{
}
} // namespace Io

View File

@ -1,20 +1,20 @@
#ifndef PARSINGEXCEPTION_H
#define PARSINGEXCEPTION_H
#ifndef PASSWORD_FILE_IO_PARSINGEXCEPTION_H
#define PASSWORD_FILE_IO_PARSINGEXCEPTION_H
#include <c++utilities/application/global.h>
#include "../global.h"
#include <stdexcept>
#include <string>
namespace Io {
class LIB_EXPORT ParsingException : public std::runtime_error
{
class PASSWORD_FILE_EXPORT ParsingException : public std::runtime_error {
public:
ParsingException(const std::string &message = std::string()) USE_NOTHROW;
virtual ~ParsingException() USE_NOTHROW;
explicit ParsingException(const std::string &message = std::string()) noexcept;
explicit ParsingException(const char *message) noexcept;
~ParsingException() override;
};
}
} // namespace Io
#endif // PARSINGEXCEPTION_H
#endif // PASSWORD_FILE_IO_PARSINGEXCEPTION_H

File diff suppressed because it is too large Load Diff

View File

@ -1,56 +1,224 @@
#ifndef PASSWORDFILE_H
#define PASSWORDFILE_H
#include <c++utilities/io/binaryreader.h>
#include <c++utilities/io/binarywriter.h>
#include <string>
#include <iostream>
#include <fstream>
#include <memory>
namespace Io {
class NodeEntry;
class LIB_EXPORT PasswordFile
{
public:
explicit PasswordFile();
explicit PasswordFile(const std::string &path, const std::string &password);
PasswordFile(const PasswordFile &other);
~PasswordFile();
void open(bool readOnly = false);
void generateRootEntry();
void create();
void close();
void load();
void save(bool useEncryption = true, bool useCompression = true);
void clearEntries();
void clear();
void exportToTextfile(const std::string &targetPath) const;
void doBackup();
bool hasRootEntry() const;
const NodeEntry *rootEntry() const;
NodeEntry *rootEntry();
const std::string &path() const;
const char *password() const;
void setPath(const std::string &value);
void clearPath();
void setPassword(const std::string &value);
void clearPassword();
bool isEncryptionUsed();
bool isOpen() const;
size_t size();
private:
std::string m_path;
char m_password[32];
std::unique_ptr<NodeEntry> m_rootEntry;
std::fstream m_file;
IoUtilities::BinaryReader m_freader;
IoUtilities::BinaryWriter m_fwriter;
};
}
#endif // PASSWORDFILE_H
#ifndef PASSWORD_FILE_IO_PASSWORD_FILE_H
#define PASSWORD_FILE_IO_PASSWORD_FILE_H
#include "../global.h"
#include <c++utilities/io/binaryreader.h>
#include <c++utilities/io/binarywriter.h>
#include <c++utilities/io/nativefilestream.h>
#include <c++utilities/misc/flagenumclass.h>
#include <cstdint>
#include <fstream>
#include <iostream>
#include <memory>
#include <string>
namespace Io {
class NodeEntry;
enum class PasswordFileOpenFlags : std::uint64_t {
None = 0,
ReadOnly = 1,
Default = None,
};
PASSWORD_FILE_EXPORT std::string flagsToString(PasswordFileOpenFlags flags);
enum class PasswordFileSaveFlags : std::uint64_t {
None = 0,
Encryption = 1,
Compression = 2,
PasswordHashing = 4,
AllowToCreateNewFile = 8,
Default = Encryption | Compression | PasswordHashing | AllowToCreateNewFile,
};
PASSWORD_FILE_EXPORT std::string flagsToString(PasswordFileSaveFlags flags);
class PASSWORD_FILE_EXPORT PasswordFile {
public:
explicit PasswordFile();
explicit PasswordFile(const std::string &path, const std::string &password);
PasswordFile(const PasswordFile &other);
PasswordFile(PasswordFile &&other);
~PasswordFile();
CppUtilities::NativeFileStream &fileStream();
void open(PasswordFileOpenFlags options = PasswordFileOpenFlags::Default);
void opened();
void generateRootEntry();
void create();
void close();
void load();
std::uint32_t mininumVersion(PasswordFileSaveFlags options) const;
void save(PasswordFileSaveFlags options = PasswordFileSaveFlags::Default);
void write(PasswordFileSaveFlags options = PasswordFileSaveFlags::Default);
void clearEntries();
void clear();
void exportToTextfile(const std::string &targetPath) const;
void doBackup();
bool hasRootEntry() const;
const NodeEntry *rootEntry() const;
NodeEntry *rootEntry();
const std::string &path() const;
const std::string &password() const;
void setPath(const std::string &value);
void clearPath();
void setPassword(const std::string &password);
void setPassword(const char *password, const std::size_t passwordSize);
void clearPassword();
bool isEncryptionUsed();
bool isOpen() const;
std::string &extendedHeader();
const std::string &extendedHeader() const;
std::string &encryptedExtendedHeader();
const std::string &encryptedExtendedHeader() const;
std::size_t size();
std::uint32_t version() const;
PasswordFileOpenFlags openOptions() const;
PasswordFileSaveFlags saveOptions() const;
std::string summary(PasswordFileSaveFlags saveOptions) const;
private:
std::string m_path;
std::string m_password;
std::unique_ptr<NodeEntry> m_rootEntry;
std::string m_extendedHeader;
std::string m_encryptedExtendedHeader;
CppUtilities::NativeFileStream m_file;
CppUtilities::BinaryReader m_freader;
CppUtilities::BinaryWriter m_fwriter;
std::uint32_t m_version;
PasswordFileOpenFlags m_openOptions;
PasswordFileSaveFlags m_saveOptions;
};
/*!
* \brief Returns the underlying file stream.
*/
inline CppUtilities::NativeFileStream &PasswordFile::fileStream()
{
return m_file;
}
/*!
* \brief Returns the current file path.
*/
inline const std::string &PasswordFile::path() const
{
return m_path;
}
/*!
* \brief Clears the current path. Causes the file to be closed if currently opened.
*/
inline void PasswordFile::clearPath()
{
close();
m_path.clear();
}
/*!
* \brief Returns the current password. It will be used when loading or saving using encryption.
*/
inline const std::string &PasswordFile::password() const
{
return m_password;
}
/*!
* \brief Sets the current password. It will be used when loading an encrypted file or when saving using encryption.
*/
inline void PasswordFile::setPassword(const std::string &password)
{
m_password = password;
}
/*!
* \brief Sets the current password. It will be used when loading an encrypted file or when saving using encryption.
*/
inline void PasswordFile::setPassword(const char *password, const size_t passwordSize)
{
m_password.assign(password, passwordSize);
}
/*!
* \brief Clears the current password.
*/
inline void PasswordFile::clearPassword()
{
m_password.clear();
}
/*!
* \brief Returns an indication whether the file is open.
*/
inline bool PasswordFile::isOpen() const
{
return m_file.is_open();
}
/*!
* \brief Returns the extended header.
*/
inline std::string &PasswordFile::extendedHeader()
{
return m_extendedHeader;
}
/*!
* \brief Returns the extended header.
*/
inline const std::string &PasswordFile::extendedHeader() const
{
return m_extendedHeader;
}
/*!
* \brief Returns the encrypted extended header.
*/
inline std::string &PasswordFile::encryptedExtendedHeader()
{
return m_encryptedExtendedHeader;
}
/*!
* \brief Returns the encrypted extended header.
*/
inline const std::string &PasswordFile::encryptedExtendedHeader() const
{
return m_encryptedExtendedHeader;
}
/*!
* \brief Returns the file version used the last time when saving the file (the version of the file as it is on the disk).
* \remarks The version might change when re-saving with different options. See mininumVersion().
*/
inline std::uint32_t PasswordFile::version() const
{
return m_version;
}
/*!
* \brief Returns the options used to open the file.
*/
inline PasswordFileOpenFlags PasswordFile::openOptions() const
{
return m_openOptions;
}
/*!
* \brief Returns the save options used the last time when saving the file.
*/
inline PasswordFileSaveFlags PasswordFile::saveOptions() const
{
return m_saveOptions;
}
} // namespace Io
CPP_UTILITIES_MARK_FLAG_ENUM_CLASS(Io, Io::PasswordFileOpenFlags);
CPP_UTILITIES_MARK_FLAG_ENUM_CLASS(Io, Io::PasswordFileSaveFlags);
#endif // PASSWORD_FILE_IO_PASSWORD_FILE_H

File diff suppressed because it is too large Load Diff

View File

@ -1,77 +0,0 @@
projectname = passwordfile
# include ../../common.pri when building as part of a subdirs project; otherwise include general.pri
!include(../../common.pri) {
!include(./general.pri) {
error("Couldn't find the common.pri or the general.pri file!")
}
}
TEMPLATE = lib
CONFIG -= qt
win32 {
CONFIG += dll
}
# files
SOURCES += aes/aes.cpp \
io/cryptoexception.cpp \
io/entry.cpp \
io/field.cpp \
io/parsingexception.cpp \
io/passwordfile.cpp \
util/opensslrandomdevice.cpp \
util/openssl.cpp
HEADERS += aes/aes.h \
io/cryptoexception.h \
io/entry.h \
io/field.h \
io/parsingexception.h \
io/passwordfile.h \
util/opensslrandomdevice.h \
util/openssl.h
OTHER_FILES += \
pkgbuild/default/PKGBUILD \
pkgbuild/mingw-w64/PKGBUILD
# libs and includepath
CONFIG(debug, debug|release) {
LIBS += -L../../ -lc++utilitiesd
} else {
LIBS += -L../../ -lc++utilities
}
win32 {
contains(QMAKE_TARGET.arch, x86_64):{
LIBS += -L../../../openssl-mingw_amd64/lib/ -lcrypto
INCLUDEPATH += ../../../build/openssl-mingw_amd64/include
} else {
LIBS += -L../../../openssl-mingw_i386/lib/ -lcrypto
INCLUDEPATH += ../../../build/openssl-mingw_i386/include
}
} else {
android {
LIBS += -L/opt/android-openssl/usr/lib/ -lcrypto
INCLUDEPATH += /opt/android-openssl/usr/include
ANDROID_PACKAGE_SOURCE_DIR = $$PWD/android
ANDROID_EXTRA_LIBS = /opt/android-openssl/usr/lib/libcrypto.so
} else {
LIBS += -lcrypto
}
}
LIBS += -lz
INCLUDEPATH += ../
# installs
!android {
target.path = $$(INSTALL_ROOT)/lib
INSTALLS += target
for(dir, $$list(io util)) {
eval(inc_$${dir} = $${dir})
inc_$${dir}.path = $$(INSTALL_ROOT)/include/$$projectname/$${dir}
inc_$${dir}.files = $${dir}/*.h
INSTALLS += inc_$${dir}
}
}

View File

@ -1,26 +0,0 @@
pkgname=passwordfile
pkgver=2.0.3
pkgrel=3
arch=('i686' 'x86_64')
pkgdesc="A simple password store using AES-256-CBC encryption via OpenSSL."
license=('GPL')
depends=('c++utilities' 'openssl')
makedepends=('qt5-base')
install=
url="https://github.com/Martchus/passwordfile"
source=("passwordfile-${pkgver}.tar.gz::https://github.com/Martchus/passwordfile/archive/v${pkgver}.tar.gz")
_reponame=passwordfile
sha256sums=('d359927292464fcf41c8a11315ff79e2')
# head end
build() {
cd "$srcdir/${PROJECT_DIR_NAME:-$_reponame-$pkgver}"
INSTALL_ROOT=$pkgdir/usr/ qmake-qt5 "$pkgname.pro" -r -spec linux-g++
make
}
package() {
cd "$srcdir/${PROJECT_DIR_NAME:-$_reponame-$pkgver}"
make install
}

View File

@ -1,47 +0,0 @@
_name=passwordfile
pkgname=mingw-w64-passwordfile
pkgver=2.0.3
pkgrel=3
arch=('any')
pkgdesc="A library for reading and writing AES-256-CBC encrypted password files using OpenSSL (mingw-w64)."
license=('GPL')
depends=('mingw-w64-crt' 'mingw-w64-c++utilities' 'mingw-w64-openssl')
makedepends=('mingw-w64-gcc')
url="https://github.com/Martchus/passwordfile"
source=("passwordfile-${pkgver}.tar.gz::https://github.com/Martchus/passwordfile/archive/v${pkgver}.tar.gz")
_reponame=passwordfile
sha256sums=('4e94aff9225d8873f752995c1bcc5f15')
options=('staticlibs' '!strip')
_architectures="i686-w64-mingw32 x86_64-w64-mingw32"
# head end
build() {
cd "$srcdir/${PROJECT_DIR_NAME:-$_reponame-$pkgver}"
# build for each architecture
for _arch in ${_architectures}; do
mkdir -p build-${_arch} && pushd build-${_arch}
INSTALL_ROOT=$pkgdir/usr/ ${_arch}-qmake-qt5 -r ../${_name}.pro
make
popd
done
}
package() {
cd "$srcdir/${PROJECT_DIR_NAME:-$_reponame-$pkgver}"
for _arch in ${_architectures}; do
# bin stuff
pushd build-${_arch}
${_arch}-strip --strip-unneeded ./release/${_name}.dll
${_arch}-strip --strip-unneeded ./release/lib${_name}.dll.a
install -m755 -D ./release/${_name}.dll $pkgdir/usr/${_arch}/bin/${_name}.dll
install -m755 -D ./release/lib${_name}.dll.a $pkgdir/usr/${_arch}/lib/lib${_name}.dll.a
popd
# include files
for dir in io util
do
mkdir -p $pkgdir/usr/${_arch}/include/${_name}/$dir
install -m644 -D ./$dir/*.h $pkgdir/usr/${_arch}/include/${_name}/$dir
done
done
}

BIN
testfiles/testfile1.pwmgr Normal file

Binary file not shown.

BIN
testfiles/testfile2.pwmgr Normal file

Binary file not shown.

195
tests/entrytests.cpp Normal file
View File

@ -0,0 +1,195 @@
#include "../io/entry.h"
#include "./utils.h"
#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
using namespace std;
using namespace Io;
using namespace CppUtilities::Literals;
using namespace CPPUNIT_NS;
/*!
* \brief The EntryTests class tests the Io::Entry class.
*/
class EntryTests : public TestFixture {
CPPUNIT_TEST_SUITE(EntryTests);
CPPUNIT_TEST(testNewEntryCorrectlyInitialized);
CPPUNIT_TEST(testNesting);
CPPUNIT_TEST(testEntryByPath);
CPPUNIT_TEST(testUniqueLabels);
CPPUNIT_TEST_SUITE_END();
public:
void setUp() override;
void tearDown() override;
void testNewEntryCorrectlyInitialized();
void testNesting();
void testEntryByPath();
void testUniqueLabels();
};
CPPUNIT_TEST_SUITE_REGISTRATION(EntryTests);
void EntryTests::setUp()
{
}
void EntryTests::tearDown()
{
}
/*!
* \brief Tests whether a new entry is correctly initialized (basically empty, default values set).
*/
void EntryTests::testNewEntryCorrectlyInitialized()
{
const NodeEntry nodeEntry;
CPPUNIT_ASSERT(!nodeEntry.parent());
CPPUNIT_ASSERT_EQUAL(string(), nodeEntry.label());
CPPUNIT_ASSERT_EQUAL(0_st, nodeEntry.children().size());
CPPUNIT_ASSERT_EQUAL(-1, nodeEntry.index());
CPPUNIT_ASSERT_EQUAL(list<string>{ "" }, nodeEntry.path());
CPPUNIT_ASSERT(nodeEntry.isExpandedByDefault());
CPPUNIT_ASSERT_EQUAL(EntryType::Node, nodeEntry.type());
const AccountEntry accountEntry;
CPPUNIT_ASSERT(!accountEntry.parent());
CPPUNIT_ASSERT_EQUAL(string(), nodeEntry.label());
CPPUNIT_ASSERT_EQUAL(0_st, accountEntry.fields().size());
CPPUNIT_ASSERT_EQUAL(-1, accountEntry.index());
CPPUNIT_ASSERT_EQUAL(list<string>{ "" }, accountEntry.path());
CPPUNIT_ASSERT_EQUAL(EntryType::Account, accountEntry.type());
const NodeEntry nodeEntryWithLabel("foo");
CPPUNIT_ASSERT(!nodeEntryWithLabel.parent());
CPPUNIT_ASSERT_EQUAL("foo"s, nodeEntryWithLabel.label());
CPPUNIT_ASSERT_EQUAL(list<string>{ "foo" }, nodeEntryWithLabel.path());
}
void EntryTests::testNesting()
{
NodeEntry root("root");
// create account under root
auto *const account = new AccountEntry("account", &root);
CPPUNIT_ASSERT_EQUAL_MESSAGE("account appended to root's children", vector<Entry *>{ account }, root.children());
CPPUNIT_ASSERT_EQUAL_MESSAGE("account's path contains parent", list<string>{ "root" CPP_UTILITIES_PP_COMMA "account" }, account->path());
CPPUNIT_ASSERT_EQUAL_MESSAGE("index initialized", 0, account->index());
CPPUNIT_ASSERT_MESSAGE("actual assignment happened", account->parent() == &root);
// create new node entry under root
auto *const node = new NodeEntry("node", &root);
CPPUNIT_ASSERT_EQUAL_MESSAGE("node appended to root's children", vector<Entry *>{ account CPP_UTILITIES_PP_COMMA node }, root.children());
CPPUNIT_ASSERT_EQUAL_MESSAGE("account's path contains parent", list<string>{ "root" CPP_UTILITIES_PP_COMMA "node" }, node->path());
CPPUNIT_ASSERT_EQUAL_MESSAGE("index initialized", 1, node->index());
CPPUNIT_ASSERT_MESSAGE("actual assignment happened", node->parent() == &root);
// nothing bad happens if we're setting the same parent again
node->setParent(&root);
CPPUNIT_ASSERT_EQUAL_MESSAGE("root's children not altered", vector<Entry *>{ account CPP_UTILITIES_PP_COMMA node }, root.children());
CPPUNIT_ASSERT_EQUAL_MESSAGE("index not altered", 0, account->index());
CPPUNIT_ASSERT_EQUAL_MESSAGE("index not altered", 1, node->index());
// change the children's order
node->setParent(&root, 0);
CPPUNIT_ASSERT_EQUAL_MESSAGE("root's children not altered", vector<Entry *>{ node CPP_UTILITIES_PP_COMMA account }, root.children());
CPPUNIT_ASSERT_EQUAL_MESSAGE("index updated", 1, account->index());
CPPUNIT_ASSERT_EQUAL_MESSAGE("index updated", 0, node->index());
// change the children's order the other way
node->setParent(&root, 1);
CPPUNIT_ASSERT_EQUAL_MESSAGE("root's children not altered", vector<Entry *>{ account CPP_UTILITIES_PP_COMMA node }, root.children());
CPPUNIT_ASSERT_EQUAL_MESSAGE("index updated", 0, account->index());
CPPUNIT_ASSERT_EQUAL_MESSAGE("index updated", 1, node->index());
// specifying an invalid index inserts at the end
auto *const anotherNode = new NodeEntry("another node", &root);
anotherNode->setParent(&root, 2000);
CPPUNIT_ASSERT_EQUAL_MESSAGE(
"another node is at the end", vector<Entry *>{ account CPP_UTILITIES_PP_COMMA node CPP_UTILITIES_PP_COMMA anotherNode }, root.children());
CPPUNIT_ASSERT_EQUAL_MESSAGE("index initialized", 2, anotherNode->index());
// move node into another node
node->setParent(anotherNode);
CPPUNIT_ASSERT_EQUAL_MESSAGE("index not altered", 0, account->index());
CPPUNIT_ASSERT_EQUAL_MESSAGE("index updated", 0, node->index());
CPPUNIT_ASSERT_EQUAL_MESSAGE("index updated", 1, anotherNode->index());
CPPUNIT_ASSERT_EQUAL_MESSAGE("root's childrens updated", vector<Entry *>{ account CPP_UTILITIES_PP_COMMA anotherNode }, root.children());
CPPUNIT_ASSERT_EQUAL_MESSAGE("another node's childrens updated", vector<Entry *>{ node }, anotherNode->children());
CPPUNIT_ASSERT_MESSAGE("node is still an indirect child of root", node->isIndirectChildOf(&root));
CPPUNIT_ASSERT_MESSAGE("node is direct and hence also an indirect child of another node", node->isIndirectChildOf(anotherNode));
CPPUNIT_ASSERT_MESSAGE("another node is no indirect child of node", !anotherNode->isIndirectChildOf(node));
// replace children
auto *const replacementNode = new NodeEntry("replacement", &root);
CPPUNIT_ASSERT_EQUAL_MESSAGE("replacement's index initialized", 2, replacementNode->index());
root.replaceChild(1, replacementNode);
CPPUNIT_ASSERT_EQUAL_MESSAGE("root's childrens updated", vector<Entry *>{ account CPP_UTILITIES_PP_COMMA replacementNode }, root.children());
CPPUNIT_ASSERT_MESSAGE("another node parentless", !anotherNode->parent());
CPPUNIT_ASSERT_EQUAL_MESSAGE("another node's index updated", -1, anotherNode->index());
CPPUNIT_ASSERT_EQUAL_MESSAGE("replacement's index updated", 1, replacementNode->index());
// delete children
anotherNode->setParent(&root, 0);
CPPUNIT_ASSERT_EQUAL_MESSAGE("index updated", 0, anotherNode->index());
CPPUNIT_ASSERT_EQUAL_MESSAGE("index updated", 1, account->index());
CPPUNIT_ASSERT_EQUAL_MESSAGE("index updated", 2, replacementNode->index());
root.deleteChildren(0, 1);
CPPUNIT_ASSERT_EQUAL_MESSAGE("root's childrens updated", vector<Entry *>{ account CPP_UTILITIES_PP_COMMA replacementNode }, root.children());
CPPUNIT_ASSERT_EQUAL_MESSAGE("index updated", 0, account->index());
CPPUNIT_ASSERT_EQUAL_MESSAGE("index updated", 1, replacementNode->index());
}
void EntryTests::testEntryByPath()
{
NodeEntry root("root");
list<string> path;
auto createNode = EntryType::Node;
auto createAccount = EntryType::Account;
CPPUNIT_ASSERT_MESSAGE("nullptr for empty path", !root.entryByPath(path));
path = { "root" };
CPPUNIT_ASSERT_EQUAL_MESSAGE("return current instance", static_cast<Entry *>(&root), root.entryByPath(path));
path = { "root", "foo" };
CPPUNIT_ASSERT_MESSAGE("nullptr for non-existent path", !root.entryByPath(path));
path = { "root", "node" };
const auto *const node = root.entryByPath(path, true, &createNode);
CPPUNIT_ASSERT_MESSAGE("node created", node);
CPPUNIT_ASSERT_EQUAL_MESSAGE("actually a node", EntryType::Node, node->type());
CPPUNIT_ASSERT_EQUAL_MESSAGE("label assigned", "node"s, node->label());
path = { "root", "account" };
const auto *const account = root.entryByPath(path, true, &createAccount);
CPPUNIT_ASSERT_MESSAGE("account created", account);
CPPUNIT_ASSERT_EQUAL_MESSAGE("actually an account", EntryType::Account, account->type());
CPPUNIT_ASSERT_EQUAL_MESSAGE("label assigned", "account"s, account->label());
path = { "root", "account", "foo" };
CPPUNIT_ASSERT_MESSAGE("nullptr for trying to add child to account", !root.entryByPath(path, true, &createAccount));
path = { "root", "node", "foo" };
const auto *const nestedAccount = root.entryByPath(path, true, &createAccount);
CPPUNIT_ASSERT_MESSAGE("nested account created", nestedAccount);
CPPUNIT_ASSERT_EQUAL_MESSAGE("nested account created", EntryType::Account, nestedAccount->type());
CPPUNIT_ASSERT_EQUAL_MESSAGE("label assigned", "foo"s, nestedAccount->label());
CPPUNIT_ASSERT_EQUAL_MESSAGE(
"path actually correct", list<string>{ "root" CPP_UTILITIES_PP_COMMA "node" CPP_UTILITIES_PP_COMMA "foo" }, nestedAccount->path());
}
void EntryTests::testUniqueLabels()
{
NodeEntry root("root");
const auto *const fooEntry = new AccountEntry("foo", &root);
CPP_UTILITIES_UNUSED(fooEntry)
const auto *const foo2Entry = new AccountEntry("foo", &root);
CPPUNIT_ASSERT_EQUAL_MESSAGE("2nd foo renamed to foo 2", "foo 2"s, foo2Entry->label());
const auto *const foo3Entry = new AccountEntry("foo", &root);
CPPUNIT_ASSERT_EQUAL_MESSAGE("3rd foo renamed to foo 3", "foo 3"s, foo3Entry->label());
}

69
tests/fieldtests.cpp Normal file
View File

@ -0,0 +1,69 @@
#include "../io/entry.h"
#include "../io/field.h"
#include "./utils.h"
#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
using namespace std;
using namespace Io;
using namespace CppUtilities::Literals;
using namespace CPPUNIT_NS;
/*!
* \brief The FieldTests class tests the Io::Field class.
*/
class FieldTests : public TestFixture {
CPPUNIT_TEST_SUITE(FieldTests);
CPPUNIT_TEST(testNewFieldCorrectlyInitialized);
CPPUNIT_TEST(testMutation);
CPPUNIT_TEST_SUITE_END();
public:
void setUp() override;
void tearDown() override;
void testNewFieldCorrectlyInitialized();
void testMutation();
};
CPPUNIT_TEST_SUITE_REGISTRATION(FieldTests);
void FieldTests::setUp()
{
}
void FieldTests::tearDown()
{
}
/*!
* \brief Tests whether a new field is correctly initialized (default values set).
*/
void FieldTests::testNewFieldCorrectlyInitialized()
{
AccountEntry account("account");
const Field emptyField(&account);
CPPUNIT_ASSERT(emptyField.isEmpty());
const Field field(&account, "foo", "bar");
CPPUNIT_ASSERT(!field.isEmpty());
CPPUNIT_ASSERT_EQUAL(&account, field.tiedAccount());
CPPUNIT_ASSERT_EQUAL("foo"s, field.name());
CPPUNIT_ASSERT_EQUAL("bar"s, field.value());
CPPUNIT_ASSERT_EQUAL(FieldType::Normal, field.type());
}
void FieldTests::testMutation()
{
AccountEntry account("account");
Field field(&account, "foo", "bar");
field.setName("bar");
field.setValue("foo");
field.setType(FieldType::Password);
CPPUNIT_ASSERT_EQUAL("bar"s, field.name());
CPPUNIT_ASSERT_EQUAL("foo"s, field.value());
CPPUNIT_ASSERT_EQUAL(FieldType::Password, field.type());
}

View File

@ -0,0 +1,51 @@
#include "../util/opensslrandomdevice.h"
#include "./utils.h"
#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
#include <random>
using namespace std;
using namespace Util;
using namespace CppUtilities::Literals;
using namespace CPPUNIT_NS;
/*!
* \brief The OpenSslRandomDeviceTests class tests the Util::OpenSslRandomDevice class.
*/
class OpenSslRandomDeviceTests : public TestFixture {
CPPUNIT_TEST_SUITE(OpenSslRandomDeviceTests);
CPPUNIT_TEST(testUsageWithStandardClasses);
CPPUNIT_TEST_SUITE_END();
public:
void setUp() override;
void tearDown() override;
void testUsageWithStandardClasses();
};
CPPUNIT_TEST_SUITE_REGISTRATION(OpenSslRandomDeviceTests);
void OpenSslRandomDeviceTests::setUp()
{
}
void OpenSslRandomDeviceTests::tearDown()
{
}
/*!
* \brief Tests using the OpenSslRandomDevice with std::uniform_int_distribution.
*/
void OpenSslRandomDeviceTests::testUsageWithStandardClasses()
{
uniform_int_distribution<> dist(1, 10);
const Util::OpenSslRandomDevice random;
const auto val = dist(random);
CPPUNIT_ASSERT_GREATEREQUAL(1, val);
CPPUNIT_ASSERT_LESSEQUAL(10, val);
}

64
tests/opensslutils.cpp Normal file
View File

@ -0,0 +1,64 @@
#include "../util/openssl.h"
#include <c++utilities/conversion/stringconversion.h>
#include <c++utilities/tests/testutils.h>
#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
#include <random>
using namespace std;
using namespace Util::OpenSsl;
using namespace CppUtilities;
using namespace CppUtilities::Literals;
using namespace CPPUNIT_NS;
/*!
* \brief The OpenSslUtilsTests class tests the functions in the Util::OpenSsl namespace.
*/
class OpenSslUtilsTests : public TestFixture {
CPPUNIT_TEST_SUITE(OpenSslUtilsTests);
CPPUNIT_TEST(testComputeSha256Sum);
CPPUNIT_TEST(testGenerateRandomNumber);
CPPUNIT_TEST_SUITE_END();
public:
void setUp() override;
void tearDown() override;
void testComputeSha256Sum();
void testGenerateRandomNumber();
};
CPPUNIT_TEST_SUITE_REGISTRATION(OpenSslUtilsTests);
void OpenSslUtilsTests::setUp()
{
}
void OpenSslUtilsTests::tearDown()
{
}
void OpenSslUtilsTests::testComputeSha256Sum()
{
const char someString[] = "hello world";
Sha256Sum sum = computeSha256Sum(reinterpret_cast<unsigned const char *>(someString), sizeof(someString));
string sumAsHex;
sumAsHex.reserve(64);
for (unsigned char hashNumber : sum.data) {
const string digits = numberToString(hashNumber, static_cast<unsigned char>(16));
sumAsHex.push_back(digits.size() < 2 ? '0' : digits.front());
sumAsHex.push_back(digits.back());
}
CPPUNIT_ASSERT_EQUAL("430646847E70344C09F58739E99D5BC96EAC8D5FE7295CF196B986279876BF9B"s, sumAsHex);
// note that the termination char is hashed as well
}
void OpenSslUtilsTests::testGenerateRandomNumber()
{
CPPUNIT_ASSERT_EQUAL(static_cast<uint32_t>(0u), generateRandomNumber(0u, 0u));
CPPUNIT_ASSERT_EQUAL(static_cast<uint32_t>(1u), generateRandomNumber(1u, 1u));
}

237
tests/passwordfiletests.cpp Normal file
View File

@ -0,0 +1,237 @@
#include "../io/cryptoexception.h"
#include "../io/entry.h"
#include "../io/passwordfile.h"
#include "./utils.h"
#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
using namespace std;
using namespace Io;
using namespace CppUtilities;
using namespace CppUtilities::Literals;
using namespace CPPUNIT_NS;
/*!
* \brief The PasswordFileTests class tests the Io::PasswordFile class.
*/
class PasswordFileTests : public TestFixture {
CPPUNIT_TEST_SUITE(PasswordFileTests);
CPPUNIT_TEST(testReading);
CPPUNIT_TEST(testBasicWriting);
CPPUNIT_TEST(testExtendedWriting);
CPPUNIT_TEST_SUITE_END();
public:
void setUp() override;
void tearDown() override;
void testReading();
void testReading(const string &context, const string &testfile1path, const string &testfile1password, const string &testfile2,
const string &testfile2password, bool testfile2Mod, bool extendedHeaderMod);
void testBasicWriting();
void testExtendedWriting();
};
CPPUNIT_TEST_SUITE_REGISTRATION(PasswordFileTests);
void PasswordFileTests::setUp()
{
}
void PasswordFileTests::tearDown()
{
}
/*!
* \brief Tests reading the testfiles testfile{1,2}.pwmgr.
*/
void PasswordFileTests::testReading()
{
testReading("read", testFilePath("testfile1.pwmgr"), "123456", testFilePath("testfile2.pwmgr"), string(), false, false);
}
void PasswordFileTests::testReading(const string &context, const string &testfile1path, const string &testfile1password, const string &testfile2,
const string &testfile2password, bool testfilesMod, bool extendedHeaderMod)
{
PasswordFile file;
// open testfile 1 ...
file.setPath(testfile1path);
file.open(PasswordFileOpenFlags::ReadOnly);
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, !testfile1password.empty(), file.isEncryptionUsed());
// attempt to decrypt using a wrong password
file.setPassword(testfile1password + "asdf");
if (!testfile1password.empty()) {
CPPUNIT_ASSERT_THROW(file.load(), CryptoException);
}
// attempt to decrypt using the correct password
file.setPassword(testfile1password);
file.load();
// test root entry
const NodeEntry *const rootEntry = file.rootEntry();
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, "testfile1"s, rootEntry->label());
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, 4_st, rootEntry->children().size());
// test testaccount1
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, "testaccount1"s, rootEntry->children()[0]->label());
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, EntryType::Account, rootEntry->children()[0]->type());
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, "pin"s, static_cast<AccountEntry *>(rootEntry->children()[0])->fields().at(0).name());
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, "123456"s, static_cast<AccountEntry *>(rootEntry->children()[0])->fields().at(0).value());
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, FieldType::Password, static_cast<AccountEntry *>(rootEntry->children()[0])->fields().at(0).type());
CPPUNIT_ASSERT(
static_cast<AccountEntry *>(rootEntry->children()[0])->fields().at(0).tiedAccount() == static_cast<AccountEntry *>(rootEntry->children()[0]));
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, FieldType::Normal, static_cast<AccountEntry *>(rootEntry->children()[0])->fields().at(1).type());
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, 2_st, static_cast<AccountEntry *>(rootEntry->children()[0])->fields().size());
// test testaccount2
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, "testaccount2"s, rootEntry->children()[1]->label());
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, EntryType::Account, rootEntry->children()[1]->type());
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, 0_st, static_cast<AccountEntry *>(rootEntry->children()[1])->fields().size());
// test testcategory1
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, "testcategory1"s, rootEntry->children()[2]->label());
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, EntryType::Node, rootEntry->children()[2]->type());
const NodeEntry *const category = static_cast<NodeEntry *>(rootEntry->children()[2]);
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, 3_st, category->children().size());
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, EntryType::Node, category->children()[2]->type());
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, 2_st, static_cast<NodeEntry *>(category->children()[2])->children().size());
// test testaccount3
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, "testaccount3"s, rootEntry->children()[3]->label());
if (!testfilesMod) {
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, "encryption, compression"s, flagsToString(file.saveOptions()));
} else if (extendedHeaderMod) {
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, "foo"s, file.extendedHeader());
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, "encryption, password hashing"s, flagsToString(file.saveOptions()));
} else {
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, ""s, file.extendedHeader());
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, "compression"s, flagsToString(file.saveOptions()));
}
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, ""s, file.encryptedExtendedHeader());
// open testfile 2
file.setPath(testfile2);
file.open(PasswordFileOpenFlags::ReadOnly);
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, !testfile2password.empty(), file.isEncryptionUsed());
file.setPassword(testfile2password);
file.load();
const NodeEntry *const rootEntry2 = file.rootEntry();
if (testfilesMod) {
if (extendedHeaderMod) {
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, static_cast<std::uint32_t>(6), file.version());
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, "encryption, password hashing"s, flagsToString(file.saveOptions()));
} else {
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, static_cast<std::uint32_t>(3), file.version());
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, "encryption"s, flagsToString(file.saveOptions()));
}
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, "testfile2 - modified"s, rootEntry2->label());
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, 2_st, rootEntry2->children().size());
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, "newAccount"s, rootEntry2->children()[1]->label());
} else {
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, static_cast<std::uint32_t>(3), file.version());
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, "testfile2"s, rootEntry2->label());
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, 1_st, rootEntry2->children().size());
}
if (extendedHeaderMod) {
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, "foo"s, file.extendedHeader());
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, "bar"s, file.encryptedExtendedHeader());
} else {
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, ""s, file.extendedHeader());
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, ""s, file.encryptedExtendedHeader());
}
}
/*!
* \brief Tests writing (and reading again) using basic features.
*/
void PasswordFileTests::testBasicWriting()
{
const string testfile1 = workingCopyPath("testfile1.pwmgr");
const string testfile2 = workingCopyPath("testfile2.pwmgr");
PasswordFile file;
// resave testfile 1
file.setPath(testfile1);
file.open();
file.setPassword("123456");
file.load();
file.doBackup();
file.save(PasswordFileSaveFlags::Compression);
// resave testfile 2
file.setPath(testfile2);
file.open();
file.load();
file.rootEntry()->setLabel("testfile2 - modified");
new AccountEntry("newAccount", file.rootEntry());
file.setPassword("654321");
file.doBackup();
file.save(PasswordFileSaveFlags::Encryption);
// check results using the reading test
testReading("basic writing", testfile1, string(), testfile2, "654321", true, false);
// check backup files
testReading("basic writing", testfile1 + ".backup", "123456", testfile2 + ".backup", string(), false, false);
}
/*!
* \brief Tests writing (and reading again) using extended features.
*/
void PasswordFileTests::testExtendedWriting()
{
const string testfile1 = workingCopyPath("testfile1.pwmgr");
const string testfile2 = workingCopyPath("testfile2.pwmgr");
PasswordFile file;
// resave testfile 1
file.setPath(testfile1);
file.open();
file.setPassword("123456");
file.load();
CPPUNIT_ASSERT_EQUAL(""s, file.extendedHeader());
CPPUNIT_ASSERT_EQUAL(""s, file.encryptedExtendedHeader());
file.doBackup();
file.extendedHeader() = "foo";
file.save(PasswordFileSaveFlags::Encryption | PasswordFileSaveFlags::PasswordHashing);
// resave testfile 2
file.setPath(testfile2);
file.open();
file.load();
CPPUNIT_ASSERT_EQUAL(""s, file.extendedHeader());
CPPUNIT_ASSERT_EQUAL(""s, file.encryptedExtendedHeader());
file.rootEntry()->setLabel("testfile2 - modified");
auto *const newAccount = new AccountEntry("newAccount", file.rootEntry());
file.setPassword("654321");
file.extendedHeader() = "foo";
file.encryptedExtendedHeader() = "bar";
file.doBackup();
file.save(PasswordFileSaveFlags::Encryption | PasswordFileSaveFlags::PasswordHashing);
// check results using the reading test
testReading("extended writing", testfile1, "123456", testfile2, "654321", true, true);
// check backup files
testReading("extended writing", testfile1 + ".backup", "123456", testfile2 + ".backup", string(), false, false);
// remove newAccount again to check what happens if the file size decreases
const auto fileSize = file.size();
delete newAccount;
file.save(PasswordFileSaveFlags::Encryption | PasswordFileSaveFlags::PasswordHashing);
file.close();
file.clearEntries();
file.open();
CPPUNIT_ASSERT_LESS(fileSize, file.size());
file.load();
auto path = std::list<std::string>{ "newAccount" };
CPPUNIT_ASSERT(file.rootEntry());
CPPUNIT_ASSERT(!file.rootEntry()->entryByPath(path));
}

30
tests/utils.h Normal file
View File

@ -0,0 +1,30 @@
#ifndef PASSWORDFILE_TESTS_UTILS_H
#define PASSWORDFILE_TESTS_UTILS_H
#include "../io/entry.h"
#include "../io/field.h"
#include <c++utilities/conversion/stringconversion.h>
#include <c++utilities/misc/traits.h>
#include <ostream>
namespace CppUtilities {
inline std::ostream &operator<<(std::ostream &out, const Io::Entry *entry)
{
return out << joinStrings(entry->path(), "/");
}
inline std::ostream &operator<<(std::ostream &out, const Io::Field *field)
{
return out << field->name() << '=' << field->value();
}
} // namespace CppUtilities
#include <c++utilities/tests/testutils.h>
using namespace CppUtilities;
#endif // PASSWORDFILE_TESTS_UTILS_H

View File

@ -1,23 +1,41 @@
#include "openssl.h"
#include "./openssl.h"
#include "./opensslrandomdevice.h"
#include <c++utilities/conversion/binaryconversion.h>
#include <openssl/conf.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/sha.h>
#include <random>
/*!
* \brief Contains utility classes and functions.
*/
namespace Util {
/*!
* \brief Contains functions utilizing the usage of OpenSSL.
*/
namespace OpenSsl {
static_assert(Sha256Sum::size == SHA256_DIGEST_LENGTH, "SHA-256 sum fits into Sha256Sum struct");
/*!
* \brief Initializes OpenSSL.
*/
void init()
{
// load the human readable error strings for libcrypto
ERR_load_crypto_strings();
// load all digest and cipher algorithms
OpenSSL_add_all_algorithms();
// load config file, and other important initialisation
OPENSSL_config(NULL);
}
/*!
* \brief Cleans resources of OpenSSL.
*/
void clean()
{
// removes all digests and ciphers
@ -26,6 +44,26 @@ void clean()
ERR_free_strings();
}
/*!
* \brief Computes a SHA-256 sum using OpenSSL.
*/
Sha256Sum computeSha256Sum(const unsigned char *buffer, std::size_t size)
{
auto hash = Sha256Sum();
SHA256(buffer, size, hash.data);
return hash;
}
/*!
* \brief Generates a random number using OpenSSL.
*/
uint32_t generateRandomNumber(uint32_t min, uint32_t max)
{
OpenSslRandomDevice dev;
std::default_random_engine rng(dev());
std::uniform_int_distribution<uint32_t> dist(min, max);
return dist(rng);
}
} // namespace OpenSsl
} // namespace Util

View File

@ -1,17 +1,26 @@
#ifndef OPENSSL_H
#define OPENSSL_H
#ifndef PASSWORD_FILE_UTIL_OPENSSL_H
#define PASSWORD_FILE_UTIL_OPENSSL_H
#include <c++utilities/application/global.h>
#include "../global.h"
#include <cstddef>
#include <cstdint>
namespace Util {
namespace OpenSsl {
void LIB_EXPORT init();
void LIB_EXPORT clean();
struct Sha256Sum {
static constexpr std::size_t size = 32;
unsigned char data[size] = { 0 };
};
}
PASSWORD_FILE_EXPORT void init();
PASSWORD_FILE_EXPORT void clean();
PASSWORD_FILE_EXPORT Sha256Sum computeSha256Sum(const unsigned char *buffer, std::size_t size);
PASSWORD_FILE_EXPORT std::uint32_t generateRandomNumber(std::uint32_t min, std::uint32_t max);
}
} // namespace OpenSsl
} // namespace Util
#endif // OPENSSL_H
#endif // PASSWORD_FILE_UTIL_OPENSSL_H

View File

@ -1,22 +1,19 @@
#include "opensslrandomdevice.h"
#include "io/cryptoexception.h"
#include "./opensslrandomdevice.h"
#include "../io/cryptoexception.h"
#include <c++utilities/conversion/binaryconversion.h>
#include <openssl/rand.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include <string>
using namespace std;
using namespace CppUtilities;
namespace Util {
/*!
* \namespace QtGui
* \brief Contains all miscellaneous utility functions.
*/
/*!
* \class OpenSslRandomDevice
* \brief Provides a random device using the OpenSSL function RAND_bytes().
@ -26,27 +23,29 @@ namespace Util {
* \brief Constructs a new random device.
*/
OpenSslRandomDevice::OpenSslRandomDevice()
{}
{
}
/*!
* \brief Generates a new random number.
*/
uint32 OpenSslRandomDevice::operator ()() const {
OpenSslRandomDevice::result_type OpenSslRandomDevice::operator()() const
{
unsigned char buf[4];
if(RAND_bytes(buf, sizeof(buf))) {
return ConversionUtilities::LE::toUInt32(reinterpret_cast<char *>(buf));
} else {
string msg;
unsigned long errorCode = ERR_get_error();
while(errorCode != 0) {
if(!msg.empty()) {
msg += "\n";
}
msg += ERR_error_string(errorCode, 0);
errorCode = ERR_get_error();
}
throw Io::CryptoException(msg);
if (RAND_bytes(buf, sizeof(buf))) {
return LE::toUInt32(reinterpret_cast<char *>(buf));
}
// handle error case
string errorMsg;
while (unsigned long errorCode = ERR_get_error()) {
if (!errorMsg.empty()) {
errorMsg += '\n';
}
errorMsg += ERR_error_string(errorCode, nullptr);
errorCode = ERR_get_error();
}
throw Io::CryptoException(std::move(errorMsg));
}
/*!
@ -56,5 +55,4 @@ bool OpenSslRandomDevice::status() const
{
return RAND_status();
}
}
} // namespace Util

View File

@ -1,19 +1,34 @@
#ifndef OPENSSLRANDOMDEVICE_H
#define OPENSSLRANDOMDEVICE_H
#ifndef PASSWORD_FILE_UTIL_OPENSSLRANDOMDEVICE_H
#define PASSWORD_FILE_UTIL_OPENSSLRANDOMDEVICE_H
#include <c++utilities/conversion/types.h>
#include <c++utilities/application/global.h>
#include "../global.h"
#include <cstdint>
#include <limits>
namespace Util {
class LIB_EXPORT OpenSslRandomDevice
{
class PASSWORD_FILE_EXPORT OpenSslRandomDevice {
public:
using result_type = std::uint32_t;
OpenSslRandomDevice();
uint32 operator()() const;
result_type operator()() const;
bool status() const;
static constexpr result_type min();
static constexpr result_type max();
};
constexpr OpenSslRandomDevice::result_type OpenSslRandomDevice::min()
{
return std::numeric_limits<result_type>::min();
}
#endif // OPENSSLRANDOMDEVICE_H
constexpr OpenSslRandomDevice::result_type OpenSslRandomDevice::max()
{
return std::numeric_limits<result_type>::max();
}
} // namespace Util
#endif // PASSWORD_FILE_UTIL_OPENSSLRANDOMDEVICE_H

View File

@ -1,37 +0,0 @@
#include "testroutines.h"
#include <martchusutilities/io/binaryreader.h>
#include <martchusutilities/io/binarywriter.h>
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
using namespace IoUtilities;
namespace Testroutines {
void lengthPrefixedString()
{
stringstream stream;
BinaryReader reader(&stream);
BinaryWriter writer(&stream);
string string1("jöalfj32öl4fj34 f234ölf3je frasdölkajwe fqwöejkfwöfklja sdefölasje fasef jasöefjas efajs eflasje faöslefj asöflej asefölajsefl öasejföaslefja söef jaseö flajseflas jeföaslefj aslefjaweöflja4 rfq34jqlök4jfq ljase öfaje4fqp 34f89uj <pfj apefjawepfoi jaefoaje föasdjfaösefj a4jfase9fau sejfpas");
string string2;
string string3("asdfalsjd23öl4j3");
writer.writeLengthPrefixedString(string1);
writer.writeLengthPrefixedString(string2);
writer.writeLengthPrefixedString(string3);
if(reader.readLengthPrefixedString() == string1
&& reader.readLengthPrefixedString() == string2
&& reader.readLengthPrefixedString() == string3) {
cout << "test sucessfull" << endl;
} else {
cout << "test failed" << endl;
}
}
}

View File

@ -1,10 +0,0 @@
#ifndef TESTROUTINES_H
#define TESTROUTINES_H
namespace Testroutines {
void lengthPrefixedString();
}
#endif // TESTROUTINES_H