Search code examples
javascriptvue.jscryptojs

undefined CryptoJS in vue


https://github.com/brix/crypto-js

i have install cryptoJs using npm i crypto-js

but how do i use it on my project ? when i write this code

// Decrypt
var bytes  = CryptoJS.AES.decrypt(ciphertext, 'secret key 123');

var originalText = bytes.toString(CryptoJS.enc.Utf8);

console.log(originalText); 

but it show an error said that CryptoJS is undefined

here is my code

<script>
import CryptoJS from 'crypto-js'
require('crypto-js')

export default {
  name: "AnswerQuestionnaire",
  components:{
  
  },
  props: {
  
  },
  data() {
    return {
     
    }
  },

  created(){
    this.CryptoJS.AES.decrypt("zU5jEPwQSm2P0X33jgH6sg==", "sB7b5q4fp0G59R9t").toString(this.CryptoJS.enc.Utf8)
      
  },
  mounted(){
    
  }
};

this is the eror

VM820424:1 Uncaught ReferenceError: CryptoJs is not defined
    at eval (eval at created


Solution

  • At first, you have to run npm install crypto-js in Vue terminal.

    Then, you have to import or require crypto first

    <script>
    import CryptoJS from 'crypto-js';
    export default {
      created() {
        var bytes  = CryptoJS.AES.decrypt(ciphertext, 'secret key 123');
    
        var originalText = bytes.toString(CryptoJS.enc.Utf8);
    
        console.log(originalText); 
      }
    }
    
    </script>