Несмотря на эти усилия, поле, которое накапливается на стороне Php, Decrypts на nothers -nepts на nots. сторона. < /p>
Я ожидал, что поле категории будет «фаст -фудом», но он был возвращен как пустая строка ('') вместо этого. < /p>
output:
{
«id»: 1,
ement »:« Burger »,
« Сообщение »:« Данные ». />} < /p>
Вот мой код PHP API (api.php):
< /code>
и вот мой клиент -код javascript (node.js) (client.js):
// client.js
// 1. Import necessary library
const CryptoJS = require('crypto-js');
// fetch is built-in since Node.js v18+.
// For older versions, import like this: const fetch = require('node-fetch');
// --- 2. Configuration ---
// Key must match the PHP side exactly!
const SECRET_KEY = 'MySuperSecretKeyForThisTest1234';
const API_URL = 'http://localhost/crypto-test/api.php';
// --- 3. Decryption function ---
function decryptData(base64Payload, key) {
try {
// Convert our Key to a format CryptoJS understands
const key_utf8 = CryptoJS.enc.Utf8.parse(key);
// **IMPORTANT:** Decode Base64 first
const encrypted_data_with_iv = CryptoJS.enc.Base64.parse(base64Payload);
// Separate IV from the encrypted data
// AES-256-CBC IV is 16 bytes long
const iv_size = 16;
const iv = CryptoJS.lib.WordArray.create(encrypted_data_with_iv.words.slice(0, iv_size / 4));
const encrypted_data = CryptoJS.lib.WordArray.create(encrypted_data_with_iv.words.slice(iv_size / 4));
// Decrypt
const decrypted = CryptoJS.AES.decrypt(
{ ciphertext: encrypted_data },
key_utf8,
{ iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 }
);
// Convert the result back to a String (UTF-8)
return decrypted.toString(CryptoJS.enc.Utf8);
} catch (error) {
console.error("Decryption Error:", error);
return "Decryption failed!";
}
}
// --- 4. Main function to call API and display results ---
async function main() {
console.log("
try {
const response = await fetch(API_URL);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log("\n
console.log(data);
// Decrypt the encrypted data
const encryptedCategory = data.category_encrypted;
const decryptedCategory = decryptData(encryptedCategory, SECRET_KEY);
console.log(`\n
// Prepare final data for display
const finalResult = { ...data, category: decryptedCategory };
delete finalResult.category_encrypted;
console.log("\n
console.log(finalResult);
} catch (error) {
console.error("\n
}
}
// Start execution!
main();
Подробнее здесь: https://stackoverflow.com/questions/796 ... lts-in-emp