| 333 | } |
| 334 | |
| 335 | bool encrypt_string_gcm(const wstring& str, const BYTE *key, string& base64_out) |
| 336 | { |
| 337 | BYTE iv[BLOCK_IV_LEN]; |
| 338 | |
| 339 | bool rval = true; |
| 340 | |
| 341 | if (!get_sys_random_bytes(iv, sizeof(iv))) |
| 342 | return false; |
| 343 | |
| 344 | auto context = get_crypt_context(BLOCK_IV_LEN, AES_MODE_GCM); |
| 345 | |
| 346 | if (!context) |
| 347 | return false; |
| 348 | |
| 349 | try { |
| 350 | string utf8; |
| 351 | if (!unicode_to_utf8(&str[0], utf8)) |
| 352 | throw(-1); |
| 353 | |
| 354 | BYTE aad[8]; |
| 355 | memset(aad, 0, sizeof(aad)); |
| 356 | |
| 357 | vector<BYTE> encrypted(utf8.size() + BLOCK_IV_LEN + BLOCK_TAG_LEN); |
| 358 | |
| 359 | memcpy(&encrypted[0], iv, sizeof(iv)); |
| 360 | |
| 361 | int ctlen = encrypt((const BYTE*)&utf8[0], (int)utf8.size(), aad, (int)sizeof(aad), key, iv, &encrypted[0] + (int)sizeof(iv), &encrypted[0] + sizeof(iv) + utf8.size(), context.get()); |
| 362 | |
| 363 | if (ctlen != utf8.size()) |
| 364 | throw(-1); |
| 365 | |
| 366 | if (!base64_encode(&encrypted[0], ctlen + sizeof(iv) + BLOCK_TAG_LEN, base64_out, false, true)) |
| 367 | throw(-1); |
| 368 | |
| 369 | } catch (...) { |
| 370 | rval = false; |
| 371 | } |
| 372 | |
| 373 | return rval; |
| 374 | } |
| 375 | |
| 376 | bool decrypt_string_gcm(const string& base64_in, const BYTE *key, wstring& str) |
| 377 | { |
no test coverage detected