123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116 |
- //
- // Created by robin on 2/26/17.
- //
-
- #include <openssl/aes.h>
- #include <cstring>
- #include "CryptoBusiness.h"
-
- std::string CryptoBusiness::_hex = "0123456789ABCDEF";
-
- CryptoBusiness::CryptoBusiness()
- {
-
- }
-
- std::string CryptoBusiness::getKey() const
- {
- return _key;
- }
-
- void CryptoBusiness::setKey(std::string key)
- {
- _key = key;
- }
-
- std::string CryptoBusiness::encrypt16(std::string data)
- {
- unsigned char enc_out[16 * sizeof(char)];
- AES_KEY enc_key;
- AES_set_encrypt_key((const unsigned char*)_key.c_str(), 128, &enc_key);
- AES_encrypt((const unsigned char*)data.c_str(), enc_out, &enc_key);
- return std::string((char*)enc_out, 16 * sizeof(char));
- }
-
- std::string CryptoBusiness::encrypt(std::string data)
- {
- std::string out;
- if (data.length() % 16 != 0)
- {
- data += std::string(16 - data.length() % 16, 0);
- }
- for (size_t i = 0; i < data.length(); i += 16)
- {
- out += encrypt16(data.substr(i, i + 16));
- }
- return out;
- }
-
- std::string CryptoBusiness::decrypt16(std::string data)
- {
- unsigned char dec_out[16 * sizeof(char)];
- memset(dec_out, 0, 16);
- AES_KEY dec_key;
- AES_set_decrypt_key((const unsigned char*)_key.c_str(), 128, &dec_key);
- AES_decrypt((const unsigned char*)data.c_str(), dec_out, &dec_key);
- int s = 16;
- for(int i = 15; i >= 0 && dec_out[i] == 0; --i)
- --s;
- return std::string((char*)dec_out, s);
- }
-
- std::string CryptoBusiness::decrypt(std::string data)
- {
- std::string out;
- for (size_t i = 0; i < data.length(); i += 16)
- {
- out += decrypt16(data.substr(i, i + 16));
- }
- return out;
- }
-
- std::string CryptoBusiness::toHex(std::string data)
- {
- size_t len = data.length();
-
- std::string output;
- output.reserve(2 * len);
- for (size_t i = 0; i < len; ++i)
- {
- const unsigned char c = data[i];
- output.push_back(_hex[c >> 4]);
- output.push_back(_hex[c & 15]);
- }
- return output;
- }
-
- std::string CryptoBusiness::fromHex(std::string data)
- {
- size_t len = data.length();
-
- std::string output;
- output.reserve(len / 2);
- for (size_t i = 0; i < len; i += 2)
- {
- char a = data[i];
- const char* p = std::lower_bound(_hex.c_str(), _hex.c_str() + 16, a);
-
- char b = data[i + 1];
- const char* q = std::lower_bound(_hex.c_str(), _hex.c_str() + 16, b);
-
- output.push_back(((p - _hex.c_str()) << 4) | (q - _hex.c_str()));
- }
- return output;
- }
-
- std::string CryptoBusiness::encryptToHex(std::string data)
- {
- auto encrypted = encrypt(data);
- return toHex(encrypted);
- }
-
- std::string CryptoBusiness::decryptFromHex(std::string data)
- {
- auto d = fromHex(data);
- return decrypt(d);
- }
|