std::string f = "Pesquisa de domínio GoDaddy - Brave"; weakEncrypt(f, 16);…
- User
std::string f = "Pesquisa de domínio GoDaddy - Brave";
weakEncrypt(f, 16); weakDecrypt(f, 16); why the decryption is failing?bool weakEncrypt(std::string& data, size_t tagSize) { if (data.empty()) return false;
int randomSize = data.length() + 9; // Generate a salt from the password + a random number unsigned char pwhash[SHA256_DIGEST_LENGTH]; std::vector<unsigned char> saltInput(reinterpret_cast<const unsigned char*>(password.data()), reinterpret_cast<const unsigned char*>(password.data()) + password.size()); saltInput.push_back(static_cast<unsigned char>(randomSize)); SHA256(saltInput.data(), saltInput.size(), pwhash); std::vector<unsigned char> salt(pwhash, pwhash + 32); // Derive nonce std::vector<unsigned char> context; context.reserve(password.size() + salt.size()); context.insert(context.end(), reinterpret_cast<const unsigned char*>(password.data()), reinterpret_cast<const unsigned char*>(password.data()) + password.size()); context.insert(context.end(), salt.begin(), salt.end()); unsigned char hash[SHA256_DIGEST_LENGTH]; SHA256(context.data(), context.size(), hash); std::vector<unsigned char> nonce(hash, hash + 12); // ChaCha20-Poly1305 uses 12-byte nonce // Derive key from password unsigned char key[32]; SHA256(reinterpret_cast<const unsigned char*>(password.data()), password.size(), key); // Encrypt with ChaCha20-Poly1305 EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new(); if (!ctx) return false; if (EVP_EncryptInit_ex(ctx, EVP_chacha20_poly1305(), nullptr, key, nonce.data()) != 1) { EVP_CIPHER_CTX_free(ctx); return false; } // Use data string directly for in-place encryption size_t originalSize = data.size(); std::string dataCopy = data; RtlSecureZeroMemory(&data[0], data.size()); data.resize(originalSize + EVP_MAX_BLOCK_LENGTH + tagSize); int ciphertextLen; if (EVP_EncryptUpdate(ctx, reinterpret_cast<unsigned char*>(&data[0]), &ciphertextLen, reinterpret_cast<const unsigned char*>(dataCopy.data()), originalSize) != 1) { EVP_CIPHER_CTX_free(ctx); return false; } RtlSecureZeroMemory(&dataCopy[0], dataCopy.size()); int finalLen; if (EVP_EncryptFinal_ex(ctx, reinterpret_cast<unsigned char*>(&data[ciphertextLen]), &finalLen) != 1) { EVP_CIPHER_CTX_free(ctx); return false; } ciphertextLen += finalLen; // Get the authentication tag std::vector<unsigned char> tag(16); // Always get full 16-byte tag if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, 16, tag.data()) != 1) { EVP_CIPHER_CTX_free(ctx); return false; } // Copy only the requested tag size std::copy(tag.begin(), tag.begin() + tagSize, data.begin() + ciphertextLen); ciphertextLen += tagSize; EVP_CIPHER_CTX_free(ctx); OPENSSL_cleanse(key, sizeof(key)); data.resize(ciphertextLen); return true;}
bool weakDecrypt(std::string& data, size_t tagSize) { if (data.size() <= 1 + tagSize) // At least 1 byte for randomSize + tag return false;
- Assistant