Make UserDefault encrypt/decrypt algorithm can be customlized

This commit is contained in:
halx99 2020-08-27 12:37:20 +08:00
parent 33c5fe6553
commit 1c76fd48ce
2 changed files with 17 additions and 14 deletions

View File

@ -36,6 +36,7 @@ THE SOFTWARE.
#include "openssl/aes.h"
#include "openssl/modes.h"
#include "openssl/rc4.h"
#include "base/CCUserDefault.h"
#include "platform/CCCommon.h"
@ -90,10 +91,6 @@ NS_CC_BEGIN
UserDefault* UserDefault::_userDefault = nullptr;
bool UserDefault::_encryptEnabled = false;
std::string UserDefault::_key;
std::string UserDefault::_iv;
static void ud_setkey(std::string& lhs, const cxx17::string_view& rhs) {
static const size_t keyLen = 16;
if (!rhs.empty()) {
@ -110,7 +107,7 @@ static void ud_write_v_s(yasio::obstream& obs, const cxx17::string_view value)
size_t valpos = obs.length();
obs.write_v(value);
if(!value.empty())
UserDefault::encrypt(obs.wptr(valpos + sizeof(int32_t)), obs.length() - valpos - sizeof(int32_t), AES_ENCRYPT);
UserDefault::getInstance()->encrypt(obs.wptr(valpos + sizeof(int32_t)), obs.length() - valpos - sizeof(int32_t), AES_ENCRYPT);
}
void UserDefault::setEncryptEnabled(bool enabled, const cxx17::string_view& key, const cxx17::string_view& iv)

View File

@ -216,15 +216,20 @@ public:
*/
static void setDelegate(UserDefault *delegate);
/* AES cfb128 encrypt support
/*
** @params:
** key: 16bytes key
** iv: 16bytes iv
*/
static void setEncryptEnabled(bool enabled, const cxx17::string_view& key, const cxx17::string_view& iv);
virtual void setEncryptEnabled(bool enabled, const cxx17::string_view& key, const cxx17::string_view& iv);
static void encrypt(std::string& inout, int enc);
static void encrypt(char* inout, size_t size, int enc);
void encrypt(std::string& inout, int enc);
/*
* Mark encrypt function as virtual, default use AES cfb128 encrypt/decrypt
* you can write your own delegate to replace encrypt/decrypt algorithm
*/
virtual void encrypt(char* inout, size_t size, int enc);
protected:
UserDefault();
@ -235,7 +240,8 @@ protected:
void closeFileMapping();
void setValueForKey(const std::string& key, const std::string& value);
private:
protected:
std::unordered_map<std::string, std::string> _values;
@ -247,10 +253,10 @@ private:
int _realSize = 0; // real data size without key/value entities count field
bool _initialized = false;
// cfb128 encrpyt args
static bool _encryptEnabled;
static std::string _key;
static std::string _iv;
// encrpyt args
bool _encryptEnabled;
std::string _key;
std::string _iv;
};