Angular5集成crypto-js遇意外令牌错误,需实现与PHP加解密
Hey there, let's sort out this issue and get your data encryption working smoothly between Angular 5 and PHP. The Error unexpected token you're seeing comes from a common mistake in how you're integrating Crypto-JS into your Angular app—let's break down the correct steps:
Step 1: Correctly Install & Import Crypto-JS
Your initial install command is spot-on:
npm install --save crypto-js
Here's the mistake: Crypto-JS is not an Angular module, so you shouldn't add it to the imports array in app.module.ts. That's exactly why you're getting the syntax error. Instead, import it directly in the components or services where you need encryption functionality.
Step 2: Angular 5 Encryption Implementation
Let's write a working encryption example in app.component.ts. We'll use AES-256-CBC (a widely supported algorithm that plays nicely with PHP) for consistency:
import { Component } from '@angular/core'; import * as CryptoJS from 'crypto-js'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { // Define your secret key and initialization vector (IV) // Important: Use a 32-byte key for AES-256, and 16-byte IV (matches AES block size) private secretKey = CryptoJS.enc.Utf8.parse('your-32-character-secret-key-here'); private iv = CryptoJS.enc.Utf8.parse('your-16-character-iv-here'); encryptData(data: any): string { // Convert data to JSON string first (if it's an object) const jsonData = JSON.stringify(data); // Encrypt using AES-256-CBC const encrypted = CryptoJS.AES.encrypt(jsonData, this.secretKey, { iv: this.iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 }); // Return encrypted data as base64 string for easy transmission return encrypted.toString(); } // Example: Send encrypted data to PHP sendDataToPHP() { const userData = { name: 'John Doe', email: 'john@example.com' }; const encryptedData = this.encryptData(userData); // Use HttpClient to send data (don't forget to import HttpClientModule in app.module.ts!) // this.http.post('your-php-script-url.php', { encrypted: encryptedData }).subscribe(response => { // console.log('PHP Response:', response); // }); } }
If you're using HTTP requests, make sure to add HttpClientModule to your app.module.ts imports (this is a valid Angular module):
import { HttpClientModule } from '@angular/common/http'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, HttpClientModule ], // Only add Angular modules here! bootstrap: [ AppComponent ] }) export class AppModule { }
Step 3: PHP Decryption Implementation
Now let's write the PHP script to decrypt the data from Angular. We'll use PHP's openssl_decrypt function, matching the exact AES-256-CBC settings from Angular:
<?php // Fetch encrypted data from the POST request $encryptedData = $_POST['encrypted']; // Use the SAME secret key and IV as defined in Angular $secretKey = 'your-32-character-secret-key-here'; $iv = 'your-16-character-iv-here'; // Decrypt the data $decrypted = openssl_decrypt( $encryptedData, 'aes-256-cbc', $secretKey, OPENSSL_RAW_DATA, $iv ); // Convert decrypted string back to a usable array/object $decodedData = json_decode($decrypted, true); // Process the data and send a response if ($decodedData) { echo json_encode(['status' => 'success', 'data' => $decodedData]); } else { echo json_encode(['status' => 'error', 'message' => 'Decryption failed']); } ?>
Critical Tips to Avoid Issues
- Consistency is everything: The secret key, IV, encryption algorithm, padding, and mode must be identical on both Angular and PHP sides—any mismatch will break decryption.
- Secure key management: Never hardcode keys/IVs in production. Use environment variables or secure key storage systems instead.
- Encoding safety: We use base64 for encrypted data transmission because it avoids issues with special characters in HTTP requests.
- Error handling: Add try/catch blocks in Angular and error checking in PHP to handle cases where decryption fails (e.g., invalid data, mismatched keys).
内容的提问来源于stack exchange,提问作者alim1990

