Undefined cryptojs when importing crypto-js in Nest Js

Viewed 37

I am importing crypto-js in a Nestjs service, and I run into this error


TypeError: Cannot read properties of undefined (reading 'enc') at CryptoUtilsService.decryptAESHex


The code:

import { Injectable, Logger } from '@nestjs/common';
import { CmacDto, Crc32Dto } from './dto';
import CryptoJS from 'crypto-js';
import { AesDecryptDto } from './dto/aesDecrypt.dto';

@Injectable()
export class CryptoUtilsService {
    private readonly logger = new Logger(CryptoUtilsService.name);
    
    decryptAESHex(data: AesDecryptDto) {
        let keyHex = CryptoJS.enc.Hex.parse(data.key);
        let ivHex = CryptoJS.enc.Hex.parse(data.iv);

        let encryptedWordArray = CryptoJS.enc.Hex.parse(
            data.encryptedData.toUpperCase(),
        );

        let encString = CryptoJS.enc.Base64.stringify(encryptedWordArray);
        // console.log("before decryption: ", encryptedString.toUpperCase(), encString);

        let decryptedResp = CryptoJS.AES.decrypt(encString, keyHex, {
            iv: ivHex,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.NoPadding,
        });
        // console.log("after decryption:: ", decryptedResp)

        return CryptoJS.enc.Hex.stringify(decryptedResp).toUpperCase();
    }
}

I have installed crypto-js and @types/crypto-js module. Also tried deleting the node_modules and installing again. It seems to work fine on other node projects without typescript. I cannot figure out what is going wrong here.

1 Answers
Related