0

I need to encrypt data sent from angular-5 to php script and decrypt it in php then process it. I am new to these stuff.

Firstly, I installed the crypto-js lib:

npm install --save crypto-js

Then I imported it into app.module.ts:

import * as crypto from 'crypto-js';

And added it to imports:

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    crypto

Inside my app.component.ts file I am trying to encrypt a variable and test the result:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  this.crypto...
}

I've got an error on the this.:

Unexpected token. A constructor, method, accessor, or property was expected.

5
  • Is crypto actually an Angular module? You can't just put arbitrary things in that list. Commented May 8, 2018 at 18:50
  • it was installed normally. Commented May 8, 2018 at 18:50
  • any other library to use it ? Commented May 8, 2018 at 18:51
  • What do you mean "it was installed normally"? By npm? That's nothing to do with Angular's modules. I'd suggest you read up on the DI in Angular: angular.io/guide/dependency-injection Commented May 8, 2018 at 18:52
  • Keep in mind that if you're using symmetric encryption on the client side then the encryption key used is visible to the user/client. Which means anyone can decrypt anyone else's traffic. So what you are doing is pointless. You should be using HTTPS. Commented May 8, 2018 at 22:50

1 Answer 1

1

Rather importing * from crypto-js my team has simply put the crypto-js dependency in the scripts array in the .angular-cli.json.

Once you've done this at the top of the ts file you plan to use crypto you can add declare const CryptoJS; and then use it normally.

This method can also be used on any other non es6 or ts packaged dependency.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Had this error: Cannot read property 'ceil' of undefined when using CryptoJS.MD5 with import * as CryptoJS from 'crypto-js' when moving from Angular 5.2 to Angular 6.x when trying to build with "optimization": true, in angular.json. Have added : "scripts": ["node_modules/crypto-js/crypto-js.js" ] in architect.build (yes you cannot add that into architect.serve, but it still work with ng serve) and declare const CryptoJS; and now it do not throw when using CryptoJS with "optimization": true !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.