Compare commits

...

91 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
28 changed files with 2188 additions and 1110 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

3
.gitignore vendored
View File

@ -42,3 +42,6 @@ Makefile*
# tests
*.backup
# clang-format
/.clang-format

View File

@ -1,4 +1,17 @@
cmake_minimum_required(VERSION 3.1.0 FATAL_ERROR)
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
@ -8,8 +21,7 @@ set(HEADER_FILES
io/parsingexception.h
io/passwordfile.h
util/openssl.h
util/opensslrandomdevice.h
)
util/opensslrandomdevice.h)
set(SRC_FILES
io/cryptoexception.cpp
io/entry.cpp
@ -17,55 +29,31 @@ set(SRC_FILES
io/parsingexception.cpp
io/passwordfile.cpp
util/openssl.cpp
util/opensslrandomdevice.cpp
)
set(TEST_HEADER_FILES
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(TEST_SRC_FILES
tests/cppunit.cpp
tests/passwordfiletests.cpp
)
set(DOC_FILES README.md)
set(DOC_FILES
README.md
)
# meta data
set(META_PROJECT_NAME passwordfile)
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 3)
set(META_VERSION_MINOR 1)
set(META_VERSION_PATCH 2)
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
find_package(c++utilities 4.0.0 REQUIRED)
use_cpp_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)
# zlib
use_external_library_from_package(
z
ZLIB ANY_VERSION
ZLIB_INCLUDE_DIRS
ZLIB_LIBRARIES
AUTO_LINKAGE
REQUIRED
)
# crypto library from OpenSSL
use_external_library_from_package(
crypto
OpenSSL ANY_VERSION
OPENSSL_INCLUDE_DIR
OPENSSL_CRYPTO_LIBRARY
AUTO_LINKAGE
REQUIRED
)
use_zlib()
use_crypto()
use_standard_filesystem()
# include modules to apply configuration
include(BasicConfig)

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

@ -4,408 +4,392 @@
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 }
};
/*!
* \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.
*/
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 }
};
// 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::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::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::Aes() :
key_length(0),
num_rounds(0),
w(0)
{
memset(state, 0, 16);
}
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()
{
}
Aes::Aes()
: keyLength(0)
, numRounds(0)
, w(0)
{
memset(state, 0, 16);
}
Aes::byte Aes::gmul(byte a, byte b)
{
unsigned char p = 0;
unsigned char hi;
Aes::~Aes()
{
}
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;
}
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 tmp[4];
memcpy(tmp, b, 4);
byte tmpb = tmp[3];
byte tmpb = tmp[3];
for(byte i = 3; i > 0; --i)
tmp[i] = tmp[i - 1];
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;
}
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

View File

@ -1,28 +1,28 @@
#ifndef AES_INCLUDED
#define AES_INCLUDED AES_INCLUDED
#include <c++utilities/application/global.h>
#include "../global.h"
#include <cstring>
namespace Crypto {
class LIB_EXPORT Aes {
class PASSWORD_FILE_EXPORT Aes {
public:
typedef unsigned char byte;
typedef unsigned long word;
using byte = unsigned char;
using word = unsigned long;
Aes();
~Aes();
size_t encrypt(char **data, size_t length, char *key);
size_t decrypt(char **data, size_t length, char *key);
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 );
static void rotWord(word *b);
static void subWord(word *b);
bool setKey(char *key);
void expandKey(byte *key);
@ -42,13 +42,13 @@ private:
static byte inv_sbox[16][16];
static word rcon[52];
byte key_length;
byte num_rounds;
byte keyLength;
byte numRounds;
word *w;
byte state[4][4];
};
}
} // namespace Crypto
#endif /* AES_INCLUDED */

View File

@ -4,14 +4,25 @@
#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
#define PASSWORD_FILE_EXPORT
#define PASSWORD_FILE_IMPORT
#else
# define PASSWORD_FILE_EXPORT LIB_EXPORT
# define PASSWORD_FILE_IMPORT LIB_IMPORT
#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

@ -4,19 +4,31 @@ 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,5 +1,5 @@
#ifndef CRYPTOFAILUREEXCEPTION_H
#define CRYPTOFAILUREEXCEPTION_H
#ifndef PASSWORD_FILE_IO_CRYPTOFAILUREEXCEPTION_H
#define PASSWORD_FILE_IO_CRYPTOFAILUREEXCEPTION_H
#include "../global.h"
@ -8,13 +8,13 @@
namespace Io {
class PASSWORD_FILE_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 <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;
}
m_extendedData = reader.readString(extendedHeaderSize);
}
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,45 +347,48 @@ 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;
}
@ -347,17 +397,17 @@ void NodeEntry::make(ostream &stream) const
BinaryWriter writer(&stream);
writer.writeByte(isExpandedByDefault() && m_extendedData.empty() ? 0x0 : 0x1); // version
writer.writeLengthPrefixedString(label());
if(!isExpandedByDefault() || !m_extendedData.empty()) {
writer.writeUInt16BE(1 + m_extendedData.size()); // extended header is 1 byte long
byte flags = 0x00;
if(isExpandedByDefault()) {
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);
}
}
@ -367,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.
@ -388,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
m_extendedData = reader.readString(extendedHeaderSize);
}
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));
}
}
/*!
@ -415,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;
}
@ -425,19 +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 | (m_extendedData.empty() ? 0x0 : 0x1)); // version
writer.writeLengthPrefixedString(label());
if(!m_extendedData.empty()) {
writer.writeUInt16BE(m_extendedData.size());
if (!m_extendedData.empty()) {
writer.writeUInt16BE(static_cast<std::uint16_t>(m_extendedData.size()));
writer.writeString(m_extendedData);
}
writer.writeUInt32BE(m_fields.size());
for(const Field &field : m_fields) {
writer.writeUInt32BE(static_cast<std::uint32_t>(m_fields.size()));
for (const Field &field : m_fields) {
field.make(stream);
}
}
@ -447,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,31 +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 <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 PASSWORD_FILE_EXPORT Entry
{
class PASSWORD_FILE_EXPORT Entry {
friend class NodeEntry;
public:
virtual ~Entry();
Entry &operator=(const Entry &other) = delete;
@ -36,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);
@ -55,7 +62,6 @@ private:
protected:
std::string m_extendedData;
};
/*!
@ -94,25 +100,37 @@ inline int Entry::index() const
return m_index;
}
class PASSWORD_FILE_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;
@ -139,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 PASSWORD_FILE_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;
};
@ -176,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

@ -5,8 +5,7 @@
#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
m_extendedData = reader.readString(extendedHeaderSize);
}
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;
}
/*!
@ -65,11 +64,10 @@ void Field::make(ostream &stream) const
writer.writeByte(m_extendedData.empty() ? 0x0 : 0x1); // version
writer.writeLengthPrefixedString(m_name);
writer.writeLengthPrefixedString(m_value);
writer.writeByte(static_cast<byte>(m_type));
if(!m_extendedData.empty()) {
writer.writeUInt16BE(m_extendedData.size());
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,5 +1,5 @@
#ifndef FIELD_H
#define FIELD_H
#ifndef PASSWORD_FILE_IO_FIELD_H
#define PASSWORD_FILE_IO_FIELD_H
#include "../global.h"
@ -8,17 +8,13 @@
namespace Io {
enum class FieldType : int
{
Normal,
Password
};
enum class FieldType : int { Normal, Password };
class AccountEntry;
class PASSWORD_FILE_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);
@ -41,9 +37,14 @@ private:
protected:
std::string m_extendedData;
};
inline Field::Field()
: m_type(FieldType::Normal)
, m_tiedAccount(nullptr)
{
}
/*!
* \brief Returns an indication whether the entry is empty.
*/
@ -115,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

@ -5,19 +5,31 @@ 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,5 +1,5 @@
#ifndef PARSINGEXCEPTION_H
#define PARSINGEXCEPTION_H
#ifndef PASSWORD_FILE_IO_PARSINGEXCEPTION_H
#define PASSWORD_FILE_IO_PARSINGEXCEPTION_H
#include "../global.h"
@ -8,13 +8,13 @@
namespace Io {
class PASSWORD_FILE_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

View File

@ -1,9 +1,14 @@
#include "./passwordfile.h"
#include "./cryptoexception.h"
#include "./parsingexception.h"
#include "./entry.h"
#include "./parsingexception.h"
#include <c++utilities/io/catchiofailure.h>
#include "../util/openssl.h"
#include "../util/opensslrandomdevice.h"
#include <c++utilities/conversion/stringbuilder.h>
#include <c++utilities/conversion/stringconversion.h>
#include <c++utilities/io/path.h>
#include <openssl/conf.h>
#include <openssl/err.h>
@ -12,18 +17,22 @@
#include <zlib.h>
#include <streambuf>
#include <sstream>
#include <cstring>
#include <memory>
#include <filesystem>
#include <functional>
#include <limits>
#include <memory>
#include <sstream>
#include <streambuf>
using namespace std;
using namespace IoUtilities;
using namespace CppUtilities;
namespace Io {
const unsigned int aes256cbcIvSize = 16U;
constexpr unsigned int aes256cbcIvSize = 16U;
constexpr unsigned int aes256blockSize = 32U;
constexpr unsigned int aes256additionalBufferSize = aes256blockSize * 2;
/*!
* \class PasswordFile
@ -34,9 +43,12 @@ const unsigned int aes256cbcIvSize = 16U;
/*!
* \brief Constructs a new password file.
*/
PasswordFile::PasswordFile() :
m_freader(BinaryReader(&m_file)),
m_fwriter(BinaryWriter(&m_file))
PasswordFile::PasswordFile()
: m_freader(BinaryReader(&m_file))
, m_fwriter(BinaryWriter(&m_file))
, m_version(0)
, m_openOptions(PasswordFileOpenFlags::None)
, m_saveOptions(PasswordFileSaveFlags::None)
{
m_file.exceptions(ios_base::failbit | ios_base::badbit);
clearPassword();
@ -45,9 +57,12 @@ PasswordFile::PasswordFile() :
/*!
* \brief Constructs a new password file with the specified \a path and \a password.
*/
PasswordFile::PasswordFile(const string &path, const string &password) :
m_freader(BinaryReader(&m_file)),
m_fwriter(BinaryWriter(&m_file))
PasswordFile::PasswordFile(const string &path, const string &password)
: m_freader(BinaryReader(&m_file))
, m_fwriter(BinaryWriter(&m_file))
, m_version(0)
, m_openOptions(PasswordFileOpenFlags::None)
, m_saveOptions(PasswordFileSaveFlags::None)
{
m_file.exceptions(ios_base::failbit | ios_base::badbit);
setPath(path);
@ -57,14 +72,37 @@ PasswordFile::PasswordFile(const string &path, const string &password) :
/*!
* \brief Constructs a copy of another password file.
*/
PasswordFile::PasswordFile(const PasswordFile &other) :
m_path(other.m_path),
m_freader(BinaryReader(&m_file)),
m_fwriter(BinaryWriter(&m_file))
PasswordFile::PasswordFile(const PasswordFile &other)
: m_path(other.m_path)
, m_password(other.m_password)
, m_rootEntry(other.m_rootEntry ? make_unique<NodeEntry>(*other.m_rootEntry) : nullptr)
, m_extendedHeader(other.m_extendedHeader)
, m_encryptedExtendedHeader(other.m_encryptedExtendedHeader)
, m_freader(BinaryReader(&m_file))
, m_fwriter(BinaryWriter(&m_file))
, m_version(other.m_version)
, m_openOptions(other.m_openOptions)
, m_saveOptions(other.m_saveOptions)
{
m_file.exceptions(ios_base::failbit | ios_base::badbit);
setPath(other.path());
memcpy(m_password, other.m_password, 32);
}
/*!
* \brief Moves the password file.
*/
PasswordFile::PasswordFile(PasswordFile &&other)
: m_path(std::move(other.m_path))
, m_password(std::move(other.m_password))
, m_rootEntry(std::move(other.m_rootEntry))
, m_extendedHeader(std::move(other.m_extendedHeader))
, m_encryptedExtendedHeader(std::move(other.m_encryptedExtendedHeader))
, m_file(std::move(other.m_file))
, m_freader(BinaryReader(&m_file))
, m_fwriter(BinaryWriter(&m_file))
, m_version(other.m_version)
, m_openOptions(other.m_openOptions)
, m_saveOptions(other.m_saveOptions)
{
}
/*!
@ -72,23 +110,34 @@ PasswordFile::PasswordFile(const PasswordFile &other) :
*/
PasswordFile::~PasswordFile()
{
close();
}
/*!
* \brief Opens the file. Does not load the contents (see load()).
* \throws Throws ios_base::failure when an IO error occurs.
*/
void PasswordFile::open(bool readOnly)
void PasswordFile::open(PasswordFileOpenFlags options)
{
close();
if(m_path.empty()) {
throwIoFailure("Unable to open file because path is emtpy.");
if (m_path.empty()) {
throw std::ios_base::failure("Unable to open file because path is empty.");
}
m_file.open(m_path, readOnly ? ios_base::in | ios_base::binary : ios_base::in | ios_base::out | ios_base::binary);
m_file.open(
m_path, options & PasswordFileOpenFlags::ReadOnly ? ios_base::in | ios_base::binary : ios_base::in | ios_base::out | ios_base::binary);
m_openOptions = options;
opened();
}
/*!
* \brief Handles the file being opened.
*
* Call this method after opening a file directly via the underlying fileStream().
*/
void PasswordFile::opened()
{
m_file.seekg(0, ios_base::end);
if(m_file.tellg() == 0) {
throwIoFailure("File is empty.");
if (m_file.tellg() == 0) {
throw std::ios_base::failure("File is empty.");
} else {
m_file.seekg(0);
}
@ -99,7 +148,7 @@ void PasswordFile::open(bool readOnly)
*/
void PasswordFile::generateRootEntry()
{
if(!m_rootEntry) {
if (!m_rootEntry) {
m_rootEntry.reset(new NodeEntry("accounts"));
}
}
@ -111,8 +160,8 @@ void PasswordFile::generateRootEntry()
void PasswordFile::create()
{
close();
if(m_path.empty()) {
throwIoFailure("Unable to create file because path is empty.");
if (m_path.empty()) {
throw std::ios_base::failure("Unable to create file because path is empty.");
}
m_file.open(m_path, fstream::out | fstream::trunc | fstream::binary);
}
@ -123,104 +172,166 @@ void PasswordFile::create()
* \throws Throws ios_base::failure when an IO error occurs.
* \throws Throws Io::ParsingException when a parsing error occurs.
* \throws Throws Io::CryptoException when a decryption error occurs.
* \throws Throws ConversionUtilities::ConversionException when a conversion error occurs.
* \throws Throws CppUtilities::ConversionException when a conversion error occurs.
*/
void PasswordFile::load()
{
if(!m_file.is_open()) {
if (!m_file.is_open()) {
open();
}
m_file.seekg(0);
m_version = 0;
m_saveOptions = PasswordFileSaveFlags::None;
// check magic number
if(m_freader.readUInt32LE() != 0x7770616DU) {
if (m_freader.readUInt32LE() != 0x7770616DU) {
throw ParsingException("Signature not present.");
}
// check version and flags (used in version 0x3 only)
uint32 version = m_freader.readUInt32LE();
if(version != 0x0U && version != 0x1U && version != 0x2U && version != 0x3U && version != 0x4U && version != 0x5U) {
throw ParsingException("Version is unknown.");
m_version = m_freader.readUInt32LE();
if (m_version > 0x6U) {
throw ParsingException(argsToString("Version \"", m_version, "\" is unknown. Only versions 0 to 6 are supported."));
}
bool decrypterUsed;
bool ivUsed;
bool compressionUsed;
if(version == 0x3U) {
byte flags = m_freader.readByte();
decrypterUsed = flags & 0x80;
if (m_version >= 0x6U) {
m_saveOptions |= PasswordFileSaveFlags::PasswordHashing;
}
bool decrypterUsed, ivUsed, compressionUsed;
if (m_version >= 0x3U) {
const auto flags = m_freader.readByte();
if ((decrypterUsed = flags & 0x80)) {
m_saveOptions |= PasswordFileSaveFlags::Encryption;
}
if ((compressionUsed = flags & 0x20)) {
m_saveOptions |= PasswordFileSaveFlags::Compression;
}
ivUsed = flags & 0x40;
compressionUsed = flags & 0x20;
} else {
decrypterUsed = version >= 0x1U;
ivUsed = version == 0x2U;
if ((decrypterUsed = m_version >= 0x1U)) {
m_saveOptions |= PasswordFileSaveFlags::Encryption;
}
compressionUsed = false;
ivUsed = m_version == 0x2U;
}
// skip extended header
// the extended header might be used in further versions to
// add additional information without breaking compatibility
if(version >= 0x4U) {
uint16 extendedHeaderSize = m_freader.readUInt16BE();
// (the extended header might be used in further versions to
// add additional information without breaking compatibility)
if (m_version >= 0x4U) {
std::uint16_t extendedHeaderSize = m_freader.readUInt16BE();
m_extendedHeader = m_freader.readString(extendedHeaderSize);
} else {
m_extendedHeader.clear();
}
// get length
fstream::pos_type headerSize = m_file.tellg();
const auto headerSize = static_cast<size_t>(m_file.tellg());
m_file.seekg(0, ios_base::end);
fstream::pos_type size = m_file.tellg();
m_file.seekg(headerSize, ios_base::beg);
size -= headerSize;
// read file
unsigned char iv[aes256cbcIvSize] = {0};
if(decrypterUsed && ivUsed) {
if(size < aes256cbcIvSize) {
throw ParsingException("Initiation vector not present.");
auto remainingSize = static_cast<size_t>(m_file.tellg()) - headerSize;
m_file.seekg(static_cast<streamoff>(headerSize), ios_base::beg);
// read hash count
uint32_t hashCount = 0U;
if ((m_saveOptions & PasswordFileSaveFlags::PasswordHashing) && decrypterUsed) {
if (remainingSize < 4) {
throw ParsingException("Hash count truncated.");
}
hashCount = m_freader.readUInt32BE();
remainingSize -= 4;
}
// read IV
unsigned char iv[aes256cbcIvSize] = { 0 };
if (decrypterUsed && ivUsed) {
if (remainingSize < aes256cbcIvSize) {
throw ParsingException("Initiation vector is truncated.");
}
m_file.read(reinterpret_cast<char *>(iv), aes256cbcIvSize);
size -= aes256cbcIvSize;
remainingSize -= aes256cbcIvSize;
}
if(size <= 0) {
if (!remainingSize) {
throw ParsingException("No contents found.");
}
// decrypt contents
vector<char> rawbuff;
m_freader.read(rawbuff, size);
vector<char> decbuff;
if(decrypterUsed) {
// initiate ctx
vector<char> rawData;
m_freader.read(rawData, static_cast<streamoff>(remainingSize));
vector<char> decryptedData;
if (decrypterUsed) {
if (remainingSize > numeric_limits<int>::max()) {
throw CryptoException("Size exceeds limit.");
}
// prepare password
Util::OpenSsl::Sha256Sum password;
if (hashCount) {
// hash the password as often as it has been hashed when writing the file
password = Util::OpenSsl::computeSha256Sum(reinterpret_cast<unsigned const char *>(m_password.data()), m_password.size());
for (uint32_t i = 1; i < hashCount; ++i) {
password = Util::OpenSsl::computeSha256Sum(password.data, Util::OpenSsl::Sha256Sum::size);
}
} else {
m_password.copy(reinterpret_cast<char *>(password.data), Util::OpenSsl::Sha256Sum::size);
}
// initiate ctx, decrypt data
EVP_CIPHER_CTX *ctx = nullptr;
decbuff.resize(size + static_cast<fstream::pos_type>(32));
decryptedData.resize(remainingSize + aes256additionalBufferSize);
int outlen1, outlen2;
if ((ctx = EVP_CIPHER_CTX_new()) == nullptr
|| EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), nullptr, reinterpret_cast<unsigned const char *>(m_password), iv) != 1
|| EVP_DecryptUpdate(ctx, reinterpret_cast<unsigned char *>(decbuff.data()), &outlen1, reinterpret_cast<unsigned char *>(rawbuff.data()), size) != 1
|| EVP_DecryptFinal_ex(ctx, reinterpret_cast<unsigned char *>(decbuff.data()) + outlen1, &outlen2) != 1) {
if(ctx) {
if ((ctx = EVP_CIPHER_CTX_new()) == nullptr || EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), nullptr, password.data, iv) != 1
|| EVP_DecryptUpdate(ctx, reinterpret_cast<unsigned char *>(decryptedData.data()), &outlen1,
reinterpret_cast<unsigned char *>(rawData.data()), static_cast<int>(remainingSize))
!= 1
|| EVP_DecryptFinal_ex(ctx, reinterpret_cast<unsigned char *>(decryptedData.data()) + outlen1, &outlen2) != 1) {
// handle decryption error
if (ctx) {
EVP_CIPHER_CTX_free(ctx);
}
string msg;
unsigned long errorCode = ERR_get_error();
while(errorCode != 0) {
if(!msg.empty()) {
auto errorCode = ERR_get_error();
while (errorCode) {
if (!msg.empty()) {
msg += "\n";
}
msg += ERR_error_string(errorCode, 0);
msg += ERR_error_string(errorCode, nullptr);
errorCode = ERR_get_error();
}
throw CryptoException(msg);
} else { // decryption suceeded
if(ctx) {
EVP_CIPHER_CTX_free(ctx);
}
size = outlen1 + outlen2;
throw CryptoException(std::move(msg));
}
} else { // file is not crypted
decbuff.swap(rawbuff);
if (ctx) {
EVP_CIPHER_CTX_free(ctx);
}
const auto decryptedSize = outlen1 + outlen2;
if (decryptedSize < 0) {
throw CryptoException("Decrypted size is negative.");
}
remainingSize = static_cast<size_t>(decryptedSize);
if (!remainingSize) {
throw ParsingException("Decrypted buffer is empty.");
}
} else {
// use raw data directly if not encrypted
decryptedData.swap(rawData);
}
// decompress
if(compressionUsed) {
if(size < 8) {
if (compressionUsed) {
if (remainingSize < 8) {
throw ParsingException("File is truncated (decompressed size expected).");
}
uLongf decompressedSize = ConversionUtilities::LE::toUInt64(decbuff.data());
rawbuff.resize(decompressedSize);
switch(uncompress(reinterpret_cast<Bytef *>(rawbuff.data()), &decompressedSize, reinterpret_cast<Bytef *>(decbuff.data() + 8), size - static_cast<fstream::pos_type>(8))) {
if (remainingSize > numeric_limits<uLongf>::max()) {
throw CryptoException("Size exceeds limit.");
}
const auto rawDecompressedSize = LE::toUInt64(decryptedData.data());
if (rawDecompressedSize > numeric_limits<uLongf>::max()) {
throw ParsingException("Decompressed size exceeds limit.");
}
auto decompressedSize = static_cast<uLongf>(rawDecompressedSize);
rawData.resize(decompressedSize);
switch (uncompress(reinterpret_cast<Bytef *>(rawData.data()), &decompressedSize, reinterpret_cast<Bytef *>(decryptedData.data() + 8),
static_cast<uLongf>(remainingSize - 8))) {
case Z_MEM_ERROR:
throw ParsingException("Decompressing failed. The source buffer was too small.");
case Z_BUF_ERROR:
@ -228,126 +339,243 @@ void PasswordFile::load()
case Z_DATA_ERROR:
throw ParsingException("Decompressing failed. The input data was corrupted or incomplete.");
case Z_OK:
decbuff.swap(rawbuff); // decompression successful
size = decompressedSize;
decryptedData.swap(rawData);
remainingSize = decompressedSize;
}
}
// parse contents
stringstream buffstr(stringstream::in | stringstream::out | stringstream::binary);
buffstr.write(decbuff.data(), static_cast<streamsize>(size));
decbuff.resize(0);
buffstr.seekg(0, ios_base::beg);
if(version >= 0x5u) {
uint16 extendedHeaderSize = m_freader.readUInt16BE();
m_encryptedExtendedHeader = m_freader.readString(extendedHeaderSize);
if (!remainingSize) {
throw ParsingException("Decompressed buffer is empty.");
}
// parse contents
stringstream decryptedStream(stringstream::in | stringstream::out | stringstream::binary);
decryptedStream.exceptions(ios_base::failbit | ios_base::badbit);
try {
#if defined(__GLIBCXX__) && !defined(_LIBCPP_VERSION)
decryptedStream.rdbuf()->pubsetbuf(decryptedData.data(), static_cast<streamsize>(remainingSize));
#else
decryptedStream.write(decryptedData.data(), static_cast<streamsize>(remainingSize));
#endif
if (m_version >= 0x5u) {
BinaryReader reader(&decryptedStream);
const auto extendedHeaderSize = reader.readUInt16BE();
m_encryptedExtendedHeader = reader.readString(extendedHeaderSize);
} else {
m_encryptedExtendedHeader.clear();
}
m_rootEntry.reset(new NodeEntry(decryptedStream));
} catch (const std::ios_base::failure &failure) {
if (decryptedStream.eof()) {
throw ParsingException("The file seems to be truncated.");
}
throw ParsingException(argsToString("An IO error occurred when reading internal buffer: ", failure.what()));
}
m_rootEntry.reset(new NodeEntry(buffstr));
}
/*!
* \brief Writes the current root entry to the file.
* \param useEncryption Specifies whether encryption should be used.
* \param useCompression Specifies whether compression should be used.
* \throws Throws ios_base::failure when an IO error occurs.
* \throws Throws runtime_error when no root entry is present.
* \throws Throws Io::CryptoException when a decryption error occurs.
* \brief Returns the minimum file version required to write the current instance with the specified \a options.
* \remarks This version will be used by save() and write() when passing the same \a options.
*/
void PasswordFile::save(bool useEncryption, bool useCompression)
std::uint32_t PasswordFile::mininumVersion(PasswordFileSaveFlags options) const
{
if(!m_rootEntry) {
if (options & PasswordFileSaveFlags::PasswordHashing) {
return 0x6U; // password hashing requires at least version 6
} else if (!m_encryptedExtendedHeader.empty()) {
return 0x5U; // encrypted extended header requires at least version 5
} else if (!m_extendedHeader.empty()) {
return 0x4U; // regular extended header requires at least version 4
}
return 0x3U; // lowest supported version by the serializer
}
/*!
* \brief Writes the current root entry to the file under path() replacing its previous contents.
* \param options Specify the features (like encryption and compression) to be used.
* \throws Throws std::ios_base::failure when an IO error occurs.
* \throws Throws std::filesystem::filesystem_error when a filesystem error occurs.
* \throws Throws Io::CryptoException when an encryption error occurs.
* \throws Throws std::runtime_error when no root entry is present or a compression error occurs.
*/
void PasswordFile::save(PasswordFileSaveFlags options)
{
if (!m_rootEntry) {
throw runtime_error("Root entry has not been created.");
}
// open file
if(m_file.is_open()) {
m_file.close();
// use already opened and writable file; otherwise re-open the file
auto fileSize = std::size_t();
if (m_file.good() && m_file.is_open() && !(m_openOptions & PasswordFileOpenFlags::ReadOnly)) {
fileSize = size();
m_file.seekp(0);
} else {
m_file.clear();
if (m_file.is_open()) {
m_file.close();
}
try {
m_file.open(m_path, ios_base::in | ios_base::out | ios_base::trunc | ios_base::binary);
} catch (const ios_base::failure &) {
// try to create a new file if configured via \a options
if (!(options & PasswordFileSaveFlags::AllowToCreateNewFile)) {
throw;
}
m_file.open(m_path, ios_base::out | ios_base::trunc | ios_base::binary);
}
}
m_file.open(m_path, ios_base::in | ios_base::out | ios_base::trunc | ios_base::binary);
// write header
m_fwriter.writeUInt32LE(0x7770616DU); // write magic number
// write version, extended header requires version 4, encrypted extended header required version 5
m_fwriter.writeUInt32LE(m_extendedHeader.empty() && m_encryptedExtendedHeader.empty() ? 0x3U : (m_encryptedExtendedHeader.empty() ? 0x4U : 0x5U));
byte flags = 0x00;
if(useEncryption) {
// write entries
write(options);
m_file.flush();
// truncate file if it became smaller
const auto newSize = static_cast<std::size_t>(m_file.tellp());
if (fileSize && newSize < fileSize) {
m_file.close();
std::filesystem::resize_file(makeNativePath(m_path), newSize);
}
}
/*!
* \brief Writes the current root entry to the file which is assumed to be opened and writeable.
* \param options Specify the features (like encryption and compression) to be used.
* \throws Throws std::ios_base::failure when an IO error occurs.
* \throws Throws Io::CryptoException when an encryption error occurs.
* \throws Throws std::runtime_error when no root entry is present, a compression error occurs.
*/
void PasswordFile::write(PasswordFileSaveFlags options)
{
if (!m_rootEntry) {
throw runtime_error("Root entry has not been created.");
}
// write magic number
m_fwriter.writeUInt32LE(0x7770616DU);
// write version
const auto version = mininumVersion(options);
m_fwriter.writeUInt32LE(version);
// write flags
std::uint8_t flags = 0x00;
if (options & PasswordFileSaveFlags::Encryption) {
flags |= 0x80 | 0x40;
}
if(useCompression) {
if (options & PasswordFileSaveFlags::Compression) {
flags |= 0x20;
}
m_fwriter.writeByte(flags);
// write extened header
if(!m_extendedHeader.empty()) {
m_fwriter.writeUInt16BE(m_extendedHeader.size());
// write extended header
if (version >= 0x4U) {
if (m_extendedHeader.size() > numeric_limits<std::uint16_t>::max()) {
throw runtime_error("Extended header exceeds maximum size.");
}
m_fwriter.writeUInt16BE(static_cast<std::uint16_t>(m_extendedHeader.size()));
m_fwriter.writeString(m_extendedHeader);
}
// serialize root entry and descendants
stringstream buffstr(stringstream::in | stringstream::out | stringstream::binary);
buffstr.exceptions(ios_base::failbit | ios_base::badbit);
// write encrypted extened header
if(!m_encryptedExtendedHeader.empty()) {
m_fwriter.writeUInt16BE(m_encryptedExtendedHeader.size());
m_fwriter.writeString(m_encryptedExtendedHeader);
// write encrypted extended header
if (version >= 0x5U) {
if (m_encryptedExtendedHeader.size() > numeric_limits<std::uint16_t>::max()) {
throw runtime_error("Encrypted extended header exceeds maximum size.");
}
BinaryWriter buffstrWriter(&buffstr);
buffstrWriter.writeUInt16BE(static_cast<std::uint16_t>(m_encryptedExtendedHeader.size()));
buffstrWriter.writeString(m_encryptedExtendedHeader);
}
m_rootEntry->make(buffstr);
buffstr.seekp(0, ios_base::end);
stringstream::pos_type size = buffstr.tellp();
auto size = static_cast<size_t>(buffstr.tellp());
// write the data to a buffer
buffstr.seekg(0);
vector<char> decbuff(size, 0);
buffstr.read(decbuff.data(), size);
vector<char> encbuff;
vector<char> decryptedData(size, 0);
buffstr.read(decryptedData.data(), static_cast<streamoff>(size));
vector<char> encryptedData;
// compress data
if(useCompression) {
if (options & PasswordFileSaveFlags::Compression) {
uLongf compressedSize = compressBound(size);
encbuff.resize(8 + compressedSize);
ConversionUtilities::LE::getBytes(static_cast<uint64>(size), encbuff.data());
switch(compress(reinterpret_cast<Bytef *>(encbuff.data() + 8), &compressedSize, reinterpret_cast<Bytef *>(decbuff.data()), size)) {
encryptedData.resize(8 + compressedSize);
LE::getBytes(static_cast<std::uint64_t>(size), encryptedData.data());
switch (
compress(reinterpret_cast<Bytef *>(encryptedData.data() + 8), &compressedSize, reinterpret_cast<Bytef *>(decryptedData.data()), size)) {
case Z_MEM_ERROR:
throw runtime_error("Decompressing failed. The source buffer was too small.");
throw runtime_error("Compressing failed. The source buffer was too small.");
case Z_BUF_ERROR:
throw runtime_error("Decompressing failed. The destination buffer was too small.");
throw runtime_error("Compressing failed. The destination buffer was too small.");
case Z_OK:
encbuff.swap(decbuff); // decompression successful
encryptedData.swap(decryptedData); // compression successful
size = 8 + compressedSize;
}
}
// encrypt data
if(useEncryption) {
// initiate ctx
EVP_CIPHER_CTX *ctx = nullptr;
unsigned char iv[aes256cbcIvSize];
int outlen1, outlen2;
encbuff.resize(size + static_cast<fstream::pos_type>(32));
if (RAND_bytes(iv, aes256cbcIvSize) != 1
|| (ctx = EVP_CIPHER_CTX_new()) == nullptr
|| EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), nullptr, reinterpret_cast<unsigned const char *>(m_password), iv) != 1
|| EVP_EncryptUpdate(ctx, reinterpret_cast<unsigned char *>(encbuff.data()), &outlen1, reinterpret_cast<unsigned char *>(decbuff.data()), size) != 1
|| EVP_EncryptFinal_ex(ctx, reinterpret_cast<unsigned char *>(encbuff.data()) + outlen1, &outlen2) != 1) {
if(ctx) {
EVP_CIPHER_CTX_free(ctx);
}
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 CryptoException(msg);
} else { // decryption succeeded
if(ctx) {
EVP_CIPHER_CTX_free(ctx);
}
// write encrypted data to file
m_file.write(reinterpret_cast<char *>(iv), aes256cbcIvSize);
m_file.write(encbuff.data(), static_cast<streamsize>(outlen1 + outlen2));
if (size > numeric_limits<int>::max()) {
throw CryptoException("size exceeds limit");
}
// write data without encryption
if (!(options & PasswordFileSaveFlags::Encryption)) {
// write data to file
m_file.write(decryptedData.data(), static_cast<streamsize>(size));
m_file.flush();
return;
}
// prepare password
Util::OpenSsl::Sha256Sum password;
const uint32_t hashCount = (options & PasswordFileSaveFlags::PasswordHashing) ? Util::OpenSsl::generateRandomNumber(1, 100) : 0u;
if (hashCount) {
// hash password a few times
password = Util::OpenSsl::computeSha256Sum(reinterpret_cast<unsigned const char *>(m_password.data()), m_password.size());
for (uint32_t i = 1; i < hashCount; ++i) {
password = Util::OpenSsl::computeSha256Sum(password.data, Util::OpenSsl::Sha256Sum::size);
}
} else {
// write data to file
m_file.write(decbuff.data(), static_cast<streamsize>(size));
m_password.copy(reinterpret_cast<char *>(password.data), Util::OpenSsl::Sha256Sum::size);
}
// initiate ctx, encrypt data
EVP_CIPHER_CTX *ctx = nullptr;
unsigned char iv[aes256cbcIvSize];
int outlen1, outlen2;
encryptedData.resize(size + aes256additionalBufferSize);
if (RAND_bytes(iv, aes256cbcIvSize) != 1 || (ctx = EVP_CIPHER_CTX_new()) == nullptr
|| EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), nullptr, password.data, iv) != 1
|| EVP_EncryptUpdate(ctx, reinterpret_cast<unsigned char *>(encryptedData.data()), &outlen1,
reinterpret_cast<unsigned char *>(decryptedData.data()), static_cast<int>(size))
!= 1
|| EVP_EncryptFinal_ex(ctx, reinterpret_cast<unsigned char *>(encryptedData.data()) + outlen1, &outlen2) != 1) {
// handle encryption error
if (ctx) {
EVP_CIPHER_CTX_free(ctx);
}
string msg;
auto errorCode = ERR_get_error();
while (errorCode) {
if (!msg.empty()) {
msg += "\n";
}
msg += ERR_error_string(errorCode, nullptr);
errorCode = ERR_get_error();
}
throw CryptoException(std::move(msg));
}
if (ctx) {
EVP_CIPHER_CTX_free(ctx);
}
// write encrypted data to file
if (version >= 0x6U) {
m_fwriter.writeUInt32BE(hashCount);
}
m_file.write(reinterpret_cast<char *>(iv), aes256cbcIvSize);
m_file.write(encryptedData.data(), static_cast<streamsize>(outlen1 + outlen2));
m_file.flush();
}
@ -368,6 +596,7 @@ void PasswordFile::clear()
clearPath();
clearPassword();
clearEntries();
m_openOptions = PasswordFileOpenFlags::None;
m_extendedHeader.clear();
m_encryptedExtendedHeader.clear();
}
@ -375,35 +604,36 @@ void PasswordFile::clear()
/*!
* \brief Writes the current root entry to a plain text file. No encryption is used.
* \param targetPath Specifies the path of the text file.
* \throws Throws ios_base::failure when an IO error occurs.
* \throws Throws runtime_error when no root entry is present.
* \throws Throws std::ios_base::failure when an IO error occurs and std::runtime_error when no root entry is present.
*/
void PasswordFile::exportToTextfile(const string &targetPath) const
{
if(!m_rootEntry) {
if (!m_rootEntry) {
throw runtime_error("Root entry has not been created.");
}
fstream output(targetPath.c_str(), ios_base::out);
function<void (int level)> indention = [&output] (int level) {
for(int i = 0; i < level; ++i) {
NativeFileStream output;
output.exceptions(std::ios_base::failbit | std::ios_base::badbit);
output.open(targetPath, std::ios_base::out);
const auto printIndention = [&output](int level) {
for (int i = 0; i < level; ++i) {
output << " ";
}
};
function<void (const Entry *entry, int level)> printNode;
printNode = [&output, &printNode, &indention] (const Entry *entry, int level) {
indention(level);
function<void(const Entry *entry, int level)> printNode;
printNode = [&output, &printNode, &printIndention](const Entry *entry, int level) {
printIndention(level);
output << " - " << entry->label() << endl;
switch(entry->type()) {
switch (entry->type()) {
case EntryType::Node:
for(const Entry *child : static_cast<const NodeEntry *>(entry)->children()) {
for (const Entry *child : static_cast<const NodeEntry *>(entry)->children()) {
printNode(child, level + 1);
}
break;
case EntryType::Account:
for(const Field &field : static_cast<const AccountEntry *>(entry)->fields()) {
indention(level);
for (const Field &field : static_cast<const AccountEntry *>(entry)->fields()) {
printIndention(level);
output << " " << field.name();
for(int i = field.name().length(); i < 15; ++i) {
for (auto i = field.name().length(); i < 15; ++i) {
output << ' ';
}
output << field.value() << endl;
@ -420,19 +650,20 @@ void PasswordFile::exportToTextfile(const string &targetPath) const
*/
void PasswordFile::doBackup()
{
if(!isOpen()) {
if (!isOpen()) {
open();
}
m_file.seekg(0, ios_base::end);
if(m_file.tellg()) {
m_file.seekg(0);
fstream backupFile(m_path + ".backup", ios::out | ios::trunc | ios::binary);
backupFile.exceptions(ios_base::failbit | ios_base::badbit);
backupFile << m_file.rdbuf();
backupFile.close();
} else {
// the current file is empty anyways
// skip if the current file is empty anyways
if (!size()) {
return;
}
m_file.seekg(0);
fstream backupFile(m_path + ".backup", ios::out | ios::trunc | ios::binary);
backupFile.exceptions(ios_base::failbit | ios_base::badbit);
backupFile << m_file.rdbuf();
backupFile.close();
}
/*!
@ -466,81 +697,48 @@ NodeEntry *PasswordFile::rootEntry()
*/
void PasswordFile::close()
{
if(m_file.is_open()) {
if (m_file.is_open()) {
m_file.close();
}
m_file.clear();
}
/*!
* \brief Returns the current file path.
*/
const string &PasswordFile::path() const
{
return m_path;
}
/*!
* \brief Sets the current file path. Causes the file to be closed if currently opened.
* \brief Sets the current file path. Closes the file if currently opened.
*/
void PasswordFile::setPath(const string &value)
{
close();
m_path = value;
// support "file://" protocol
if (startsWith(m_path, "file:")) {
m_path = m_path.substr(5);
}
}
/*!
* \brief Clears the current path. Causes the file to be closed if currently opened.
*/
void PasswordFile::clearPath()
{
close();
m_path.clear();
}
/*!
* \brief Returns the current password. It will be used when loading or saving using encryption.
*/
const char *PasswordFile::password() const
{
return m_password;
}
/*!
* \brief Sets the current password. It will be used when loading or saving using encryption.
*/
void PasswordFile::setPassword(const string &value)
{
clearPassword();
value.copy(m_password, 32, 0);
}
/*!
* \brief Clears the current password.
*/
void PasswordFile::clearPassword()
{
memset(m_password, 0, 32);
}
/*!
* \brief Returns an indication whether encryption is used if the file is open; returns always false otherwise.
* \brief Returns an indication whether encryption is used and the file is open; returns always false otherwise.
* \remarks This method is meant to determine whether encryption is used *before* loading the file. If the file has
* already been loaded, use preferably saveOptions().
*/
bool PasswordFile::isEncryptionUsed()
{
if(!isOpen()) {
if (!isOpen()) {
return false;
}
m_file.seekg(0);
//check magic number
if(m_freader.readUInt32LE() != 0x7770616DU) {
// check magic number
if (m_freader.readUInt32LE() != 0x7770616DU) {
return false;
}
//check version
uint32 version = m_freader.readUInt32LE();
if(version == 0x1U || version == 0x2U) {
// check version
const auto version = m_freader.readUInt32LE();
if (version == 0x1U || version == 0x2U) {
return true;
} else if(version == 0x3U) {
} else if (version >= 0x3U) {
return m_freader.readByte() & 0x80;
} else {
return false;
@ -548,23 +746,76 @@ bool PasswordFile::isEncryptionUsed()
}
/*!
* \brief Returns an indication whether the file is open.
*/
bool PasswordFile::isOpen() const
{
return m_file.is_open();
}
/*!
* \brief Returns the size of the file if the file is open; returns always zero otherwise.
* \brief Returns the size of the file if the file is open; otherwise returns zero.
*/
size_t PasswordFile::size()
{
if(!isOpen()) {
if (!isOpen()) {
return 0;
}
m_file.seekg(0, ios::end);
return m_file.tellg();
return static_cast<size_t>(m_file.tellg());
}
/*!
* \brief Returns a summary about the file (version, used features, statistics).
*/
string PasswordFile::summary(PasswordFileSaveFlags saveOptions) const
{
string result = "<table>";
if (!m_path.empty()) {
result += argsToString("<tr><td>Path:</td><td>", m_path, "</td></tr>");
}
result += argsToString("<tr><td>Version:</td><td>", m_version, "</td></tr>");
const auto minVersion = mininumVersion(saveOptions);
if (m_version != minVersion) {
result += argsToString("<tr><td></td><td>(on disk, after saving: ", minVersion, ")</td></tr>");
}
result += argsToString("<tr><td>Features:</td><td>", flagsToString(m_saveOptions), "</td></tr>");
if (m_saveOptions != saveOptions) {
result += argsToString("<tr><td></td><td>(on disk, after saving: ", flagsToString(saveOptions), ")</td></tr>");
}
const auto stats = m_rootEntry ? m_rootEntry->computeStatistics() : EntryStatistics();
result += argsToString("<tr><td>Number of categories:</td><td>", stats.nodeCount, "</td></tr><tr><td>Number of accounts:</td><td>",
stats.accountCount, "</td></tr><tr><td>Number of fields:</td><td>", stats.fieldCount, "</td></tr></table>");
return result;
}
/*!
* \brief Returns a comma-separated string for the specified \a flags.
*/
string flagsToString(PasswordFileOpenFlags flags)
{
vector<string> options;
if (flags & PasswordFileOpenFlags::ReadOnly) {
options.emplace_back("read-only");
}
if (options.empty()) {
options.emplace_back("none");
}
return joinStrings(options, ", ");
}
/*!
* \brief Returns a comma-separated string for the specified \a flags.
*/
string flagsToString(PasswordFileSaveFlags flags)
{
vector<string> options;
options.reserve(3);
if (flags & PasswordFileSaveFlags::Encryption) {
options.emplace_back("encryption");
}
if (flags & PasswordFileSaveFlags::Compression) {
options.emplace_back("compression");
}
if (flags & PasswordFileSaveFlags::PasswordHashing) {
options.emplace_back("password hashing");
}
if (options.empty()) {
options.emplace_back("none");
}
return joinStrings(options, ", ");
}
} // namespace Io

View File

@ -1,33 +1,59 @@
#ifndef PASSWORDFILE_H
#define 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 <string>
#include <iostream>
#include <cstdint>
#include <fstream>
#include <iostream>
#include <memory>
#include <string>
namespace Io {
class NodeEntry;
class PASSWORD_FILE_EXPORT PasswordFile
{
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();
void open(bool readOnly = false);
CppUtilities::NativeFileStream &fileStream();
void open(PasswordFileOpenFlags options = PasswordFileOpenFlags::Default);
void opened();
void generateRootEntry();
void create();
void close();
void load();
void save(bool useEncryption = true, bool useCompression = true);
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;
@ -36,25 +62,163 @@ public:
const NodeEntry *rootEntry() const;
NodeEntry *rootEntry();
const std::string &path() const;
const char *password() const;
const std::string &password() const;
void setPath(const std::string &value);
void clearPath();
void setPassword(const std::string &value);
void setPassword(const std::string &password);
void setPassword(const char *password, const std::size_t passwordSize);
void clearPassword();
bool isEncryptionUsed();
bool isOpen() const;
size_t size();
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;
char m_password[32];
std::string m_password;
std::unique_ptr<NodeEntry> m_rootEntry;
std::string m_extendedHeader;
std::string m_encryptedExtendedHeader;
std::fstream m_file;
IoUtilities::BinaryReader m_freader;
IoUtilities::BinaryWriter m_fwriter;
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;
}
#endif // PASSWORDFILE_H
/*!
* \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

View File

@ -1 +0,0 @@
#include <c++utilities/tests/cppunit.h>

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));
}

View File

@ -1,157 +1,237 @@
#include "../io/passwordfile.h"
#include "../io/cryptoexception.h"
#include "../io/entry.h"
#include "../io/passwordfile.h"
#include <c++utilities/tests/testutils.h>
#include "./utils.h"
#include <cppunit/extensions/HelperMacros.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
{
class PasswordFileTests : public TestFixture {
CPPUNIT_TEST_SUITE(PasswordFileTests);
CPPUNIT_TEST(testReading);
#ifdef PLATFORM_UNIX
CPPUNIT_TEST(testWriting);
#endif
CPPUNIT_TEST(testBasicWriting);
CPPUNIT_TEST(testExtendedWriting);
CPPUNIT_TEST_SUITE_END();
public:
void setUp();
void tearDown();
void setUp() override;
void tearDown() override;
void testReading();
void testReading(const string &testfile1path, const string &testfile1password, const string &testfile2, const string &testfile2password, bool testfile2Mod);
#ifdef PLATFORM_UNIX
void testWriting();
#endif
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(TestUtilities::testFilePath("testfile1.pwmgr"), "123456",
TestUtilities::testFilePath("testfile2.pwmgr"), string(), false);
testReading("read", testFilePath("testfile1.pwmgr"), "123456", testFilePath("testfile2.pwmgr"), string(), false, false);
}
void PasswordFileTests::testReading(const string &testfile1path, const string &testfile1password, const string &testfile2, const string &testfile2password, bool testfile2Mod)
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(true);
file.open(PasswordFileOpenFlags::ReadOnly);
CPPUNIT_ASSERT(file.isEncryptionUsed() == !testfile1password.empty());
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, !testfile1password.empty(), file.isEncryptionUsed());
// attempt to decrypt using a wrong password
file.setPassword(testfile1password + "asdf");
if(!testfile1password.empty()) {
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 *rootEntry = file.rootEntry();
CPPUNIT_ASSERT(rootEntry->label() == "testfile1");
CPPUNIT_ASSERT(rootEntry->children().size() == 4);
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(rootEntry->children()[0]->label() == "testaccount1");
CPPUNIT_ASSERT(rootEntry->children()[0]->type() == EntryType::Account);
CPPUNIT_ASSERT(static_cast<AccountEntry *>(rootEntry->children()[0])->fields().at(0).name() == "pin");
CPPUNIT_ASSERT(static_cast<AccountEntry *>(rootEntry->children()[0])->fields().at(0).value() == "123456");
CPPUNIT_ASSERT(static_cast<AccountEntry *>(rootEntry->children()[0])->fields().at(0).type() == FieldType::Password);
CPPUNIT_ASSERT(static_cast<AccountEntry *>(rootEntry->children()[0])->fields().at(0).tiedAccount() == static_cast<AccountEntry *>(rootEntry->children()[0]));
CPPUNIT_ASSERT(static_cast<AccountEntry *>(rootEntry->children()[0])->fields().at(1).type() == FieldType::Normal);
CPPUNIT_ASSERT_THROW(static_cast<AccountEntry *>(rootEntry->children()[0])->fields().at(2), out_of_range);
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(rootEntry->children()[1]->label() == "testaccount2");
CPPUNIT_ASSERT(rootEntry->children()[1]->type() == EntryType::Account);
CPPUNIT_ASSERT(static_cast<AccountEntry *>(rootEntry->children()[1])->fields().empty());
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(rootEntry->children()[2]->label() == "testcategory1");
CPPUNIT_ASSERT(rootEntry->children()[2]->type() == EntryType::Node);
const NodeEntry *category = static_cast<NodeEntry *>(rootEntry->children()[2]);
CPPUNIT_ASSERT(category->children().size() == 3);
CPPUNIT_ASSERT(category->children()[2]->type() == EntryType::Node);
CPPUNIT_ASSERT(static_cast<NodeEntry *>(category->children()[2])->children().size() == 2);
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(rootEntry->children()[3]->label() == "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(true);
file.open(PasswordFileOpenFlags::ReadOnly);
CPPUNIT_ASSERT(file.isEncryptionUsed() == !testfile2password.empty());
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, !testfile2password.empty(), file.isEncryptionUsed());
file.setPassword(testfile2password);
file.load();
rootEntry = file.rootEntry();
if(testfile2Mod) {
CPPUNIT_ASSERT(rootEntry->label() == "testfile2 - modified");
CPPUNIT_ASSERT(rootEntry->children().size() == 2);
CPPUNIT_ASSERT(rootEntry->children()[1]->label() == "newAccount");
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(rootEntry->label() == "testfile2");
CPPUNIT_ASSERT(rootEntry->children().size() == 1);
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());
}
}
#ifdef PLATFORM_UNIX
/*!
* \brief Tests writing and reading.
* \brief Tests writing (and reading again) using basic features.
*/
void PasswordFileTests::testWriting()
void PasswordFileTests::testBasicWriting()
{
string testfile1 = TestUtilities::workingCopyPath("testfile1.pwmgr");
string testfile2 = TestUtilities::workingCopyPath("testfile2.pwmgr");
const string testfile1 = workingCopyPath("testfile1.pwmgr");
const string testfile2 = workingCopyPath("testfile2.pwmgr");
PasswordFile file;
// resave testfile 1
file.setPath(testfile1);
file.open(false);
file.open();
file.setPassword("123456");
file.load();
file.doBackup();
file.save(false, true);
file.save(PasswordFileSaveFlags::Compression);
// resave testfile 2
file.setPath(testfile2);
file.open(false);
file.open();
file.load();
file.rootEntry()->setLabel("testfile2 - modified");
new AccountEntry("newAccount", file.rootEntry());
file.setPassword("654321");
file.doBackup();
file.save(true, false);
file.save(PasswordFileSaveFlags::Encryption);
// check results using the reading test
testReading(testfile1, string(),
testfile2, "654321", true);
testReading("basic writing", testfile1, string(), testfile2, "654321", true, false);
// check backup files
testReading(testfile1 + ".backup", "123456",
testfile2 + ".backup", string(), false);
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));
}
#endif

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,8 +1,14 @@
#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.
@ -14,6 +20,8 @@ namespace Util {
*/
namespace OpenSsl {
static_assert(Sha256Sum::size == SHA256_DIGEST_LENGTH, "SHA-256 sum fits into Sha256Sum struct");
/*!
* \brief Initializes OpenSSL.
*/
@ -23,8 +31,6 @@ void init()
ERR_load_crypto_strings();
// load all digest and cipher algorithms
OpenSSL_add_all_algorithms();
// load config file, and other important initialisation
OPENSSL_config(NULL);
}
/*!
@ -38,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 "../global.h"
#include <cstddef>
#include <cstdint>
namespace Util {
namespace OpenSsl {
void PASSWORD_FILE_EXPORT init();
void PASSWORD_FILE_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

@ -4,20 +4,16 @@
#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().
@ -27,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));
}
/*!
@ -57,5 +55,4 @@ bool OpenSslRandomDevice::status() const
{
return RAND_status();
}
}
} // namespace Util

View File

@ -1,20 +1,34 @@
#ifndef OPENSSLRANDOMDEVICE_H
#define OPENSSLRANDOMDEVICE_H
#ifndef PASSWORD_FILE_UTIL_OPENSSLRANDOMDEVICE_H
#define PASSWORD_FILE_UTIL_OPENSSLRANDOMDEVICE_H
#include "../global.h"
#include <c++utilities/conversion/types.h>
#include <cstdint>
#include <limits>
namespace Util {
class PASSWORD_FILE_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