Search code examples
javascriptvue.jscryptojs

Cannot read property 'HmacSHA256' of undefined


I am trying to encrypt an id so I can use as params in vue.js using crypto-js, but I keep getting this error. Cannot read property 'HmacSHA256' of undefined when I tried ASE and MD5 I had same error, What am I not doing right? this is my code

//in main.js
import CryptoJS from 'crypto-js'
Vue.use(CryptoJS)

//im my component
goToEvent (singleEvent) {
  const id = this.CryptoJS.HmacSHA256(singleEvent.id, 'mySecreteKey').toString(this.CryptoJS.enc.Hex)
  this.$store.commit('SET_SELECTED_EVENT', singleEvent)
  this.$router.push(`/admin/events/event/${id}`)
}

Solution

  • thanks for all your help, what I realized was that I had to pass my value to json string, I also had to add some few stuffs to get a value that is url friendly. this is my final solution

    import CryptoJS from 'crypto-js'
    
    const key = 'mysecrete'
    
    
    
     // encryption
       export function Encrypt (text) {
        const b64 = CryptoJS.AES.encrypt(JSON.stringify(text), key).toString()
          const e64 = CryptoJS.enc.Base64.parse(b64)
          return e64.toString(CryptoJS.enc.Hex)
        }
    // decryption
    export function Decrypt (text) {
      const reb64 = CryptoJS.enc.Hex.parse(text)
      const bytes = reb64.toString(CryptoJS.enc.Base64)
      const decrypt = CryptoJS.AES.decrypt(bytes, key)
      return decrypt.toString(CryptoJS.enc.Utf8)
    }
    

    now I can import it in any component