S.M_Emamian
S.M_Emamian

Reputation: 17383

TypeError: Cannot read property 'random' of undefined - crypto-js

I'm using crypto-js inside reactjs and everything works fine on localhost. but on server with chrome I got this error message:

TypeError: Cannot read property 'random' of undefined

on firefox:

TypeError: "r is undefined"

my code:

import CryptoJS from 'crypto-js';

console.log('text',text); //printed on console as well
var p = randomString(10) 
console.log('p',p) //printed on console as well
var c = CryptoJS.AES.encrypt(text,p).toString(); // error line
console.log('crypted',c+p)//not printed !

my function:

  function setWindow(text){
    console.log('text',text);
    var p = randomString(10)
    console.log('p',p)
    var c = CryptoJS.AES.encrypt(text,p).toString();
    console.log('crypted',c+p)
    return c+p;
  }

"crypto-js": "^3.1.9-1",

I don't know where is my problem! I removed node_modules, but I got the same error. my site: http://posweb.ccg24.com/signin

updated

  function randomString(length) {
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for (var i = 0; i < length; i++)
      text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
  }

Upvotes: 0

Views: 3566

Answers (2)

Luan Persini
Luan Persini

Reputation: 63

You can try:

import * as CryptoJS from 'crypto-js';

Upvotes: 0

I_Al-thamary
I_Al-thamary

Reputation: 4003

You can generate random without using Math.random

var _ = require('lodash');
var CryptoJS = require("crypto-js");
var p;
function randomString(length) {
  var text = "";
  var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

 var text= _.sampleSize(possible , length).join('');

  return text;
}

function setWindow(text){
    console.log('text',text);
     p = randomString(10)
    console.log('p',p)
    var c = CryptoJS.AES.encrypt(text,p).toString();
    console.log('crypted',c+p)
    return c+p;
  }



var ciphertext=setWindow("plain text");
var bytes  = CryptoJS.AES.decrypt(ciphertext.toString(), p);
var plaintext = bytes.toString(CryptoJS.enc.Utf8);

console.log("decrypte",plaintext);

function randomString(length) {
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for (var i = 0; i < length; i++)
      text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
  }




function setWindow(text){
 

    console.log('text',text);
    var p = randomString(10)
    console.log('p',p)
    var c =CryptoJS.AES.encrypt(text,p);
    console.log('crypted',c+p)
    return c+p;
}
var text="Plain Text";
setWindow(text);    
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.min.js"></script>

The code here:https://repl.it/@ibrahimth/LastSatisfiedBrain

Upvotes: 0

Related Questions