Compare commits

...

61 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
26 changed files with 1294 additions and 748 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

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,61 +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/utils.h
tests/passwordfiletests.cpp
tests/entrytests.cpp
tests/fieldtests.cpp
tests/opensslrandomdevice.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 2)
set(META_VERSION_PATCH 0)
set(META_PUBLIC_SHARED_LIB_DEPENDS c++utilities)
set(META_PUBLIC_STATIC_LIB_DEPENDS c++utilities_static)
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.8.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,8 +1,14 @@
# passwordfile
C++ library to read/write key-value pairs from/to AES-256 encrypted files.
It allows to organize the key-value pairs in tables within an hierarchical
structure. The data can be compressed with gzip before applying the encryption.
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,15 @@
#ifndef PASSWORD_FILE_GLOBAL
#define PASSWORD_FILE_GLOBAL
#include "passwordfile-definitions.h"
#include <c++utilities/application/global.h>
#ifdef PASSWORD_FILE_STATIC
#define PASSWORD_FILE_EXPORT
#define PASSWORD_FILE_IMPORT
#else
#define PASSWORD_FILE_EXPORT 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
/*!

View File

@ -4,20 +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) noexcept
: runtime_error(openSslErrorQueue)
CryptoException::CryptoException(const std::string &message) noexcept
: runtime_error(message)
{
}
/*!
* \brief Destroys the exception.
* \brief Constructs a crypto exception.
*/
CryptoException::~CryptoException() noexcept
CryptoException::CryptoException(const char *message) noexcept
: runtime_error(message)
{
}
/*!
* \brief Destroys the crypto exception.
*/
CryptoException::~CryptoException()
{
}
} // namespace Io

View File

@ -10,9 +10,11 @@ namespace Io {
class PASSWORD_FILE_EXPORT CryptoException : public std::runtime_error {
public:
CryptoException(const std::string &openSslErrorQueue) noexcept;
~CryptoException() noexcept;
explicit CryptoException(const std::string &message) noexcept;
explicit CryptoException(const char *message) noexcept;
~CryptoException() override;
};
} // namespace Io
#endif // PASSWORD_FILE_IO_CRYPTOFAILUREEXCEPTION_H

View File

@ -9,8 +9,7 @@
#include <sstream>
using namespace std;
using namespace IoUtilities;
using namespace ConversionUtilities;
using namespace CppUtilities;
namespace Io {
@ -21,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.
@ -115,7 +114,7 @@ void Entry::setParent(NodeEntry *parent, int index)
// attach the new parent
if (parent) {
if (index < 0 || static_cast<size_t>(index) >= parent->m_children.size()) {
m_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) {
@ -136,9 +135,8 @@ void Entry::setParent(NodeEntry *parent, int index)
/*!
* \brief Returns an indication whether the instance is an indirect child of the specified \a entry.
* \todo Make \a entry const in v4.
*/
bool Entry::isIndirectChildOf(NodeEntry *entry) const
bool Entry::isIndirectChildOf(const NodeEntry *entry) const
{
if (!parent()) {
return false;
@ -177,7 +175,7 @@ void Entry::path(std::list<string> &res) const
*/
Entry *Entry::parse(istream &stream)
{
const auto version = static_cast<byte>(stream.peek());
const auto version = static_cast<std::uint8_t>(stream.peek());
if (denotesNodeEntry(version)) {
return new NodeEntry(stream);
} else {
@ -232,7 +230,7 @@ NodeEntry::NodeEntry(istream &stream)
: m_expandedByDefault(true)
{
BinaryReader reader(&stream);
const byte version = reader.readByte();
const std::uint8_t version = reader.readByte();
if (!denotesNodeEntry(version)) {
throw ParsingException("Node entry expected.");
}
@ -242,16 +240,16 @@ NodeEntry::NodeEntry(istream &stream)
setLabel(reader.readLengthPrefixedString());
// read extended header for version 0x1
if (version == 0x1) {
uint16 extendedHeaderSize = reader.readUInt16BE();
std::uint16_t extendedHeaderSize = reader.readUInt16BE();
if (extendedHeaderSize >= 1) {
byte flags = reader.readByte();
std::uint8_t flags = reader.readByte();
m_expandedByDefault = flags & 0x80;
extendedHeaderSize -= 1;
}
m_extendedData = reader.readString(extendedHeaderSize);
}
const uint32 childCount = reader.readUInt32BE();
for (uint32 i = 0; i != childCount; ++i) {
const std::uint32_t childCount = reader.readUInt32BE();
for (std::uint32_t i = 0; i != childCount; ++i) {
Entry::parse(stream)->setParent(this);
}
}
@ -267,7 +265,7 @@ NodeEntry::NodeEntry(const NodeEntry &other)
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);
}
}
@ -304,7 +302,7 @@ void NodeEntry::deleteChildren(int begin, int end)
// adjust indices of subsequent children
const int diff = end - begin;
for (auto iterator = m_children.begin() + begin, end = m_children.end(); iterator != end; ++iterator) {
for (auto iterator = m_children.begin() + begin, end2 = m_children.end(); iterator != end2; ++iterator) {
(*iterator)->m_index -= diff;
}
}
@ -322,7 +320,7 @@ void NodeEntry::replaceChild(size_t at, Entry *newChild)
return;
}
// detatch the old child
// detach the old child
m_children[at]->m_parent = nullptr;
m_children[at]->m_index = -1;
@ -336,7 +334,7 @@ void NodeEntry::replaceChild(size_t at, Entry *newChild)
// do the actual assignment
newChild->m_parent = this;
newChild->m_index = at;
newChild->m_index = static_cast<int>(at);
m_children[at] = newChild;
}
@ -348,9 +346,8 @@ void NodeEntry::replaceChild(size_t at, Entry *newChild)
* if the entry specified by the provided \a path does not exist. The parent of the entry
* 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.
* \todo Use dedicated flags or at least make \a creationType const in v4.
*/
Entry *NodeEntry::entryByPath(list<string> &path, bool includeThis, EntryType *creationType)
Entry *NodeEntry::entryByPath(list<string> &path, bool includeThis, const EntryType *creationType)
{
if (path.empty()) {
return nullptr;
@ -401,15 +398,15 @@ void NodeEntry::make(ostream &stream) const
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;
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());
writer.writeUInt32BE(static_cast<std::uint32_t>(m_children.size()));
for (const Entry *const child : m_children) {
child->make(stream);
}
@ -420,6 +417,17 @@ 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.
@ -443,7 +451,7 @@ AccountEntry::AccountEntry(const string &label, NodeEntry *parent)
AccountEntry::AccountEntry(istream &stream)
{
BinaryReader reader(&stream);
byte version = reader.readByte();
std::uint8_t version = reader.readByte();
if (denotesNodeEntry(version)) {
throw ParsingException("Account entry expected.");
}
@ -454,12 +462,12 @@ AccountEntry::AccountEntry(istream &stream)
setLabel(reader.readLengthPrefixedString());
// read extended header for version 0x1
if (version == 0x1) {
const uint16 extendedHeaderSize = reader.readUInt16BE();
const std::uint16_t extendedHeaderSize = reader.readUInt16BE();
// currently there's nothing to read here
m_extendedData = reader.readString(extendedHeaderSize);
}
const uint32 fieldCount = reader.readUInt32BE();
for (uint32 i = 0; i != fieldCount; ++i) {
const std::uint32_t fieldCount = reader.readUInt32BE();
for (std::uint32_t i = 0; i != fieldCount; ++i) {
m_fields.push_back(Field(this, stream));
}
}
@ -488,10 +496,10 @@ void AccountEntry::make(ostream &stream) const
writer.writeByte(0x80 | (m_extendedData.empty() ? 0x0 : 0x1)); // version
writer.writeLengthPrefixedString(label());
if (!m_extendedData.empty()) {
writer.writeUInt16BE(m_extendedData.size());
writer.writeUInt16BE(static_cast<std::uint16_t>(m_extendedData.size()));
writer.writeString(m_extendedData);
}
writer.writeUInt32BE(m_fields.size());
writer.writeUInt32BE(static_cast<std::uint32_t>(m_fields.size()));
for (const Field &field : m_fields) {
field.make(stream);
}
@ -501,4 +509,13 @@ 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

@ -3,8 +3,7 @@
#include "./field.h"
#include <c++utilities/conversion/types.h>
#include <cstdint>
#include <iostream>
#include <list>
#include <string>
@ -20,6 +19,12 @@ enum class EntryType : int {
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 {
@ -35,14 +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 constexpr EntryType denotedEntryType(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);
@ -93,6 +100,17 @@ inline int Entry::index() const
return m_index;
}
/*!
* \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;
@ -101,17 +119,18 @@ public:
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(std::size_t at, Entry *newChild);
Entry *entryByPath(std::list<std::string> &path, bool includeThis = true, EntryType *creationType = nullptr);
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;
@ -138,12 +157,12 @@ 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;
}
constexpr EntryType Entry::denotedEntryType(byte version)
constexpr EntryType Entry::denotedEntryType(std::uint8_t version)
{
return (version & 0x80) == 0 ? EntryType::Node : EntryType::Account;
}
@ -154,13 +173,14 @@ public:
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;

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 {
@ -42,14 +41,14 @@ Field::Field(AccountEntry *tiedAccount, istream &stream)
}
m_name = reader.readLengthPrefixedString();
m_value = reader.readLengthPrefixedString();
byte type = reader.readByte();
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 uint16 extendedHeaderSize = reader.readUInt16BE();
const std::uint16_t extendedHeaderSize = reader.readUInt16BE();
// currently there's nothing to read here
m_extendedData = reader.readString(extendedHeaderSize);
}
@ -65,9 +64,9 @@ 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));
writer.writeByte(static_cast<std::uint8_t>(m_type));
if (!m_extendedData.empty()) {
writer.writeUInt16BE(m_extendedData.size());
writer.writeUInt16BE(static_cast<std::uint16_t>(m_extendedData.size()));
writer.writeString(m_extendedData);
}
}

View File

@ -5,6 +5,8 @@ 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.
*/
/*!
@ -16,9 +18,18 @@ ParsingException::ParsingException(const std::string &message) noexcept
}
/*!
* \brief Destroys the exception.
* \brief Constructs a parsing exception.
*/
ParsingException::~ParsingException() noexcept
ParsingException::ParsingException(const char *message) noexcept
: runtime_error(message)
{
}
/*!
* \brief Destroys the parsing exception.
*/
ParsingException::~ParsingException()
{
}
} // namespace Io

View File

@ -10,9 +10,11 @@ namespace Io {
class PASSWORD_FILE_EXPORT ParsingException : public std::runtime_error {
public:
ParsingException(const std::string &message = std::string()) noexcept;
~ParsingException() noexcept;
explicit ParsingException(const std::string &message = std::string()) noexcept;
explicit ParsingException(const char *message) noexcept;
~ParsingException() override;
};
} // namespace Io
#endif // PASSWORD_FILE_IO_PARSINGEXCEPTION_H

View File

@ -3,8 +3,12 @@
#include "./entry.h"
#include "./parsingexception.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/catchiofailure.h>
#include <c++utilities/io/path.h>
#include <openssl/conf.h>
#include <openssl/err.h>
@ -14,6 +18,7 @@
#include <zlib.h>
#include <cstring>
#include <filesystem>
#include <functional>
#include <limits>
#include <memory>
@ -21,11 +26,13 @@
#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
@ -39,6 +46,9 @@ const unsigned int aes256cbcIvSize = 16U;
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();
@ -50,6 +60,9 @@ PasswordFile::PasswordFile()
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);
@ -61,29 +74,35 @@ PasswordFile::PasswordFile(const string &path, const string &password)
*/
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);
memcpy(m_password, other.m_password, 32);
}
/*!
* \brief Moves the password file.
*/
PasswordFile::PasswordFile(PasswordFile &&other)
: m_path(move(other.m_path))
, m_rootEntry(move(other.m_rootEntry))
, m_extendedHeader(move(other.m_extendedHeader))
, m_encryptedExtendedHeader(move(other.m_encryptedExtendedHeader))
, m_file(move(other.m_file))
: 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)
{
memcpy(m_password, other.m_password, 32);
}
/*!
@ -97,13 +116,15 @@ PasswordFile::~PasswordFile()
* \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.");
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();
}
@ -116,7 +137,7 @@ void PasswordFile::opened()
{
m_file.seekg(0, ios_base::end);
if (m_file.tellg() == 0) {
throwIoFailure("File is empty.");
throw std::ios_base::failure("File is empty.");
} else {
m_file.seekg(0);
}
@ -140,7 +161,7 @@ void PasswordFile::create()
{
close();
if (m_path.empty()) {
throwIoFailure("Unable to create file because path is 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);
}
@ -151,7 +172,7 @@ 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()
{
@ -159,6 +180,8 @@ void PasswordFile::load()
open();
}
m_file.seekg(0);
m_version = 0;
m_saveOptions = PasswordFileSaveFlags::None;
// check magic number
if (m_freader.readUInt32LE() != 0x7770616DU) {
@ -166,28 +189,39 @@ void PasswordFile::load()
}
// check version and flags (used in version 0x3 only)
const auto 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."));
}
if (m_version >= 0x6U) {
m_saveOptions |= PasswordFileSaveFlags::PasswordHashing;
}
bool decrypterUsed, ivUsed, compressionUsed;
if (version == 0x3U) {
if (m_version >= 0x3U) {
const auto flags = m_freader.readByte();
decrypterUsed = flags & 0x80;
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();
if (m_version >= 0x4U) {
std::uint16_t extendedHeaderSize = m_freader.readUInt16BE();
m_extendedHeader = m_freader.readString(extendedHeaderSize);
} else {
m_extendedHeader.clear();
}
// get length
@ -196,7 +230,17 @@ void PasswordFile::load()
auto remainingSize = static_cast<size_t>(m_file.tellg()) - headerSize;
m_file.seekg(static_cast<streamoff>(headerSize), ios_base::beg);
// read file
// 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) {
@ -218,12 +262,23 @@ void PasswordFile::load()
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;
decryptedData.resize(remainingSize + 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
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
@ -241,7 +296,7 @@ void PasswordFile::load()
msg += ERR_error_string(errorCode, nullptr);
errorCode = ERR_get_error();
}
throw CryptoException(msg);
throw CryptoException(std::move(msg));
}
if (ctx) {
@ -252,6 +307,9 @@ void PasswordFile::load()
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
@ -263,10 +321,17 @@ void PasswordFile::load()
if (remainingSize < 8) {
throw ParsingException("File is truncated (decompressed size expected).");
}
uLongf decompressedSize = ConversionUtilities::LE::toUInt64(decryptedData.data());
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), remainingSize - 8)) {
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:
@ -278,53 +343,106 @@ void PasswordFile::load()
remainingSize = decompressedSize;
}
}
if (!remainingSize) {
throw ParsingException("Decompressed buffer is empty.");
}
// parse contents
stringstream decryptedStream(stringstream::in | stringstream::out | stringstream::binary);
decryptedStream.rdbuf()->pubsetbuf(decryptedData.data(), static_cast<streamsize>(remainingSize));
if (version >= 0x5u) {
const auto extendedHeaderSize = m_freader.readUInt16BE();
m_encryptedExtendedHeader = m_freader.readString(extendedHeaderSize);
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(decryptedStream));
}
/*!
* \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.
*/
std::uint32_t PasswordFile::mininumVersion(PasswordFileSaveFlags options) const
{
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 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 or a compression error occurs.
* \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(bool useEncryption, bool useCompression)
void PasswordFile::save(PasswordFileSaveFlags options)
{
if (!m_rootEntry) {
throw runtime_error("Root entry has not been created.");
}
// use already opened and writable file; otherwise re-open the file
if (m_file.good() && m_file.is_open() && (m_file.flags() & ios_base::out)) {
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.close();
m_file.clear();
m_file.open(m_path, ios_base::in | ios_base::out | ios_base::trunc | ios_base::binary);
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);
}
}
write(useEncryption, useCompression);
// 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 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 or a compression error occurs.
* \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(bool useEncryption, bool useCompression)
void PasswordFile::write(PasswordFileSaveFlags options)
{
if (!m_rootEntry) {
throw runtime_error("Root entry has not been created.");
@ -333,20 +451,26 @@ void PasswordFile::write(bool useEncryption, bool useCompression)
// write magic number
m_fwriter.writeUInt32LE(0x7770616DU);
// 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 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(static_cast<uint16>(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);
}
@ -354,10 +478,14 @@ void PasswordFile::write(bool useEncryption, bool useCompression)
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(static_cast<uint16>(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);
@ -370,10 +498,10 @@ void PasswordFile::write(bool useEncryption, bool useCompression)
vector<char> encryptedData;
// compress data
if (useCompression) {
if (options & PasswordFileSaveFlags::Compression) {
uLongf compressedSize = compressBound(size);
encryptedData.resize(8 + compressedSize);
ConversionUtilities::LE::getBytes(static_cast<uint64>(size), encryptedData.data());
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:
@ -381,7 +509,7 @@ void PasswordFile::write(bool useEncryption, bool useCompression)
case Z_BUF_ERROR:
throw runtime_error("Compressing failed. The destination buffer was too small.");
case Z_OK:
encryptedData.swap(decryptedData); // decompression successful
encryptedData.swap(decryptedData); // compression successful
size = 8 + compressedSize;
}
}
@ -391,19 +519,33 @@ void PasswordFile::write(bool useEncryption, bool useCompression)
}
// write data without encryption
if (!useEncryption) {
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 {
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 + 32);
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, reinterpret_cast<unsigned const char *>(m_password), iv) != 1
|| 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
@ -421,7 +563,7 @@ void PasswordFile::write(bool useEncryption, bool useCompression)
msg += ERR_error_string(errorCode, nullptr);
errorCode = ERR_get_error();
}
throw CryptoException(msg);
throw CryptoException(std::move(msg));
}
if (ctx) {
@ -429,8 +571,12 @@ void PasswordFile::write(bool useEncryption, bool useCompression)
}
// 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();
}
/*!
@ -450,6 +596,7 @@ void PasswordFile::clear()
clearPath();
clearPassword();
clearEntries();
m_openOptions = PasswordFileOpenFlags::None;
m_extendedHeader.clear();
m_encryptedExtendedHeader.clear();
}
@ -457,15 +604,16 @@ 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) {
throw runtime_error("Root entry has not been created.");
}
fstream output(targetPath.c_str(), ios_base::out);
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 << " ";
@ -555,14 +703,6 @@ void PasswordFile::close()
m_file.clear();
}
/*!
* \brief Returns the current file path.
*/
const string &PasswordFile::path() const
{
return m_path;
}
/*!
* \brief Sets the current file path. Closes the file if currently opened.
*/
@ -572,47 +712,15 @@ void PasswordFile::setPath(const string &value)
m_path = value;
// support "file://" protocol
if (ConversionUtilities::startsWith(m_path, "file:")) {
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()
{
@ -621,30 +729,22 @@ bool PasswordFile::isEncryptionUsed()
}
m_file.seekg(0);
//check magic number
// check magic number
if (m_freader.readUInt32LE() != 0x7770616DU) {
return false;
}
//check version
// 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;
}
}
/*!
* \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; otherwise returns zero.
*/
@ -656,4 +756,66 @@ size_t PasswordFile::size()
m_file.seekg(0, ios::end);
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

@ -6,7 +6,9 @@
#include <c++utilities/io/binaryreader.h>
#include <c++utilities/io/binarywriter.h>
#include <c++utilities/io/nativefilestream.h>
#include <c++utilities/misc/flagenumclass.h>
#include <cstdint>
#include <fstream>
#include <iostream>
#include <memory>
@ -16,6 +18,25 @@ namespace Io {
class NodeEntry;
enum class PasswordFileOpenFlags : std::uint64_t {
None = 0,
ReadOnly = 1,
Default = None,
};
PASSWORD_FILE_EXPORT std::string flagsToString(PasswordFileOpenFlags flags);
enum class PasswordFileSaveFlags : std::uint64_t {
None = 0,
Encryption = 1,
Compression = 2,
PasswordHashing = 4,
AllowToCreateNewFile = 8,
Default = Encryption | Compression | PasswordHashing | AllowToCreateNewFile,
};
PASSWORD_FILE_EXPORT std::string flagsToString(PasswordFileSaveFlags flags);
class PASSWORD_FILE_EXPORT PasswordFile {
public:
explicit PasswordFile();
@ -23,16 +44,16 @@ public:
PasswordFile(const PasswordFile &other);
PasswordFile(PasswordFile &&other);
~PasswordFile();
IoUtilities::NativeFileStream &fileStream();
void open(bool readOnly = false);
CppUtilities::NativeFileStream &fileStream();
void open(PasswordFileOpenFlags options = PasswordFileOpenFlags::Default);
void opened();
void generateRootEntry();
void create();
void close();
void load();
// FIXME: use flags in v4
void save(bool useEncryption = true, bool useCompression = true);
void write(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;
@ -41,34 +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;
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;
IoUtilities::NativeFileStream 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 IoUtilities::NativeFileStream &PasswordFile::fileStream()
inline CppUtilities::NativeFileStream &PasswordFile::fileStream()
{
return m_file;
}
/*!
* \brief Returns the current file path.
*/
inline const std::string &PasswordFile::path() const
{
return m_path;
}
/*!
* \brief Clears the current path. Causes the file to be closed if currently opened.
*/
inline void PasswordFile::clearPath()
{
close();
m_path.clear();
}
/*!
* \brief Returns the current password. It will be used when loading or saving using encryption.
*/
inline const std::string &PasswordFile::password() const
{
return m_password;
}
/*!
* \brief Sets the current password. It will be used when loading an encrypted file or when saving using encryption.
*/
inline void PasswordFile::setPassword(const std::string &password)
{
m_password = password;
}
/*!
* \brief Sets the current password. It will be used when loading an encrypted file or when saving using encryption.
*/
inline void PasswordFile::setPassword(const char *password, const size_t passwordSize)
{
m_password.assign(password, passwordSize);
}
/*!
* \brief Clears the current password.
*/
inline void PasswordFile::clearPassword()
{
m_password.clear();
}
/*!
* \brief Returns an indication whether the file is open.
*/
inline bool PasswordFile::isOpen() const
{
return m_file.is_open();
}
/*!
* \brief Returns the extended header.
*/
inline std::string &PasswordFile::extendedHeader()
{
return m_extendedHeader;
}
/*!
* \brief Returns the extended header.
*/
inline const std::string &PasswordFile::extendedHeader() const
{
return m_extendedHeader;
}
/*!
* \brief Returns the encrypted extended header.
*/
inline std::string &PasswordFile::encryptedExtendedHeader()
{
return m_encryptedExtendedHeader;
}
/*!
* \brief Returns the encrypted extended header.
*/
inline const std::string &PasswordFile::encryptedExtendedHeader() const
{
return m_encryptedExtendedHeader;
}
/*!
* \brief Returns the file version used the last time when saving the file (the version of the file as it is on the disk).
* \remarks The version might change when re-saving with different options. See mininumVersion().
*/
inline std::uint32_t PasswordFile::version() const
{
return m_version;
}
/*!
* \brief Returns the options used to open the file.
*/
inline PasswordFileOpenFlags PasswordFile::openOptions() const
{
return m_openOptions;
}
/*!
* \brief Returns the save options used the last time when saving the file.
*/
inline PasswordFileSaveFlags PasswordFile::saveOptions() const
{
return m_saveOptions;
}
} // namespace Io
CPP_UTILITIES_MARK_FLAG_ENUM_CLASS(Io, Io::PasswordFileOpenFlags);
CPP_UTILITIES_MARK_FLAG_ENUM_CLASS(Io, Io::PasswordFileSaveFlags);
#endif // PASSWORD_FILE_IO_PASSWORD_FILE_H

View File

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

View File

@ -2,15 +2,12 @@
#include "./utils.h"
#include <c++utilities/tests/testutils.h>
using namespace TestUtilities;
#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
using namespace std;
using namespace Io;
using namespace TestUtilities::Literals;
using namespace CppUtilities::Literals;
using namespace CPPUNIT_NS;
@ -26,8 +23,8 @@ class EntryTests : public TestFixture {
CPPUNIT_TEST_SUITE_END();
public:
void setUp();
void tearDown();
void setUp() override;
void tearDown() override;
void testNewEntryCorrectlyInitialized();
void testNesting();
@ -160,7 +157,7 @@ void EntryTests::testEntryByPath()
CPPUNIT_ASSERT_EQUAL_MESSAGE("return current instance", static_cast<Entry *>(&root), root.entryByPath(path));
path = { "root", "foo" };
CPPUNIT_ASSERT_MESSAGE("nullptr for non-existant path", !root.entryByPath(path));
CPPUNIT_ASSERT_MESSAGE("nullptr for non-existent path", !root.entryByPath(path));
path = { "root", "node" };
const auto *const node = root.entryByPath(path, true, &createNode);
@ -190,7 +187,7 @@ void EntryTests::testUniqueLabels()
{
NodeEntry root("root");
const auto *const fooEntry = new AccountEntry("foo", &root);
VAR_UNUSED(fooEntry)
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);

View File

@ -3,15 +3,12 @@
#include "./utils.h"
#include <c++utilities/tests/testutils.h>
using namespace TestUtilities;
#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
using namespace std;
using namespace Io;
using namespace TestUtilities::Literals;
using namespace CppUtilities::Literals;
using namespace CPPUNIT_NS;
@ -25,8 +22,8 @@ class FieldTests : public TestFixture {
CPPUNIT_TEST_SUITE_END();
public:
void setUp();
void tearDown();
void setUp() override;
void tearDown() override;
void testNewFieldCorrectlyInitialized();
void testMutation();

View File

@ -1,6 +1,6 @@
#include "../util/opensslrandomdevice.h"
#include <c++utilities/tests/testutils.h>
#include "./utils.h"
#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
@ -9,7 +9,7 @@
using namespace std;
using namespace Util;
using namespace TestUtilities::Literals;
using namespace CppUtilities::Literals;
using namespace CPPUNIT_NS;
@ -22,8 +22,8 @@ class OpenSslRandomDeviceTests : public TestFixture {
CPPUNIT_TEST_SUITE_END();
public:
void setUp();
void tearDown();
void setUp() override;
void tearDown() override;
void testUsageWithStandardClasses();
};

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

@ -2,15 +2,15 @@
#include "../io/entry.h"
#include "../io/passwordfile.h"
#include <c++utilities/tests/testutils.h>
#include "./utils.h"
#include <cppunit/TestFixture.h>
#include <cppunit/extensions/HelperMacros.h>
using namespace std;
using namespace Io;
using namespace TestUtilities::Literals;
using namespace CppUtilities;
using namespace CppUtilities::Literals;
using namespace CPPUNIT_NS;
/*!
@ -19,21 +19,19 @@ using namespace CPPUNIT_NS;
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);
@ -51,19 +49,19 @@ void PasswordFileTests::tearDown()
*/
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_EQUAL(!testfile1password.empty(), file.isEncryptionUsed());
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, !testfile1password.empty(), file.isEncryptionUsed());
// attempt to decrypt using a wrong password
file.setPassword(testfile1password + "asdf");
if (!testfile1password.empty()) {
@ -74,86 +72,166 @@ void PasswordFileTests::testReading(
file.load();
// test root entry
const NodeEntry *const rootEntry = file.rootEntry();
CPPUNIT_ASSERT_EQUAL("testfile1"s, rootEntry->label());
CPPUNIT_ASSERT_EQUAL(4_st, rootEntry->children().size());
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, "testfile1"s, rootEntry->label());
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, 4_st, rootEntry->children().size());
// test testaccount1
CPPUNIT_ASSERT_EQUAL("testaccount1"s, rootEntry->children()[0]->label());
CPPUNIT_ASSERT_EQUAL(EntryType::Account, rootEntry->children()[0]->type());
CPPUNIT_ASSERT_EQUAL("pin"s, static_cast<AccountEntry *>(rootEntry->children()[0])->fields().at(0).name());
CPPUNIT_ASSERT_EQUAL("123456"s, static_cast<AccountEntry *>(rootEntry->children()[0])->fields().at(0).value());
CPPUNIT_ASSERT_EQUAL(FieldType::Password, static_cast<AccountEntry *>(rootEntry->children()[0])->fields().at(0).type());
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(FieldType::Normal, static_cast<AccountEntry *>(rootEntry->children()[0])->fields().at(1).type());
CPPUNIT_ASSERT_THROW(static_cast<AccountEntry *>(rootEntry->children()[0])->fields().at(2), out_of_range);
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, FieldType::Normal, static_cast<AccountEntry *>(rootEntry->children()[0])->fields().at(1).type());
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, 2_st, static_cast<AccountEntry *>(rootEntry->children()[0])->fields().size());
// test testaccount2
CPPUNIT_ASSERT_EQUAL("testaccount2"s, rootEntry->children()[1]->label());
CPPUNIT_ASSERT_EQUAL(EntryType::Account, rootEntry->children()[1]->type());
CPPUNIT_ASSERT_EQUAL(0_st, static_cast<AccountEntry *>(rootEntry->children()[1])->fields().size());
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, "testaccount2"s, rootEntry->children()[1]->label());
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, EntryType::Account, rootEntry->children()[1]->type());
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, 0_st, static_cast<AccountEntry *>(rootEntry->children()[1])->fields().size());
// test testcategory1
CPPUNIT_ASSERT_EQUAL("testcategory1"s, rootEntry->children()[2]->label());
CPPUNIT_ASSERT_EQUAL(EntryType::Node, rootEntry->children()[2]->type());
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(3_st, category->children().size());
CPPUNIT_ASSERT_EQUAL(EntryType::Node, category->children()[2]->type());
CPPUNIT_ASSERT_EQUAL(2_st, static_cast<NodeEntry *>(category->children()[2])->children().size());
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, 3_st, category->children().size());
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, EntryType::Node, category->children()[2]->type());
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, 2_st, static_cast<NodeEntry *>(category->children()[2])->children().size());
// test testaccount3
CPPUNIT_ASSERT_EQUAL("testaccount3"s, rootEntry->children()[3]->label());
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_EQUAL(!testfile2password.empty(), file.isEncryptionUsed());
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, !testfile2password.empty(), file.isEncryptionUsed());
file.setPassword(testfile2password);
file.load();
const NodeEntry *const rootEntry2 = file.rootEntry();
if (testfile2Mod) {
CPPUNIT_ASSERT_EQUAL("testfile2 - modified"s, rootEntry2->label());
CPPUNIT_ASSERT_EQUAL(2_st, rootEntry2->children().size());
CPPUNIT_ASSERT_EQUAL("newAccount"s, rootEntry2->children()[1]->label());
if (testfilesMod) {
if (extendedHeaderMod) {
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, static_cast<std::uint32_t>(6), file.version());
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, "encryption, password hashing"s, flagsToString(file.saveOptions()));
} else {
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, static_cast<std::uint32_t>(3), file.version());
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, "encryption"s, flagsToString(file.saveOptions()));
}
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, "testfile2 - modified"s, rootEntry2->label());
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, 2_st, rootEntry2->children().size());
CPPUNIT_ASSERT_EQUAL_MESSAGE(context, "newAccount"s, rootEntry2->children()[1]->label());
} else {
CPPUNIT_ASSERT_EQUAL("testfile2"s, rootEntry2->label());
CPPUNIT_ASSERT_EQUAL(1_st, rootEntry2->children().size());
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()
{
const string testfile1 = TestUtilities::workingCopyPath("testfile1.pwmgr");
const 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

View File

@ -9,11 +9,11 @@
#include <ostream>
namespace TestUtilities {
namespace CppUtilities {
inline std::ostream &operator<<(std::ostream &out, const Io::Entry *entry)
{
return out << ConversionUtilities::joinStrings(entry->path(), "/");
return out << joinStrings(entry->path(), "/");
}
inline std::ostream &operator<<(std::ostream &out, const Io::Field *field)
@ -21,6 +21,10 @@ inline std::ostream &operator<<(std::ostream &out, const Io::Field *field)
return out << field->name() << '=' << field->value();
}
} // namespace TestUtilities
} // 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.
*/
@ -35,5 +43,27 @@ void clean()
// remove error strings
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,14 +1,25 @@
#ifndef PASSWORD_FILE_UTIL_OPENSSL_H
#define 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

View File

@ -10,6 +10,7 @@
#include <string>
using namespace std;
using namespace CppUtilities;
namespace Util {
@ -28,11 +29,11 @@ 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));
return LE::toUInt32(reinterpret_cast<char *>(buf));
}
// handle error case
@ -44,7 +45,7 @@ uint32 OpenSslRandomDevice::operator()() const
errorMsg += ERR_error_string(errorCode, nullptr);
errorCode = ERR_get_error();
}
throw Io::CryptoException(errorMsg);
throw Io::CryptoException(std::move(errorMsg));
}
/*!

View File

@ -3,18 +3,17 @@
#include "../global.h"
#include <c++utilities/conversion/types.h>
#include <cstdint>
#include <limits>
namespace Util {
class PASSWORD_FILE_EXPORT OpenSslRandomDevice {
public:
using result_type = uint32;
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();