TypeError:无法读取未定义的属性“随机”-crypto-js

时间:2019-01-24 08:14:58

标签: javascript reactjs cryptojs

我在crypto-js中使用reactjs,并且在localhost上一切正常。 但是在使用chrome的服务器上,我收到此错误消息:

TypeError: Cannot read property 'random' of undefined

在Firefox上:

TypeError: "r is undefined"

我的代码:

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 !

我的功能:

  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",

我不知道我的问题在哪里!我删除了node_modules,但是遇到了同样的错误。 我的网站: http://posweb.ccg24.com/signin

已更新

  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;
  }

1 个答案:

答案 0 :(得分:0)

您可以不使用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>

此处的代码:https://repl.it/@ibrahimth/LastSatisfiedBrain