3
votes

I new bee of Ionic and angular. I used Browserify to require Crypto module of nodejs for my Ionic project. Following are my steps:

  1. I added new line to app.js file

angular.module(.....).constant('Crypto',require('crypto'))

  1. I run the command line, which create new file perfectly with code of Crypto module and app.js file

browserify app.js > bundle.js

  1. I replace app.js by bundle.js in index.html file

  2. I try to test it in service.js

angular.module('mapp.services').factory('abc',['$http','Crypto',function($http,Crypto){
return {
getAllProduct:function(){ console.log(Crypto.SHA256("Message")); });
} }]);

It return message "Crypto.SHA256 is not a function". I think that "constant" means a value, not a static object, so that I cannot pass Crypto to "constant". So, how can I require all needed modules at app.js file by Browserify and then pass use it at other js file, like $http? Thanks!

2
You can get a more useful error message in the console if you do console.dir(Crypto) instead of trying to call a function that may not exist, this will let you see the actual javascript objects that the require('Crypto') call actually injected into your application via browserify. - Ryan Weir
I added console.dir(Crypto). It return "0 977846 dir". What it means? And I think that if I push it to "angular.module(.....).constant('Crypto',require('crypto'))", the system will consider it as simple value only, right? - supper aban_89
It looks like it tried to import a wrapper to a native system call and failed. Basically all Crypto is doing on the server is wrapping OpenSSL so trying to convert it t for browser use is just creating a string like you see with a file pointer and not a Crypto object that can perform actual encryption functions. You need to switch libraries to make what you're doing work. - Ryan Weir

2 Answers

2
votes

Sorry because of my stupid question. The fact that we can assign Crypto object to constant pool. The problem is my code. To encrypt a string, the code must be

crypto.createHash('sha256').update(mystr).digest('base64');

instead of

crypto.sha256(mystr)

Now problem solved, but thanks for your all reply and comments.

0
votes

I don't think Crypto will work on the client, it's the server-side library for performing encryption and is largely a wrapper around OpenSSL (see here).

The functions that it wraps cannot be called in Ionic/Angular for the simple reason that they aren't available on the client.

Try using CryptoJS instead as was proposed by this answer - it was designed to be used client-side like in your Ionic/Angular project to perform cryto-related operations.